

Doc AWS SDK 예제 GitHub 리포지토리에서 더 많은 SDK 예제를 사용할 수 있습니다. [AWS](https://github.com/awsdocs/aws-doc-sdk-examples) 

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# AWS SDKs를 사용한 CloudTrail 코드 예제
<a name="cloudtrail_code_examples"></a>

다음 코드 예제에서는 AWS 소프트웨어 개발 키트(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)

# AWS SDKs 사용한 CloudTrail의 기본 예제
<a name="cloudtrail_code_examples_basics"></a>

다음 코드 예제에서는 AWS CloudTrail SDKs에서의 기본 사항을 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)

# AWS SDKs를 사용한 CloudTrail 작업
<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'으로 전송됩니다. 이 예제에서는 스플래팅을 사용하여 cmdlet에 파라미터 값을 제공합니다.**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(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'으로 전송됩니다. 이 예제에서는 스플래팅을 사용하여 cmdlet에 파라미터 값을 제공합니다.**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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 명령 참조의 [DescribeTrail](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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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일 동안 발생한 모든 이벤트를 반환합니다. 기본적으로 cmdlet은 모든 이벤트를 전달하기 위해 자동으로 여러 번의 직접 호출을 사용하며, 서비스에서 추가 데이터를 사용할 수 없다고 표시되면 종료됩니다.**  

```
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 Cmdlet 참조(V4)*의 [LookupEvents](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 지난 7일 동안 발생한 모든 이벤트를 반환합니다. 기본적으로 cmdlet은 모든 이벤트를 전달하기 위해 자동으로 여러 번의 직접 호출을 사용하며, 서비스에서 추가 데이터를 사용할 수 없다고 표시되면 종료됩니다.**  

```
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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(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 Cmdlet 참조(V5)*의 [UpdateTrail](https://docs.aws.amazon.com/powershell/v5/reference)을 참조하세요.

------