

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

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

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

次のコード例は、 AWS Software Development Kit (SDK) AWS CloudTrail で を使用する方法を示しています。

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

**その他のリソース**
+  **[ CloudTrail デベロッパーガイド](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html)** – CloudTrail に関する詳細情報。
+ **[ CloudTrail API リファレンス](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/Welcome.html)** — 使用可能なすべての CloudTrail アクションに関する詳細。
+ **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23)** – カテゴリまたは全文検索でフィルタリングできるコード例。
+ **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** – 完全なコードを優先言語で含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Contents**
+ [基本](cloudtrail_code_examples_basics.md)
  + [アクション](cloudtrail_code_examples_actions.md)
    + [`CreateTrail`](cloudtrail_example_cloudtrail_CreateTrail_section.md)
    + [`DeleteTrail`](cloudtrail_example_cloudtrail_DeleteTrail_section.md)
    + [`DescribeTrail`](cloudtrail_example_cloudtrail_DescribeTrail_section.md)
    + [`DescribeTrails`](cloudtrail_example_cloudtrail_DescribeTrails_section.md)
    + [`GetTrailStatus`](cloudtrail_example_cloudtrail_GetTrailStatus_section.md)
    + [`ListTrails`](cloudtrail_example_cloudtrail_ListTrails_section.md)
    + [`LookupEvents`](cloudtrail_example_cloudtrail_LookupEvents_section.md)
    + [`StartLogging`](cloudtrail_example_cloudtrail_StartLogging_section.md)
    + [`StopLogging`](cloudtrail_example_cloudtrail_StopLogging_section.md)
    + [`UpdateTrail`](cloudtrail_example_cloudtrail_UpdateTrail_section.md)

# SDK を使用した CloudTrail の基本的な例 AWS SDKs
<a name="cloudtrail_code_examples_basics"></a>

次のコード例は、 SDKs AWS CloudTrail で AWS の基本を使用する方法を示しています。

**Contents**
+ [アクション](cloudtrail_code_examples_actions.md)
  + [`CreateTrail`](cloudtrail_example_cloudtrail_CreateTrail_section.md)
  + [`DeleteTrail`](cloudtrail_example_cloudtrail_DeleteTrail_section.md)
  + [`DescribeTrail`](cloudtrail_example_cloudtrail_DescribeTrail_section.md)
  + [`DescribeTrails`](cloudtrail_example_cloudtrail_DescribeTrails_section.md)
  + [`GetTrailStatus`](cloudtrail_example_cloudtrail_GetTrailStatus_section.md)
  + [`ListTrails`](cloudtrail_example_cloudtrail_ListTrails_section.md)
  + [`LookupEvents`](cloudtrail_example_cloudtrail_LookupEvents_section.md)
  + [`StartLogging`](cloudtrail_example_cloudtrail_StartLogging_section.md)
  + [`StopLogging`](cloudtrail_example_cloudtrail_StopLogging_section.md)
  + [`UpdateTrail`](cloudtrail_example_cloudtrail_UpdateTrail_section.md)

# SDK を使用した CloudTrail のアクション AWS SDKs
<a name="cloudtrail_code_examples_actions"></a>

次のコード例は、 AWS SDKs を使用して個々の CloudTrail アクションを実行する方法を示しています。それぞれの例には、GitHub へのリンクがあり、そこにはコードの設定と実行に関する説明が記載されています。

 以下の例には、最も一般的に使用されるアクションのみ含まれています。詳細な一覧については、「[AWS CloudTrail API リファレンス](https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/Welcome.html)」を参照してください。

**Topics**
+ [`CreateTrail`](cloudtrail_example_cloudtrail_CreateTrail_section.md)
+ [`DeleteTrail`](cloudtrail_example_cloudtrail_DeleteTrail_section.md)
+ [`DescribeTrail`](cloudtrail_example_cloudtrail_DescribeTrail_section.md)
+ [`DescribeTrails`](cloudtrail_example_cloudtrail_DescribeTrails_section.md)
+ [`GetTrailStatus`](cloudtrail_example_cloudtrail_GetTrailStatus_section.md)
+ [`ListTrails`](cloudtrail_example_cloudtrail_ListTrails_section.md)
+ [`LookupEvents`](cloudtrail_example_cloudtrail_LookupEvents_section.md)
+ [`StartLogging`](cloudtrail_example_cloudtrail_StartLogging_section.md)
+ [`StopLogging`](cloudtrail_example_cloudtrail_StopLogging_section.md)
+ [`UpdateTrail`](cloudtrail_example_cloudtrail_UpdateTrail_section.md)

