

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

# Amazon S3 소스에 대한 EventBridge 규칙 생성(CloudFormation 템플릿)
<a name="create-cloudtrail-S3-source-cfn"></a>

 CloudFormation 를 사용하여 규칙을 생성하려면 다음과 같이 템플릿을 업데이트합니다.<a name="proc-cfn-event-s3-createrule"></a>

**Amazon S3가 이벤트 소스이고 CodePipeline이 대상인 EventBridge 규칙을 생성하고 권한 정책을 적용하려면**

1. 템플릿의에서 `AWS::IAM::Role` CloudFormation 리소스를 `Resources`사용하여 이벤트가 파이프라인을 시작하도록 허용하는 IAM 역할을 구성합니다. 이 항목은 두 가지 정책을 사용하는 역할을 만듭니다.
   + 첫 번째 정책은 가 역할을 수임하도록 허용합니다.
   + 두 번째 정책은 파이프라인을 시작할 권한을 부여합니다.

   **이렇게 변경하는 이유는 무엇입니까?** `AWS::IAM::Role` 리소스를 추가하면 CloudFormation 가 EventBridge에 대한 권한을 생성할 수 있습니다. 이 리소스는 CloudFormation 스택에 추가됩니다.

------
#### [ YAML ]

   ```
     EventRole:
       Type: AWS::IAM::Role
       Properties:
         AssumeRolePolicyDocument:
           Version: 2012-10-17		 	 	 
           Statement:
             -
               Effect: Allow
               Principal:
                 Service:
                   - events.amazonaws.com
               Action: sts:AssumeRole
         Path: /
         Policies:
           -
             PolicyName: eb-pipeline-execution
             PolicyDocument:
               Version: 2012-10-17		 	 	 
               Statement:
                 -
                   Effect: Allow
                   Action: codepipeline:StartPipelineExecution
                   Resource: !Join [ '', [ 'arn:aws:codepipeline:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':', !Ref AppPipeline ] ]
   
   
   ...
   ```

------
#### [ JSON ]

   ```
     "EventRole": {
       "Type": "AWS::IAM::Role",
       "Properties": {
         "AssumeRolePolicyDocument": {
           "Version": "2012-10-17",		 	 	 
           "Statement": [
             {
               "Effect": "Allow",
               "Principal": {
                 "Service": [
                   "events.amazonaws.com"
                 ]
               },
               "Action": "sts:AssumeRole"
             }
           ]
         },
         "Path": "/",
         "Policies": [
           {
             "PolicyName": "eb-pipeline-execution",
             "PolicyDocument": {
               "Version": "2012-10-17",		 	 	 
               "Statement": [
                 {
                   "Effect": "Allow",
                   "Action": "codepipeline:StartPipelineExecution",
                   "Resource": {
                     "Fn::Join": [
                       "",
                       [
                         "arn:aws:codepipeline:",
                         {
                           "Ref": "AWS::Region"
                         },
                         ":",
                         {
                           "Ref": "AWS::AccountId"
                         },
                         ":",
                         {
                           "Ref": "AppPipeline"
                         }
                       ]
                     ]
   
   ...
   ```

------

1. `AWS::Events::Rule` CloudFormation 리소스를 사용하여 EventBridge 규칙을 추가합니다. 이 이벤트 패턴은 Amazon S3 소스 버킷의 `CopyObject`, `PutObject` 및 `CompleteMultipartUpload`를 모니터링하는 이벤트를 생성합니다. 또한 파이프라인 대상도 포함하세요. 이 규칙은 `CopyObject`, `PutObject` 또는 `CompleteMultipartUpload` 발생 시 대상 파이프라인에서 `StartPipelineExecution`을 호출합니다.

   **이렇게 변경하는 이유는 무엇입니까?** `AWS::Events::Rule` 리소스를 추가 CloudFormation 하면가 이벤트를 생성할 수 있습니다. 이 리소스는 CloudFormation 스택에 추가됩니다.