# AWS SDK または CLI `CreateTrail`で を使用する
<a name="cloudtrail_example_cloudtrail_CreateTrail_section"></a>

次のサンプルコードは、`CreateTrail` を使用する方法を説明しています。

------
#### [ C\$1\$1 ]

**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)」を参照してください。

------
#### [ CLI ]

**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)」を参照してください。

------
#### [ PowerShell ]

**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)」を参照してください。

**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)」を参照してください。

------
#### [ Ruby ]

**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)」を参照してください。

------

# AWS SDK または CLI `DeleteTrail`で を使用する
<a name="cloudtrail_example_cloudtrail_DeleteTrail_section"></a>

次のサンプルコードは、`DeleteTrail` を使用する方法を説明しています。

------
#### [ C\$1\$1 ]

**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)」を参照してください。

------
#### [ CLI ]

**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)」を参照してください。

------
#### [ PowerShell ]

**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)」を参照してください。

**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)」を参照してください。

------
#### [ Ruby ]

**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)」を参照してください。

------

# AWS SDK `DescribeTrail`で を使用する
<a name="cloudtrail_example_cloudtrail_DescribeTrail_section"></a>

次の例は、`DescribeTrail` を使用する方法を説明しています。

------
#### [ C\$1\$1 ]

**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)」を参照してください。

------

# CLI で `DescribeTrails` を使用する
<a name="cloudtrail_example_cloudtrail_DescribeTrails_section"></a>

次のサンプルコードは、`DescribeTrails` を使用する方法を説明しています。

------
#### [ CLI ]

**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)」を参照してください。

------
#### [ PowerShell ]

**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)」を参照してください。

**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)」を参照してください。

------

# CLI で `GetTrailStatus` を使用する
<a name="cloudtrail_example_cloudtrail_GetTrailStatus_section"></a>

次のサンプルコードは、`GetTrailStatus` を使用する方法を説明しています。

------
#### [ CLI ]

**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)」を参照してください。

------
#### [ PowerShell ]

**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)」を参照してください。

**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)」を参照してください。

------

# AWS SDK `ListTrails`で を使用する
<a name="cloudtrail_example_cloudtrail_ListTrails_section"></a>

次の例は、`ListTrails` を使用する方法を説明しています。

------
#### [ Ruby ]

**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)」を参照してください。**

------

# AWS SDK または CLI `LookupEvents`で を使用する
<a name="cloudtrail_example_cloudtrail_LookupEvents_section"></a>

次のサンプルコードは、`LookupEvents` を使用する方法を説明しています。

------
#### [ C\$1\$1 ]

**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)」を参照してください。

------
#### [ CLI ]

**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)」を参照してください。

------
#### [ PowerShell ]

**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)」を参照してください。

**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)」を参照してください。

------
#### [ Ruby ]

**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)」を参照してください。

------

# CLI で `StartLogging` を使用する
<a name="cloudtrail_example_cloudtrail_StartLogging_section"></a>

次のサンプルコードは、`StartLogging` を使用する方法を説明しています。

------
#### [ CLI ]

**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)」を参照してください。

------
#### [ PowerShell ]

**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)」を参照してください。

**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)」を参照してください。

------

# CLI で `StopLogging` を使用する
<a name="cloudtrail_example_cloudtrail_StopLogging_section"></a>

次のサンプルコードは、`StopLogging` を使用する方法を説明しています。

------
#### [ CLI ]

**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)」を参照してください。

------
#### [ PowerShell ]

**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)」を参照してください。

**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)」を参照してください。

------

# CLI で `UpdateTrail` を使用する
<a name="cloudtrail_example_cloudtrail_UpdateTrail_section"></a>

次のサンプルコードは、`UpdateTrail` を使用する方法を説明しています。

------
#### [ CLI ]

**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)」を参照してください。

------
#### [ PowerShell ]

**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 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)」を参照してください。

------