------
#### [ YAML ]

   ```
     EventRule:
       Type: AWS::Events::Rule
       Properties:
         EventPattern:
           source:
             - aws.s3
           detail-type:
             - 'AWS API Call via CloudTrail'
           detail:
             eventSource:
               - s3.amazonaws.com
             eventName:
               - CopyObject
               - PutObject
               - CompleteMultipartUpload
             requestParameters:
               bucketName:
                 - !Ref SourceBucket
               key:
                 - !Ref SourceObjectKey
         Targets:
           -
             Arn:
               !Join [ '', [ 'arn:aws:codepipeline:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':', !Ref AppPipeline ] ]
             RoleArn: !GetAtt EventRole.Arn
             Id: codepipeline-AppPipeline
   
   
   ...
   ```

------
#### [ JSON ]

   ```
     "EventRule": {
       "Type": "AWS::Events::Rule",
       "Properties": {
         "EventPattern": {
           "source": [
             "aws.s3"
           ],
           "detail-type": [
             "AWS API Call via CloudTrail"
           ],
           "detail": {
             "eventSource": [
               "s3.amazonaws.com"
             ],
             "eventName": [
               "CopyObject",
               "PutObject",
               "CompleteMultipartUpload"
             ],
             "requestParameters": {
               "bucketName": [
                 {
                   "Ref": "SourceBucket"
                 }
               ],
               "key": [
                 {
                   "Ref": "SourceObjectKey"
                 }
               ]
             }
           }
         },
         "Targets": [
           {
             "Arn": {
               "Fn::Join": [
                 "",
                 [
                   "arn:aws:codepipeline:",
                   {
                     "Ref": "AWS::Region"
                   },
                   ":",
                   {
                     "Ref": "AWS::AccountId"
                   },
                   ":",
                   {
                     "Ref": "AppPipeline"
                   }
                 ]
               ]
             },
             "RoleArn": {
               "Fn::GetAtt": [
                 "EventRole",
                 "Arn"
               ]
             },
             "Id": "codepipeline-AppPipeline"
           }
         ]
       }
     }
   },
   
   ...
   ```

------

1. 이 코드 조각을 첫 번째 템플릿에 추가하여 교차 스택 기능을 허용하세요.

------
#### [ YAML ]

   ```
   Outputs:
     SourceBucketARN:
       Description: "S3 bucket ARN that Cloudtrail will use"
       Value: !GetAtt SourceBucket.Arn
       Export:
         Name: SourceBucketARN
   ```

------
#### [ JSON ]

   ```
     "Outputs" : {
       "SourceBucketARN" : {
         "Description" : "S3 bucket ARN that Cloudtrail will use",
         "Value" : { "Fn::GetAtt": ["SourceBucket", "Arn"] },
         "Export" : {
           "Name" : "SourceBucketARN"
         }
       }
   
   ...
   ```

------

1. (선택 사항) 특정 이미지 ID에 대해 소스 오버라이드를 적용하는 입력 변환기를 구성하려면 다음 YAML 스니펫을 사용합니다. 다음 예제에서는 다음과 같은 경우 재정의를 구성합니다.
   + 이 예제에서 `actionName`, `Source`는 소스 이벤트에서 파생되지 않은 파이프라인 생성 시 정의된 동적 값입니다.
   + 이 예제에서 `revisionType`, `S3_OBJECT_VERSION_ID`는 소스 이벤트에서 파생되지 않은 파이프라인 생성 시 정의된 동적 값입니다.
   + 이 예제에서 `revisionValue`, <{{revisionValue}}>는 소스 이벤트 변수에서 파생됩니다.

   ```
   ---
   Rule: my-rule
   Targets:
   - Id: MyTargetId
     Arn: {{pipeline-ARN}}
     InputTransformer:
       InputPathsMap:
         revisionValue: "$.detail.object.version-id"
       InputTemplate:
         sourceRevisions:
           actionName: Source
           revisionType: S3_OBJECT_VERSION_ID
           revisionValue: '<{{revisionValue}}>'
   ```

1. 업데이트된 템플릿을 로컬 컴퓨터에 저장하고 CloudFormation 콘솔을 엽니다.

1. 스택을 선택한 후 **현재 스택에 대한 변경 세트 만들기**를 선택합니다.

1. 업데이트된 템플릿을 업로드한 후 CloudFormation에 나열된 변경 사항을 확인합니다. 이는 스택에 적용될 변경 사항입니다. 목록에 새로운 리소스가 표시됩니다.

1. **실행**을 선택합니다.<a name="proc-cfn-flag-s3"></a>

**파이프라인의 PollForSourceChanges 파라미터를 편집하려면**
**중요**  
이 방법으로 파이프라인을 생성할 때 명시적으로 false로 설정되지 않은 경우 `PollForSourceChanges` 파라미터 기본값은 true입니다. 이벤트 기반 변경 감지를 추가할 때는 출력에 파라미터를 추가하고 false로 설정하여 폴링을 비활성화해야 합니다. 그렇지 않으면 파이프라인이 단일 소스 변경 시 두 번 시작됩니다. 자세한 내용은 [`PollForSourceChanges` 파라미터의 유효한 설정](PollForSourceChanges-defaults.md)을 참조하세요.
+ 템플릿에서 `PollForSourceChanges`를 `false`로 변경합니다. `PollForSourceChanges`를 파이프라인 정의에 포함하지 않은 경우 추가하고 `false`로 설정하세요.

  **이렇게 변경하는 이유는 무엇입니까?** `PollForSourceChanges`를 `false`로 변경하면 정기적 확인이 비활성화되어 이벤트 기반 변경 탐지만 사용할 수 있습니다.

------
#### [ YAML ]

  ```
            Name: Source
            Actions: 
              - 
                Name: SourceAction
                ActionTypeId: 
                  Category: Source
                  Owner: AWS
                  Version: 1
                  Provider: S3
                OutputArtifacts: 
                  - Name: SourceOutput
                Configuration: 
                  S3Bucket: !Ref SourceBucket
                  S3ObjectKey: !Ref SourceObjectKey
                  {{PollForSourceChanges: false}}
                RunOrder: 1
  ```

------
#### [ JSON ]

  ```
   {
      "Name": "SourceAction",
      "ActionTypeId": {
        "Category": "Source",
        "Owner": "AWS",
        "Version": 1,
        "Provider": "S3"
      },
      "OutputArtifacts": [
        {
          "Name": "SourceOutput"
        }
      ],
      "Configuration": {
        "S3Bucket": {
          "Ref": "SourceBucket"
        },
        "S3ObjectKey": {
          "Ref": "SourceObjectKey"
        },
        "PollForSourceChanges": {{false}}
      },
      "RunOrder": 1
    }
  ```

------<a name="proc-cfn-event-s3-createtrail"></a>

**Amazon S3 파이프라인의 CloudTrail 리소스를 위한 두 번째 템플릿을 만들려면**
+ 별도의 템플릿에서 `Resources`, `AWS::S3::Bucket` `AWS::S3::BucketPolicy`및 `AWS::CloudTrail::Trail` CloudFormation 리소스를 사용하여 CloudTrail에 대한 간단한 버킷 정의 및 추적을 제공합니다.

  **이렇게 변경하는 이유는 무엇입니까?** 현재 계정당 5개의 추적으로 제한되어 있으므로 CloudTrail 추적을 별도로 생성하고 관리해야 합니다. ([의 제한 AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/WhatIsCloudTrail-Limits.html) 참조) 하지만 단일 추적에 많은 Amazon S3 버킷을 포함할 수 있으므로 추적을 한 번 생성한 다음 필요에 따라 다른 파이프라인용 Amazon S3 버킷을 추가할 수 있습니다. 다음 내용을 두 번째 샘플 템플릿 파일에 붙여넣습니다.

------
#### [ YAML ]

  ```
  ###################################################################################
  # Prerequisites: 
  #   - S3 SourceBucket and SourceObjectKey must exist
  ###################################################################################
  
  Parameters:
    SourceObjectKey:
      Description: 'S3 source artifact'
      Type: String
      Default: SampleApp_Linux.zip
  
  Resources:
    AWSCloudTrailBucketPolicy:
      Type: AWS::S3::BucketPolicy
      Properties:
        Bucket: !Ref AWSCloudTrailBucket
        PolicyDocument:
          Version: 2012-10-17		 	 	 
          Statement:
            -
              Sid: AWSCloudTrailAclCheck
              Effect: Allow
              Principal:
                Service:
                  - cloudtrail.amazonaws.com
              Action: s3:GetBucketAcl
              Resource: !GetAtt AWSCloudTrailBucket.Arn
            -
              Sid: AWSCloudTrailWrite
              Effect: Allow
              Principal:
                Service:
                  - cloudtrail.amazonaws.com
              Action: s3:PutObject
              Resource: !Join [ '', [ !GetAtt AWSCloudTrailBucket.Arn, '/AWSLogs/', !Ref 'AWS::AccountId', '/*' ] ]
              Condition: 
                StringEquals:
                  s3:x-amz-acl: bucket-owner-full-control
    AWSCloudTrailBucket:
      Type: AWS::S3::Bucket
      DeletionPolicy: Retain
    AwsCloudTrail:
      DependsOn:
        - AWSCloudTrailBucketPolicy
      Type: AWS::CloudTrail::Trail
      Properties:
        S3BucketName: !Ref AWSCloudTrailBucket
        EventSelectors:
          -
            DataResources:
              -
                Type: AWS::S3::Object
                Values:
                  - !Join [ '', [ !ImportValue SourceBucketARN, '/', !Ref SourceObjectKey ] ]
            ReadWriteType: WriteOnly
            IncludeManagementEvents: false
        IncludeGlobalServiceEvents: true
        IsLogging: true
        IsMultiRegionTrail: true
  
  
  ...
  ```

------
#### [ JSON ]

  ```
  {
    "Parameters": {
      "SourceObjectKey": {
        "Description": "S3 source artifact",
        "Type": "String",
        "Default": "SampleApp_Linux.zip"
      }
    },
    "Resources": {
      "AWSCloudTrailBucket": {
        "Type": "AWS::S3::Bucket",
          "DeletionPolicy": "Retain"
      },
      "AWSCloudTrailBucketPolicy": {
        "Type": "AWS::S3::BucketPolicy",
        "Properties": {
          "Bucket": {
            "Ref": "AWSCloudTrailBucket"
          },
          "PolicyDocument": {
            "Version": "2012-10-17",		 	 	 
            "Statement": [
              {
                "Sid": "AWSCloudTrailAclCheck",
                "Effect": "Allow",
                "Principal": {
                  "Service": [
                    "cloudtrail.amazonaws.com"
                  ]
                },
                "Action": "s3:GetBucketAcl",
                "Resource": {
                  "Fn::GetAtt": [
                    "AWSCloudTrailBucket",
                    "Arn"
                  ]
                }
              },
              {
                "Sid": "AWSCloudTrailWrite",
                "Effect": "Allow",
                "Principal": {
                  "Service": [
                    "cloudtrail.amazonaws.com"
                  ]
                },
                "Action": "s3:PutObject",
                "Resource": {
                  "Fn::Join": [
                    "",
                    [
                      {
                        "Fn::GetAtt": [
                          "AWSCloudTrailBucket",
                          "Arn"
                        ]
                      },
                      "/AWSLogs/",
                      {
                        "Ref": "AWS::AccountId"
                      },
                      "/*"
                    ]
                  ]
                },
                "Condition": {
                  "StringEquals": {
                    "s3:x-amz-acl": "bucket-owner-full-control"
                  }
                }
              }
            ]
          }
        }
      },
      "AwsCloudTrail": {
        "DependsOn": [
          "AWSCloudTrailBucketPolicy"
        ],
        "Type": "AWS::CloudTrail::Trail",
        "Properties": {
          "S3BucketName": {
            "Ref": "AWSCloudTrailBucket"
          },
          "EventSelectors": [
            {
              "DataResources": [
                {
                  "Type": "AWS::S3::Object",
                  "Values": [
                    {
                      "Fn::Join": [
                        "",
                        [
                          {
                            "Fn::ImportValue": "SourceBucketARN"
                          },
                          "/",
                          {
                            "Ref": "SourceObjectKey"
                          }
                        ]
                      ]
                    }
                  ]
                }
              ],
              "ReadWriteType": "WriteOnly",
              "IncludeManagementEvents": false
            }
          ],
          "IncludeGlobalServiceEvents": true,
          "IsLogging": true,
          "IsMultiRegionTrail": true
        }
      }
    }
  }
  
  ...
  ```

------