이벤트 기반 변경 감지를 사용하도록 폴링 파이프라인 마이그레이션 - AWS CodePipeline

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

이벤트 기반 변경 감지를 사용하도록 폴링 파이프라인 마이그레이션

AWS CodePipeline 코드 변경이 있을 때마다 파이프라인을 시작하는 것을 포함하여 완전하고 end-to-end 지속적인 전송을 지원합니다. 코드 변경 시 파이프라인을 시작하는 방법은 이벤트 기반 변경 감지 및 폴링 두 가지가 있습니다. 파이프라인에는 이벤트 기반 변경 감지를 사용하는 것이 좋습니다.

여기에 포함된 절차를 사용하여 폴링 파이프라인을 파이프라인의 이벤트 기반 변경 감지 방법으로 마이그레이션(업데이트)하세요.

파이프라인에 권장되는 이벤트 기반 변경 감지 방법은 파이프라인 소스 (예:) 에 따라 결정됩니다. CodeCommit 예를 들어 이 경우 폴링 파이프라인을 를 사용하여 이벤트 기반 변경 감지로 마이그레이션해야 합니다. EventBridge

폴링 파이프라인을 마이그레이션하는 방법

폴링 파이프라인을 마이그레이션하려면 폴링 파이프라인을 결정한 다음 권장되는 이벤트 기반 변경 감지 방법을 결정하세요.

  • 계정의 폴링 파이프라인 보기의 단계를 사용하여 폴링 파이프라인을 확인하세요.

  • 표에서 파이프라인 소스 유형을 찾은 다음 폴링 파이프라인을 마이그레이션하는 데 사용할 구현이 포함된 절차를 선택합니다. 각 섹션에는 OR 사용과 같은 여러 마이그레이션 방법이 포함되어 있습니다. CLI AWS CloudFormation

파이프라인을 권장되는 변경 감지 방법으로 마이그레이션하는 방법
파이프라인 소스 권장되는 이벤트 기반 탐지 방법 마이그레이션 절차
AWS CodeCommit EventBridge (권장). 소스가 있는 폴링 파이프라인을 마이그레이션하세요. CodeCommit 을 참조하세요.
Amazon S3 EventBridge 및 이벤트 알림을 위한 버킷 활성화 (권장). 이벤트용으로 활성화된 S3 소스를 사용하여 폴링 파이프라인 마이그레이션을 참조하세요.
Amazon S3 EventBridge 그리고 AWS CloudTrail 트레일. S3 소스 및 트레일을 사용하여 폴링 파이프라인을 마이그레이션하십시오. CloudTrail 을 참조하세요.
GitHub 버전 1 연결(권장) GitHub 버전 1 소스 작업의 폴링 파이프라인을 연결로 마이그레이션합니다.을 참조하세요.
GitHub 버전 1 Webhook GitHub 버전 1 소스 작업의 폴링 파이프라인을 웹후크로 마이그레이션합니다.을 참조하세요.
중요

GitHub버전 1 작업이 포함된 파이프라인 등 해당하는 파이프라인 작업 구성 업데이트의 경우 소스 작업의 구성 내에서 PollForSourceChanges 매개변수를 false로 명시적으로 설정하여 파이프라인의 폴링을 중지해야 합니다. 따라서 규칙을 구성하고 파라미터를 생략하는 등의 방법으로 이벤트 기반 변경 감지와 폴링을 모두 포함하는 파이프라인을 잘못 구성할 수 있습니다. EventBridge PollForSourceChanges 이 결과 파이프라인 실행이 중복되고 파이프라인이 기본적으로 이벤트 기반 파이프라인보다 훨씬 낮은 총 폴링 파이프라인 수의 제한에 개수가 기록됩니다. 자세한 내용은 할당량 입력 AWS CodePipeline 단원을 참조하십시오.

계정의 폴링 파이프라인 보기

첫 번째 단계로 다음 스크립트 중 하나를 사용하여 계정의 어떤 파이프라인을 폴링용으로 구성했는지 확인하세요. 다음은 이벤트 기반 변경 감지로 마이그레이션하기 위한 파이프라인입니다.

계정의 폴링 파이프라인 보기(스크립트)

다음 단계에 따라 스크립트를 사용하여 계정에서 폴링을 사용하는 파이프라인을 확인하세요.

  1. 터미널 창을 열고 다음 중 하나를 수행합니다.

    • 다음 명령을 실행하여 .sh라는 새 스크립트를 생성합니다. PollingPipelinesExtractor

      vi PollingPipelinesExtractor.sh
    • Python 스크립트를 사용하려면 다음 명령을 PollingPipelinesExtractor실행하여.py라는 새 Python 스크립트를 만드십시오.

      vi PollingPipelinesExtractor.py
  2. 다음 코드를 복사하여 PollingPipelinesExtractor스크립트에 붙여넣습니다. 다음 중 하나를 수행합니다.

    • 다음 코드를 PollingPipelinesExtractor복사하여.sh 스크립트에 붙여넣습니다.

      #!/bin/bash set +x POLLING_PIPELINES=() LAST_EXECUTED_DATES=() NEXT_TOKEN=null HAS_NEXT_TOKEN=true if [[ $# -eq 0 ]] ; then echo 'Please provide region name' exit 0 fi REGION=$1 while [ "$HAS_NEXT_TOKEN" != "false" ]; do if [ "$NEXT_TOKEN" != "null" ]; then LIST_PIPELINES_RESPONSE=$(aws codepipeline list-pipelines --region $REGION --next-token $NEXT_TOKEN) else LIST_PIPELINES_RESPONSE=$(aws codepipeline list-pipelines --region $REGION) fi LIST_PIPELINES=$(jq -r '.pipelines[].name' <<< "$LIST_PIPELINES_RESPONSE") NEXT_TOKEN=$(jq -r '.nextToken' <<< "$LIST_PIPELINES_RESPONSE") if [ "$NEXT_TOKEN" == "null" ]; then HAS_NEXT_TOKEN=false fi for pipline_name in $LIST_PIPELINES do PIPELINE=$(aws codepipeline get-pipeline --name $pipline_name --region $REGION) HAS_POLLABLE_ACTIONS=$(jq '.pipeline.stages[].actions[] | select(.actionTypeId.category == "Source") | select(.actionTypeId.owner == ("ThirdParty","AWS")) | select(.actionTypeId.provider == ("GitHub","S3","CodeCommit")) | select(.configuration.PollForSourceChanges == ("true",null))' <<< "$PIPELINE") if [ ! -z "$HAS_POLLABLE_ACTIONS" ]; then POLLING_PIPELINES+=("$pipline_name") PIPELINE_EXECUTIONS=$(aws codepipeline list-pipeline-executions --pipeline-name $pipline_name --region $REGION) LAST_EXECUTION=$(jq -r '.pipelineExecutionSummaries[0]' <<< "$PIPELINE_EXECUTIONS") if [ "$LAST_EXECUTION" != "null" ]; then LAST_EXECUTED_TIMESTAMP=$(jq -r '.startTime' <<< "$LAST_EXECUTION") LAST_EXECUTED_DATE="$(date -r ${LAST_EXECUTED_TIMESTAMP%.*})" else LAST_EXECUTED_DATE="Not executed in last year" fi LAST_EXECUTED_DATES+=("$LAST_EXECUTED_DATE") fi done done fileName=$REGION-$(date +%s) printf "| %-30s | %-30s |\n" "Polling Pipeline Name" "Last Executed Time" printf "| %-30s | %-30s |\n" "_____________________" "__________________" for i in "${!POLLING_PIPELINES[@]}"; do printf "| %-30s | %-30s |\n" "${POLLING_PIPELINES[i]}" "${LAST_EXECUTED_DATES[i]}" printf "${POLLING_PIPELINES[i]}," >> $fileName.csv done printf "\nSaving Polling Pipeline Names to file $fileName.csv."
    • 다음 코드를 PollingPipelinesExtractor복사하여.py 스크립트에 붙여넣습니다.

      import boto3 import sys import time import math hasNextToken = True nextToken = "" pollablePipelines = [] lastExecutedTimes = [] if len(sys.argv) == 1: raise Exception("Please provide region name.") session = boto3.Session(profile_name='default', region_name=sys.argv[1]) codepipeline = session.client('codepipeline') def is_pollable_action(action): actionTypeId = action['actionTypeId'] configuration = action['configuration'] return actionTypeId['owner'] in {"AWS", "ThirdParty"} and actionTypeId['provider'] in {"GitHub", "CodeCommit", "S3"} and ('PollForSourceChanges' not in configuration or configuration['PollForSourceChanges'] == 'true') def has_pollable_actions(pipeline): hasPollableAction = False pipelineDefinition = codepipeline.get_pipeline(name=pipeline['name'])['pipeline'] for action in pipelineDefinition['stages'][0]['actions']: hasPollableAction = is_pollable_action(action) if hasPollableAction: break return hasPollableAction def get_last_executed_time(pipelineName): pipelineExecutions=codepipeline.list_pipeline_executions(pipelineName=pipelineName)['pipelineExecutionSummaries'] if pipelineExecutions: return pipelineExecutions[0]['startTime'].strftime("%A %m/%d/%Y, %H:%M:%S") else: return "Not executed in last year" while hasNextToken: if nextToken=="": list_pipelines_response = codepipeline.list_pipelines() else: list_pipelines_response = codepipeline.list_pipelines(nextToken=nextToken) if 'nextToken' in list_pipelines_response: nextToken = list_pipelines_response['nextToken'] else: hasNextToken= False for pipeline in list_pipelines_response['pipelines']: if has_pollable_actions(pipeline): pollablePipelines.append(pipeline['name']) lastExecutedTimes.append(get_last_executed_time(pipeline['name'])) fileName="{region}-{timeNow}.csv".format(region=sys.argv[1],timeNow=math.trunc(time.time())) file = open(fileName, 'w') print ("{:<30} {:<30} {:<30}".format('Polling Pipeline Name', '|','Last Executed Time')) print ("{:<30} {:<30} {:<30}".format('_____________________', '|','__________________')) for i in range(len(pollablePipelines)): print("{:<30} {:<30} {:<30}".format(pollablePipelines[i], '|', lastExecutedTimes[i])) file.write("{pipeline},".format(pipeline=pollablePipelines[i])) file.close() print("\nSaving Polling Pipeline Names to file {fileName}".format(fileName=fileName))
  3. 파이프라인이 있는 각 리전에 대해 해당 리전에 대한 스크립트를 실행해야 합니다. 스크립트를 실행하려면 다음 중 하나를 수행합니다.

    • 다음 명령을 실행하여 PollingPipelinesExtractor.sh라는 스크립트를 실행합니다. 이 예제에서 리전은 us-west-2입니다.

      ./PollingPipelinesExtractor.sh us-west-2
    • python 스크립트의 경우 다음 명령을 PollingPipelinesExtractor실행하여.py라는 파이썬 스크립트를 실행합니다. 이 예제에서 리전은 us-west-2입니다.

      python3 PollingPipelinesExtractor.py us-west-2

    스크립트의 다음 샘플 출력에서 us-west-2 리전은 폴링 파이프라인 목록을 반환하고 각 파이프라인의 마지막 실행 시간을 보여줍니다.

    % ./pollingPipelineExtractor.sh us-west-2 | Polling Pipeline Name | Last Executed Time | | _____________________ | __________________ | | myCodeBuildPipeline | Wed Mar 8 09:35:49 PST 2023 | | myCodeCommitPipeline | Mon Apr 24 22:32:32 PDT 2023 | | TestPipeline | Not executed in last year | Saving list of polling pipeline names to us-west-2-1682496174.csv...%

    스크립트 출력을 분석하고 목록의 각 파이프라인에 대해 폴링 소스를 권장되는 이벤트 기반 변경 감지 방법으로 업데이트합니다.

    참고

    폴링 파이프라인은 PollForSourceChanges 파라미터에 대한 파이프라인의 작업 구성에 따라 결정됩니다. 파이프라인 소스 구성에서 PollForSourceChanges 매개 변수가 생략된 경우 CodePipeline 기본적으로 리포지토리를 폴링하여 소스 변경 사항을 확인합니다. 이러한 동작은 PollForSourceChanges이 포함되었고 true로 설정된 경우와 똑같습니다. 자세한 내용은 Amazon S3 소스 액션 레퍼런스에서 Amazon S3 소스 작업 구성 파라미터 등 파이프라인 소스 작업에 대한 구성 파라미터를 참조하세요.

    참고로 이 스크립트는 계정의 폴링 파이프라인 목록이 포함된.csv 파일을 생성하고.csv 파일을 현재 작업 폴더에 저장합니다.

소스가 있는 폴링 파이프라인을 마이그레이션하세요. CodeCommit

폴링 파이프라인을 마이그레이션하여 CodeCommit 원본 리포지토리 또는 Amazon S3 원본 버킷의 변경 사항을 감지하는 데 사용할 EventBridge 수 있습니다.

CodeCommit-- CodeCommit 소스가 있는 파이프라인의 경우 변경 감지가 자동화되도록 파이프라인을 수정하십시오. EventBridge 다음 방법 중에서 선택하여 마이그레이션을 구현하세요.

폴링 파이프라인 (CodeCommit 또는 Amazon S3 소스) 마이그레이션 (콘솔)

CodePipeline 콘솔을 사용하여 CodeCommit 원본 리포지토리 또는 Amazon S3 원본 버킷의 변경 사항을 감지하는 EventBridge 데 사용할 파이프라인을 업데이트할 수 있습니다.

참고

콘솔을 사용하여 CodeCommit 원본 리포지토리 또는 Amazon S3 원본 버킷이 있는 파이프라인을 편집하면 규칙과 IAM 역할이 자동으로 생성됩니다. 를 사용하여 파이프라인을 AWS CLI 편집하는 경우 EventBridge 규칙과 IAM 역할을 직접 생성해야 합니다. 자세한 내용은 CodeCommit 소스 액션 및 EventBridge 단원을 참조하십시오.

정기적 확인을 사용하는 파이프라인을 편집하려면 다음 단계를 사용합니다. 파이프라인을 생성하려면 파이프라인, 스테이지, 액션 생성 단원을 참조하십시오.

파이프라인 소스 단계를 편집하려면
  1. 에 AWS Management Console 로그인하고 http://console.aws.amazon.com/codesuite/codepipeline/home 에서 CodePipeline 콘솔을 엽니다.

    AWS 계정과 연결된 모든 파이프라인의 이름이 표시됩니다.

  2. [Name]에서 편집할 파이프라인의 이름을 선택합니다. 이렇게 하면 파이프라인 각 단계의 각 작업 상태를 포함하여 파이프라인의 세부 정보 보기가 열립니다.

  3. 파이프라인 세부 정보 페이지에서 [Edit]를 선택합니다.

  4. 편집 단계에서 소스 작업의 편집 아이콘을 선택합니다.

  5. 변경 사항 발생 시 파이프라인을 자동으로 시작하려면 변경 감지 옵션을 확장하고 CloudWatch 이벤트 사용을 선택합니다 (권장).

    이 파이프라인에 대해 생성할 EventBridge 규칙을 보여주는 메시지가 나타납니다. 업데이트를 선택합니다.

    Amazon S3 소스가 있는 파이프라인을 업데이트하는 경우, 다음 메시지가 표시됩니다. 업데이트를 선택합니다.

  6. 파이프라인 편집을 마쳤으면 [Save pipeline changes]를 선택하여 요약 페이지로 돌아갑니다.

    파이프라인에 생성할 EventBridge 규칙의 이름이 메시지에 표시됩니다. [Save and continue]를 선택합니다.

  7. 작업을 테스트하려면 를 사용하여 파이프라인의 소스 단계에 지정된 소스에 변경 내용을 커밋하여 변경 사항을 릴리스하세요. AWS CLI

폴링 파이프라인 마이그레이션 (CodeCommit source) () CLI

다음 단계에 따라 폴링 (주기적 검사) 을 사용하는 파이프라인을 편집하여 EventBridge 규칙을 사용하여 파이프라인을 시작합니다. 파이프라인을 생성하려면 파이프라인, 스테이지, 액션 생성 단원을 참조하십시오.

를 사용하여 이벤트 기반 파이프라인을 구축하려면 파이프라인의 PollForSourceChanges 파라미터를 편집한 후 다음 리소스를 생성합니다. CodeCommit

  • EventBridge 이벤트

  • IAM이 이벤트에서 파이프라인을 시작할 수 있도록 허용하는 역할

파이프라인 PollForSourceChanges 파라미터를 편집하려면
중요

이 방법으로 파이프라인을 생성할 때 명시적으로 false로 설정되지 않은 경우 PollForSourceChanges 파라미터 기본값은 true입니다. 이벤트 기반 변경 감지를 추가할 때는 출력에 파라미터를 추가하고 false로 설정하여 폴링을 비활성화해야 합니다. 그렇지 않으면 파이프라인이 단일 소스 변경 시 두 번 시작됩니다. 세부 정보는 PollForSourceChanges 파라미터에 대한 유효한 설정을 참조하세요.

  1. get-pipeline명령을 실행하여 파이프라인 구조를 JSON 파일에 복사합니다. 예를 들어, MyFirstPipeline라는 파이프라인의 경우 다음 명령을 입력합니다.

    aws codepipeline get-pipeline --name MyFirstPipeline >pipeline.json

    이 명령은 아무 것도 반환하지 않지만 생성한 파일이 명령을 실행한 디렉터리에 표시되어야 합니다.

  2. 일반 텍스트 편집기에서 JSON 파일을 열고 이 예제와 같이 PollForSourceChanges 파라미터를 로 변경하여 소스 스테이지를 false 편집합니다.

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

    "configuration": { "PollForSourceChanges": "false", "BranchName": "main", "RepositoryName": "MyTestRepo" },
  3. get-pipeline명령을 사용하여 검색한 파이프라인 구조로 작업하는 경우 파일에서 해당 metadata 라인을 제거하세요. JSON 이렇게 하지 않으면 update-pipeline 명령에서 사용할 수 없습니다. "metadata": { } 행과, "created", "pipelineARN""updated" 필드를 제거합니다.

    예를 들어, 구조에서 다음 행을 삭제합니다.

    "metadata": { "pipelineArn": "arn:aws:codepipeline:region:account-ID:pipeline-name", "created": "date", "updated": "date" },

    파일을 저장합니다.

  4. 변경 내용을 적용하려면 파이프라인 JSON 파일을 지정하여 update-pipeline 명령을 실행합니다.

    중요

    파일 이름 앞에 file://를 포함해야 합니다. 이 명령에 필수적입니다.

    aws codepipeline update-pipeline --cli-input-json file://pipeline.json

    이 명령은 편집한 파이프라인의 전체 구조를 반환합니다.

    참고

    update-pipeline 명령을 실행하면 파이프라인이 중지됩니다. update-pipeline 명령을 실행할 때 파이프라인을 통해 개정을 실행하는 중이라면 해당 실행이 중지됩니다. 업데이트된 파이프라인을 통해 해당 개정을 실행하려면 파이프라인을 수동으로 시작해야 합니다. start-pipeline-execution 명령을 사용하여 수동으로 파이프라인을 시작합니다.

이벤트 소스 및 CodeCommit CodePipeline 대상으로 사용하여 EventBridge 규칙을 만들려면
  1. 규칙을 EventBridge 호출하는 CodePipeline 데 사용할 권한을 추가합니다. 자세한 내용은 Amazon의 리소스 기반 정책 사용을 참조하십시오. EventBridge

    1. 다음 샘플을 사용하여 서비스 역할을 EventBridge 맡을 수 있는 신뢰 정책을 생성하십시오. 신뢰 정책 이름을 trustpolicyforEB.json으로 지정합니다.

      { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "events.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
    2. 다음 명령을 사용하여 Role-for-MyRule 역할을 생성한 후 신뢰 정책에 연결합니다.

      aws iam create-role --role-name Role-for-MyRule --assume-role-policy-document file://trustpolicyforEB.json
    3. 이 샘플에 표시된 대로 이름이 지정된 파이프라인에 대한 권한 정책을 JSON 생성합니다MyFirstPipeline. 권한 정책 이름을 permissionspolicyforEB.json으로 지정합니다.

      { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "codepipeline:StartPipelineExecution" ], "Resource": [ "arn:aws:codepipeline:us-west-2:80398EXAMPLE:MyFirstPipeline" ] } ] }
    4. 다음 명령을 사용하여 CodePipeline-Permissions-Policy-for-EB 권한 정책을 Role-for-MyRule 역할에 연결합니다.

      이렇게 변경하는 이유는 무엇입니까? 이 정책을 역할에 추가하면 에 대한 권한이 생성됩니다 EventBridge.

      aws iam put-role-policy --role-name Role-for-MyRule --policy-name CodePipeline-Permissions-Policy-For-EB --policy-document file://permissionspolicyforEB.json
  2. put-rule 명령을 호출하고 --name, --event-pattern--role-arn 파라미터를 포함시킵니다.

    이렇게 변경하는 이유는 무엇입니까? 이 명령은 AWS CloudFormation 에서 이벤트를 생성할 수 있게 합니다.

    다음 샘플 명령은 MyCodeCommitRepoRule이라는 역할 별칭을 생성합니다.

    aws events put-rule --name "MyCodeCommitRepoRule" --event-pattern "{\"source\":[\"aws.codecommit\"],\"detail-type\":[\"CodeCommit Repository State Change\"],\"resources\":[\"repository-ARN\"],\"detail\":{\"referenceType\":[\"branch\"],\"referenceName\":[\"main\"]}}" --role-arn "arn:aws:iam::ACCOUNT_ID:role/Role-for-MyRule"
  3. CodePipeline 대상으로 추가하려면 put-targets 명령을 호출하고 다음 파라미터를 포함하세요.

    • --rule 파라미터는 put-rule을 사용하여 생성한 rule_name에 사용됩니다.

    • --targets 파라미터는 대상 목록에 있는 대상의 목록 Id 및 대상 파이프라인의 ARN에 사용됩니다.

    다음 예제 명령은 MyCodeCommitRepoRule이라는 규칙에 대해 대상 Id가 숫자 1로 구성됨을 지정하며, 규칙의 대상 목록에서 1로 대상 1로 표시됩니다. 이 예제 명령은 또한 파이프라인에 대한 예제 ARN를 지정합니다. 파이프라인은 리포지토리에서 변경이 발생하면 시작됩니다.

    aws events put-targets --rule MyCodeCommitRepoRule --targets Id=1,Arn=arn:aws:codepipeline:us-west-2:80398EXAMPLE:TestPipeline

폴링 파이프라인 마이그레이션 (CodeCommit 소스) (AWS CloudFormation 템플릿)

를 사용하여 이벤트 기반 파이프라인을 구축하려면 파이프라인의 PollForSourceChanges 파라미터를 편집한 후 템플릿에 다음 리소스를 추가합니다. AWS CodeCommit

  • 규칙 EventBridge

  • EventBridge 규칙의 IAM 역할

를 AWS CloudFormation 사용하여 파이프라인을 만들고 관리하는 경우 템플릿에는 다음과 같은 콘텐츠가 포함됩니다.

참고

PollForSourceChanges라고 하는 소스 단계의 Configuration 속성. 템플릿에 해당 속성이 포함되어 있지 않으면 기본적으로 PollForSourceChangestrue로 설정됩니다.

YAML
Resources: AppPipeline: Type: AWS::CodePipeline::Pipeline Properties: Name: codecommit-polling-pipeline RoleArn: !GetAtt CodePipelineServiceRole.Arn Stages: - Name: Source Actions: - Name: SourceAction ActionTypeId: Category: Source Owner: AWS Version: 1 Provider: CodeCommit OutputArtifacts: - Name: SourceOutput Configuration: BranchName: !Ref BranchName RepositoryName: !Ref RepositoryName PollForSourceChanges: true RunOrder: 1
JSON
"Stages": [ { "Name": "Source", "Actions": [{ "Name": "SourceAction", "ActionTypeId": { "Category": "Source", "Owner": "AWS", "Version": 1, "Provider": "CodeCommit" }, "OutputArtifacts": [{ "Name": "SourceOutput" }], "Configuration": { "BranchName": { "Ref": "BranchName" }, "RepositoryName": { "Ref": "RepositoryName" }, "PollForSourceChanges": true }, "RunOrder": 1 }] },
파이프라인 AWS CloudFormation 템플릿을 업데이트하고 규칙을 생성하려면 EventBridge
  1. 템플릿의 아래에서 Resources AWS::IAM::Role AWS CloudFormation 리소스를 사용하여 이벤트가 파이프라인을 시작하도록 허용하는 IAM 역할을 구성합니다. 이 항목은 두 가지 정책을 사용하는 역할을 만듭니다.

    • 첫 번째 정책은 가 역할을 수임하도록 허용합니다.

    • 두 번째 정책은 파이프라인을 시작할 권한을 부여합니다.

    이렇게 변경하는 이유는 무엇입니까? AWS::IAM::Role리소스를 추가하면 AWS CloudFormation 권한을 생성할 수 있습니다 EventBridge. 이 리소스는 AWS 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" } ] ...
  2. 템플릿의 아래에서 Resources AWS::Events::Rule AWS CloudFormation 리소스를 사용하여 EventBridge 규칙을 추가합니다. 이 이벤트 패턴은 리포지토리에 대한 푸시 변경 사항을 모니터링하는 이벤트를 생성합니다. 리포지토리 상태 변경을 EventBridge 감지하면 규칙이 대상 StartPipelineExecution 파이프라인에서 호출됩니다.

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

    YAML
    EventRule: Type: AWS::Events::Rule Properties: EventPattern: source: - aws.codecommit detail-type: - 'CodeCommit Repository State Change' resources: - !Join [ '', [ 'arn:aws:codecommit:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':', !Ref RepositoryName ] ] detail: event: - referenceCreated - referenceUpdated referenceType: - branch referenceName: - main 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.codecommit" ], "detail-type": [ "CodeCommit Repository State Change" ], "resources": [ { "Fn::Join": [ "", [ "arn:aws:codecommit:", { "Ref": "AWS::Region" }, ":", { "Ref": "AWS::AccountId" }, ":", { "Ref": "RepositoryName" } ] ] } ], "detail": { "event": [ "referenceCreated", "referenceUpdated" ], "referenceType": [ "branch" ], "referenceName": [ "main" ] } }, "Targets": [ { "Arn": { "Fn::Join": [ "", [ "arn:aws:codepipeline:", { "Ref": "AWS::Region" }, ":", { "Ref": "AWS::AccountId" }, ":", { "Ref": "AppPipeline" } ] ] }, "RoleArn": { "Fn::GetAtt": [ "EventRole", "Arn" ] }, "Id": "codepipeline-AppPipeline" } ] } },
  3. 업데이트된 템플릿을 로컬 컴퓨터에 저장하고 AWS CloudFormation 콘솔을 엽니다.

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

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

  6. 실행을 선택합니다.

파이프라인 PollForSourceChanges 파라미터를 편집하려면
중요

많은 경우 파이프라인을 생성할 때 PollForSourceChanges 파라미터 기본값은 true입니다. 이벤트 기반 변경 감지를 추가할 때는 출력에 파라미터를 추가하고 false로 설정하여 폴링을 비활성화해야 합니다. 그렇지 않으면 파이프라인이 단일 소스 변경 시 두 번 시작됩니다. 세부 정보는 PollForSourceChanges 파라미터에 대한 유효한 설정을 참조하세요.

  • 템플릿에서 PollForSourceChangesfalse로 변경합니다. PollForSourceChanges를 파이프라인 정의에 포함하지 않은 경우 추가하고 false로 설정하세요.

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

    YAML
    Name: Source Actions: - Name: SourceAction ActionTypeId: Category: Source Owner: AWS Version: 1 Provider: CodeCommit OutputArtifacts: - Name: SourceOutput Configuration: BranchName: !Ref BranchName RepositoryName: !Ref RepositoryName PollForSourceChanges: false RunOrder: 1
    JSON
    { "Name": "Source", "Actions": [ { "Name": "SourceAction", "ActionTypeId": { "Category": "Source", "Owner": "AWS", "Version": 1, "Provider": "CodeCommit" }, "OutputArtifacts": [ { "Name": "SourceOutput" } ], "Configuration": { "BranchName": { "Ref": "BranchName" }, "RepositoryName": { "Ref": "RepositoryName" }, "PollForSourceChanges": false }, "RunOrder": 1 } ] },

를 사용하여 이러한 리소스를 생성하면 리포지토리의 파일이 생성되거나 업데이트될 때 파이프라인이 트리거됩니다. AWS CloudFormation다음은 최종 템플릿 스니펫입니다.

YAML
Resources: 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 ] ] EventRule: Type: AWS::Events::Rule Properties: EventPattern: source: - aws.codecommit detail-type: - 'CodeCommit Repository State Change' resources: - !Join [ '', [ 'arn:aws:codecommit:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':', !Ref RepositoryName ] ] detail: event: - referenceCreated - referenceUpdated referenceType: - branch referenceName: - main Targets: - Arn: !Join [ '', [ 'arn:aws:codepipeline:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':', !Ref AppPipeline ] ] RoleArn: !GetAtt EventRole.Arn Id: codepipeline-AppPipeline AppPipeline: Type: AWS::CodePipeline::Pipeline Properties: Name: codecommit-events-pipeline RoleArn: !GetAtt CodePipelineServiceRole.Arn Stages: - Name: Source Actions: - Name: SourceAction ActionTypeId: Category: Source Owner: AWS Version: 1 Provider: CodeCommit OutputArtifacts: - Name: SourceOutput Configuration: BranchName: !Ref BranchName RepositoryName: !Ref RepositoryName PollForSourceChanges: false RunOrder: 1 ...
JSON
"Resources": { ... "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" } ] ] } } ] } } ] } }, "EventRule": { "Type": "AWS::Events::Rule", "Properties": { "EventPattern": { "source": [ "aws.codecommit" ], "detail-type": [ "CodeCommit Repository State Change" ], "resources": [ { "Fn::Join": [ "", [ "arn:aws:codecommit:", { "Ref": "AWS::Region" }, ":", { "Ref": "AWS::AccountId" }, ":", { "Ref": "RepositoryName" } ] ] } ], "detail": { "event": [ "referenceCreated", "referenceUpdated" ], "referenceType": [ "branch" ], "referenceName": [ "main" ] } }, "Targets": [ { "Arn": { "Fn::Join": [ "", [ "arn:aws:codepipeline:", { "Ref": "AWS::Region" }, ":", { "Ref": "AWS::AccountId" }, ":", { "Ref": "AppPipeline" } ] ] }, "RoleArn": { "Fn::GetAtt": [ "EventRole", "Arn" ] }, "Id": "codepipeline-AppPipeline" } ] } }, "AppPipeline": { "Type": "AWS::CodePipeline::Pipeline", "Properties": { "Name": "codecommit-events-pipeline", "RoleArn": { "Fn::GetAtt": [ "CodePipelineServiceRole", "Arn" ] }, "Stages": [ { "Name": "Source", "Actions": [ { "Name": "SourceAction", "ActionTypeId": { "Category": "Source", "Owner": "AWS", "Version": 1, "Provider": "CodeCommit" }, "OutputArtifacts": [ { "Name": "SourceOutput" } ], "Configuration": { "BranchName": { "Ref": "BranchName" }, "RepositoryName": { "Ref": "RepositoryName" }, "PollForSourceChanges": false }, "RunOrder": 1 } ] }, ...

이벤트용으로 활성화된 S3 소스를 사용하여 폴링 파이프라인 마이그레이션

Amazon S3 소스가 있는 파이프라인의 경우, 이벤트 알림이 활성화된 소스 버킷을 통해 EventBridge 변경 감지가 자동화되도록 파이프라인을 수정하십시오. CLIOR를 사용하여 파이프라인을 AWS CloudFormation 마이그레이션하는 경우 이 방법을 사용하는 것이 좋습니다.

참고

여기에는 별도의 CloudTrail 트레일을 생성할 필요가 없는 이벤트 알림이 활성화된 버킷을 사용하는 것도 포함됩니다. 콘솔을 사용하는 경우 이벤트 규칙과 CloudTrail 트레일이 자동으로 설정됩니다. 이러한 단계는 S3 소스 및 트레일을 사용하여 폴링 파이프라인을 마이그레이션하십시오. CloudTrail 을 참조하세요.

S3 소스에서 events를 사용하도록 설정한 상태로 폴링 파이프라인을 마이그레이션하십시오 () CLI

다음 단계에 따라 폴링 (주기적 검사) 을 사용하는 파이프라인을 편집하여 이벤트를 대신 사용하도록 하십시오. EventBridge 파이프라인을 생성하려면 파이프라인, 스테이지, 액션 생성 단원을 참조하십시오.

Amazon S3를 사용하여 이벤트 기반 파이프라인을 빌드하려면 파이프라인의 PollForSourceChanges 파라미터를 편집한 후 다음 리소스를 생성합니다.

  • EventBridge 이벤트 규칙

  • IAM EventBridge 이벤트가 파이프라인을 시작하도록 허용하는 역할

Amazon S3를 이벤트 소스 및 CodePipeline 대상으로 사용하여 EventBridge 규칙을 생성하고 권한 정책을 적용하려면
  1. 규칙을 EventBridge 호출하는 CodePipeline 데 사용할 권한을 부여합니다. 자세한 내용은 Amazon의 리소스 기반 정책 사용을 참조하십시오. EventBridge

    1. 다음 샘플을 사용하여 서비스 역할을 EventBridge 맡을 수 있는 신뢰 정책을 생성하십시오. 이름을 trustpolicyforEB.json로 지정합니다.

      { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "events.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
    2. 다음 명령을 사용하여 Role-for-MyRule 역할을 생성한 후 신뢰 정책에 연결합니다.

      이렇게 변경하는 이유는 무엇입니까? 이 신뢰 정책을 역할에 추가하면 에 대한 권한이 생성됩니다 EventBridge.

      aws iam create-role --role-name Role-for-MyRule --assume-role-policy-document file://trustpolicyforEB.json
    3. 이름이 지정된 파이프라인에 대해 여기에 표시된 대로 권한 정책을 JSON 생성합니다MyFirstPipeline. 권한 정책 이름을 permissionspolicyforEB.json으로 지정합니다.

      { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "codepipeline:StartPipelineExecution" ], "Resource": [ "arn:aws:codepipeline:us-west-2:80398EXAMPLE:MyFirstPipeline" ] } ] }
    4. 다음 명령을 사용하여 앞에서 생성한 Role-for-MyRule 역할에 새로운 CodePipeline-Permissions-Policy-for-EB 권한 정책을 연결합니다.

      aws iam put-role-policy --role-name Role-for-MyRule --policy-name CodePipeline-Permissions-Policy-For-EB --policy-document file://permissionspolicyforEB.json
  2. put-rule 명령을 호출하고 --name, --event-pattern--role-arn 파라미터를 포함시킵니다.

    다음 샘플 명령은 EnabledS3SourceRule이라는 역할 별칭을 생성합니다.

    aws events put-rule --name "EnabledS3SourceRule" --event-pattern "{\"source\":[\"aws.s3\"],\"detail-type\":[\"Object Created\"],\"detail\":{\"bucket\":{\"name\":[\"amzn-s3-demo-source-bucket\"]}}}" --role-arn "arn:aws:iam::ACCOUNT_ID:role/Role-for-MyRule"
  3. CodePipeline 대상으로 추가하려면 put-targets 명령을 호출하고 --rule--targets 매개변수를 포함시키십시오.

    다음 명령은 EnabledS3SourceRule이라는 규칙에 대해 대상 Id가 숫자 1로 구성됨을 지정하며, 규칙에 대한 대상 목록에서 대상 1로 표시됩니다. 이 명령은 또한 파이프라인에 대한 예제 ARN를 지정합니다. 파이프라인은 리포지토리에서 변경이 발생하면 시작됩니다.

    aws events put-targets --rule EnabledS3SourceRule --targets Id=codepipeline-AppPipeline,Arn=arn:aws:codepipeline:us-west-2:80398EXAMPLE:TestPipeline
파이프라인 PollForSourceChanges 파라미터를 편집하려면
중요

이 방법으로 파이프라인을 생성할 때 명시적으로 false로 설정되지 않은 경우 PollForSourceChanges 파라미터 기본값은 true입니다. 이벤트 기반 변경 감지를 추가할 때는 출력에 파라미터를 추가하고 false로 설정하여 폴링을 비활성화해야 합니다. 그렇지 않으면 파이프라인이 단일 소스 변경 시 두 번 시작됩니다. 세부 정보는 PollForSourceChanges 파라미터에 대한 유효한 설정을 참조하세요.

  1. get-pipeline명령을 실행하여 파이프라인 구조를 JSON 파일에 복사합니다. 예를 들어, MyFirstPipeline라는 파이프라인의 경우 다음 명령을 입력합니다.

    aws codepipeline get-pipeline --name MyFirstPipeline >pipeline.json

    이 명령은 아무 것도 반환하지 않지만 생성한 파일이 명령을 실행한 디렉터리에 표시되어야 합니다.

  2. 일반 텍스트 편집기에서 JSON 파일을 열고 이 예제와 같이 이름이 지정된 버킷의 PollForSourceChanges 파라미터를 변경하여 소스 amzn-s3-demo-source-bucket 스테이지를 false 편집합니다.

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

    "configuration": { "S3Bucket": "amzn-s3-demo-source-bucket", "PollForSourceChanges": "false", "S3ObjectKey": "index.zip" },
  3. get-pipeline명령을 사용하여 검색한 파이프라인 구조로 작업하는 경우 파일에서 metadata 라인을 제거해야 합니다. JSON 이렇게 하지 않으면 update-pipeline 명령에서 사용할 수 없습니다. "metadata": { } 행과, "created", "pipelineARN""updated" 필드를 제거합니다.

    예를 들어, 구조에서 다음 행을 삭제합니다.

    "metadata": { "pipelineArn": "arn:aws:codepipeline:region:account-ID:pipeline-name", "created": "date", "updated": "date" },

    파일을 저장합니다.

  4. 변경 내용을 적용하려면 파이프라인 JSON 파일을 지정하여 update-pipeline 명령을 실행합니다.

    중요

    파일 이름 앞에 file://를 포함해야 합니다. 이 명령에 필수적입니다.

    aws codepipeline update-pipeline --cli-input-json file://pipeline.json

    이 명령은 편집한 파이프라인의 전체 구조를 반환합니다.

    참고

    update-pipeline 명령을 실행하면 파이프라인이 중지됩니다. update-pipeline 명령을 실행할 때 파이프라인을 통해 개정을 실행하는 중이라면 해당 실행이 중지됩니다. 업데이트된 파이프라인을 통해 해당 개정을 실행하려면 파이프라인을 수동으로 시작해야 합니다. start-pipeline-execution 명령을 사용하여 수동으로 파이프라인을 시작합니다.

이벤트에 사용할 수 있는 S3 소스 (AWS CloudFormation 템플릿) 를 사용하여 폴링 파이프라인을 마이그레이션합니다.

이 절차는 소스 버킷에 이벤트가 활성화된 파이프라인을 위한 것입니다.

폴링에서 이벤트 기반 변경 감지로 Amazon S3 소스가 있는 파이프라인을 편집하려면 다음 단계를 수행합니다.

Amazon S3를 사용하여 이벤트 기반 파이프라인을 빌드하려면 해당 파이프라인의 PollForSourceChanges 파라미터를 편집한 후 다음 리소스를 템플릿에 추가합니다.

  • EventBridge 이 이벤트에서 파이프라인을 시작할 수 있도록 허용하는 규칙 및 IAM 역할

를 AWS CloudFormation 사용하여 파이프라인을 생성하고 관리하는 경우 템플릿에는 다음과 같은 콘텐츠가 포함됩니다.

참고

PollForSourceChanges라고 하는 소스 단계의 Configuration 속성. 템플릿에 해당 속성이 포함되어 있지 않으면 기본적으로 PollForSourceChangestrue로 설정됩니다.

YAML
AppPipeline: Type: AWS::CodePipeline::Pipeline Properties: RoleArn: !GetAtt CodePipelineServiceRole.Arn Stages: - Name: Source Actions: - Name: SourceAction ActionTypeId: Category: Source Owner: AWS Version: 1 Provider: S3 OutputArtifacts: - Name: SourceOutput Configuration: S3Bucket: !Ref SourceBucket S3ObjectKey: !Ref S3SourceObjectKey PollForSourceChanges: true RunOrder: 1 ...
JSON
"AppPipeline": { "Type": "AWS::CodePipeline::Pipeline", "Properties": { "RoleArn": { "Fn::GetAtt": ["CodePipelineServiceRole", "Arn"] }, "Stages": [ { "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": true }, "RunOrder": 1 } ] }, ...
Amazon S3를 이벤트 소스 및 CodePipeline 대상으로 사용하여 EventBridge 규칙을 생성하고 권한 정책을 적용하려면
  1. 템플릿의 아래에서 Resources AWS::IAM::Role AWS CloudFormation 리소스를 사용하여 이벤트가 파이프라인을 시작하도록 허용하는 IAM 역할을 구성합니다. 이 항목은 두 가지 정책을 사용하는 역할을 만듭니다.

    • 첫 번째 정책은 가 역할을 수임하도록 허용합니다.

    • 두 번째 정책은 파이프라인을 시작할 권한을 부여합니다.

    이렇게 변경하는 이유는 무엇입니까? AWS::IAM::Role리소스를 추가하면 AWS CloudFormation 권한을 생성할 수 있습니다 EventBridge. 이 리소스는 AWS 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" } ] ] ...
  2. AWS::Events::Rule AWS CloudFormation 리소스를 사용하여 EventBridge 규칙을 추가합니다. 이 이벤트 패턴은 Amazon S3 원본 버킷의 객체 생성 또는 삭제를 모니터링하는 이벤트를 생성합니다. 또한 파이프라인 대상도 포함하세요. 객체가 생성되면 이 규칙이 대상 파이프라인의 StartPipelineExecution을 호출합니다.

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

    YAML
    EventRule: Type: AWS::Events::Rule Properties: EventBusName: default EventPattern: source: - aws.s3 detail-type: - Object Created detail: bucket: name: - !Ref SourceBucket Name: EnabledS3SourceRule State: ENABLED 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": { "EventBusName": "default", "EventPattern": { "source": [ "aws.s3" ], "detail-type": [ "Object Created" ], "detail": { "bucket": { "name": [ "s3-pipeline-source-fra-bucket" ] } } }, "Name": "EnabledS3SourceRule", "State": "ENABLED", "Targets": [ { "Arn": { "Fn::Join": [ "", [ "arn:aws:codepipeline:", { "Ref": "AWS::Region" }, ":", { "Ref": "AWS::AccountId" }, ":", { "Ref": "AppPipeline" } ] ] }, "RoleArn": { "Fn::GetAtt": [ "EventRole", "Arn" ] }, "Id": "codepipeline-AppPipeline" } ] } } }, ...
  3. 업데이트된 템플릿을 로컬 컴퓨터에 저장하고 AWS CloudFormation 콘솔을 엽니다.

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

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

  6. 실행을 선택합니다.

파이프라인 PollForSourceChanges 파라미터를 편집하려면
중요

이 방법으로 파이프라인을 생성할 때 명시적으로 false로 설정되지 않은 경우 PollForSourceChanges 파라미터 기본값은 true입니다. 이벤트 기반 변경 감지를 추가할 때는 출력에 파라미터를 추가하고 false로 설정하여 폴링을 비활성화해야 합니다. 그렇지 않으면 파이프라인이 단일 소스 변경 시 두 번 시작됩니다. 세부 정보는 PollForSourceChanges 파라미터에 대한 유효한 설정을 참조하세요.

  • 템플릿에서 PollForSourceChangesfalse로 변경합니다. PollForSourceChanges를 파이프라인 정의에 포함하지 않은 경우 추가하고 false로 설정하세요.

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

    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 }

를 AWS CloudFormation 사용하여 이러한 리소스를 생성하면 리포지토리의 파일이 생성되거나 업데이트될 때 파이프라인이 트리거됩니다.

참고

여기에서 중단하지 마십시오. 파이프라인이 생성되었더라도 Amazon S3 파이프라인에 사용할 두 번째 AWS CloudFormation 템플릿을 생성해야 합니다. 두 번째 템플릿을 생성하지 않으면 파이프라인에 변경 감지 기능이 없습니다.

YAML
Parameters: SourceObjectKey: Description: 'S3 source artifact' Type: String Default: SampleApp_Linux.zip ApplicationName: Description: 'CodeDeploy application name' Type: String Default: DemoApplication BetaFleet: Description: 'Fleet configured in CodeDeploy' Type: String Default: DemoFleet Resources: SourceBucket: Type: AWS::S3::Bucket Properties: NotificationConfiguration: EventBridgeConfiguration: EventBridgeEnabled: true VersioningConfiguration: Status: Enabled CodePipelineArtifactStoreBucket: Type: AWS::S3::Bucket CodePipelineArtifactStoreBucketPolicy: Type: AWS::S3::BucketPolicy Properties: Bucket: !Ref CodePipelineArtifactStoreBucket PolicyDocument: Version: 2012-10-17 Statement: - Sid: DenyUnEncryptedObjectUploads Effect: Deny Principal: '*' Action: s3:PutObject Resource: !Join [ '', [ !GetAtt CodePipelineArtifactStoreBucket.Arn, '/*' ] ] Condition: StringNotEquals: s3:x-amz-server-side-encryption: aws:kms - Sid: DenyInsecureConnections Effect: Deny Principal: '*' Action: s3:* Resource: !Sub ${CodePipelineArtifactStoreBucket.Arn}/* Condition: Bool: aws:SecureTransport: false CodePipelineServiceRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: Service: - codepipeline.amazonaws.com Action: sts:AssumeRole Path: / Policies: - PolicyName: AWS-CodePipeline-Service-3 PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - codecommit:CancelUploadArchive - codecommit:GetBranch - codecommit:GetCommit - codecommit:GetUploadArchiveStatus - codecommit:UploadArchive Resource: 'resource_ARN' - Effect: Allow Action: - codedeploy:CreateDeployment - codedeploy:GetApplicationRevision - codedeploy:GetDeployment - codedeploy:GetDeploymentConfig - codedeploy:RegisterApplicationRevision Resource: 'resource_ARN' - Effect: Allow Action: - codebuild:BatchGetBuilds - codebuild:StartBuild Resource: 'resource_ARN' - Effect: Allow Action: - devicefarm:ListProjects - devicefarm:ListDevicePools - devicefarm:GetRun - devicefarm:GetUpload - devicefarm:CreateUpload - devicefarm:ScheduleRun Resource: 'resource_ARN' - Effect: Allow Action: - lambda:InvokeFunction - lambda:ListFunctions Resource: 'resource_ARN' - Effect: Allow Action: - iam:PassRole Resource: 'resource_ARN' - Effect: Allow Action: - elasticbeanstalk:* - ec2:* - elasticloadbalancing:* - autoscaling:* - cloudwatch:* - s3:* - sns:* - cloudformation:* - rds:* - sqs:* - ecs:* Resource: 'resource_ARN' AppPipeline: Type: AWS::CodePipeline::Pipeline Properties: Name: s3-events-pipeline RoleArn: !GetAtt CodePipelineServiceRole.Arn Stages: - 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 - Name: Beta Actions: - Name: BetaAction InputArtifacts: - Name: SourceOutput ActionTypeId: Category: Deploy Owner: AWS Version: 1 Provider: CodeDeploy Configuration: ApplicationName: !Ref ApplicationName DeploymentGroupName: !Ref BetaFleet RunOrder: 1 ArtifactStore: Type: S3 Location: !Ref CodePipelineArtifactStoreBucket 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 ] ] EventRule: Type: AWS::Events::Rule Properties: EventBusName: default EventPattern: source: - aws.s3 detail-type: - Object Created detail: bucket: name: - !Ref SourceBucket Name: EnabledS3SourceRule State: ENABLED Targets: - Arn: !Join [ '', [ 'arn:aws:codepipeline:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':', !Ref AppPipeline ] ] RoleArn: !GetAtt EventRole.Arn Id: codepipeline-AppPipeline
JSON
{ "Parameters": { "SourceObjectKey": { "Description": "S3 source artifact", "Type": "String", "Default": "SampleApp_Linux.zip" }, "ApplicationName": { "Description": "CodeDeploy application name", "Type": "String", "Default": "DemoApplication" }, "BetaFleet": { "Description": "Fleet configured in CodeDeploy", "Type": "String", "Default": "DemoFleet" } }, "Resources": { "SourceBucket": { "Type": "AWS::S3::Bucket", "Properties": { "NotificationConfiguration": { "EventBridgeConfiguration": { "EventBridgeEnabled": true } }, "VersioningConfiguration": { "Status": "Enabled" } } }, "CodePipelineArtifactStoreBucket": { "Type": "AWS::S3::Bucket" }, "CodePipelineArtifactStoreBucketPolicy": { "Type": "AWS::S3::BucketPolicy", "Properties": { "Bucket": { "Ref": "CodePipelineArtifactStoreBucket" }, "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "DenyUnEncryptedObjectUploads", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", "Resource": { "Fn::Join": [ "", [ { "Fn::GetAtt": [ "CodePipelineArtifactStoreBucket", "Arn" ] }, "/*" ] ] }, "Condition": { "StringNotEquals": { "s3:x-amz-server-side-encryption": "aws:kms" } } }, { "Sid": "DenyInsecureConnections", "Effect": "Deny", "Principal": "*", "Action": "s3:*", "Resource": { "Fn::Join": [ "", [ { "Fn::GetAtt": [ "CodePipelineArtifactStoreBucket", "Arn" ] }, "/*" ] ] }, "Condition": { "Bool": { "aws:SecureTransport": false } } } ] } } }, "CodePipelineServiceRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "codepipeline.amazonaws.com" ] }, "Action": "sts:AssumeRole" } ] }, "Path": "/", "Policies": [ { "PolicyName": "AWS-CodePipeline-Service-3", "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "codecommit:CancelUploadArchive", "codecommit:GetBranch", "codecommit:GetCommit", "codecommit:GetUploadArchiveStatus", "codecommit:UploadArchive" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "codedeploy:CreateDeployment", "codedeploy:GetApplicationRevision", "codedeploy:GetDeployment", "codedeploy:GetDeploymentConfig", "codedeploy:RegisterApplicationRevision" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "codebuild:BatchGetBuilds", "codebuild:StartBuild" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "devicefarm:ListProjects", "devicefarm:ListDevicePools", "devicefarm:GetRun", "devicefarm:GetUpload", "devicefarm:CreateUpload", "devicefarm:ScheduleRun" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "lambda:InvokeFunction", "lambda:ListFunctions" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "iam:PassRole" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "elasticbeanstalk:*", "ec2:*", "elasticloadbalancing:*", "autoscaling:*", "cloudwatch:*", "s3:*", "sns:*", "cloudformation:*", "rds:*", "sqs:*", "ecs:*" ], "Resource": "resource_ARN" } ] } } ] } }, "AppPipeline": { "Type": "AWS::CodePipeline::Pipeline", "Properties": { "Name": "s3-events-pipeline", "RoleArn": { "Fn::GetAtt": [ "CodePipelineServiceRole", "Arn" ] }, "Stages": [ { "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 } ] }, { "Name": "Beta", "Actions": [ { "Name": "BetaAction", "InputArtifacts": [ { "Name": "SourceOutput" } ], "ActionTypeId": { "Category": "Deploy", "Owner": "AWS", "Version": 1, "Provider": "CodeDeploy" }, "Configuration": { "ApplicationName": { "Ref": "ApplicationName" }, "DeploymentGroupName": { "Ref": "BetaFleet" } }, "RunOrder": 1 } ] } ], "ArtifactStore": { "Type": "S3", "Location": { "Ref": "CodePipelineArtifactStoreBucket" } } } }, "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" } ] ] } } ] } } ] } }, "EventRule": { "Type": "AWS::Events::Rule", "Properties": { "EventBusName": "default", "EventPattern": { "source": [ "aws.s3" ], "detail-type": [ "Object Created" ], "detail": { "bucket": { "name": [ { "Ref": "SourceBucket" } ] } } }, "Name": "EnabledS3SourceRule", "State": "ENABLED", "Targets": [ { "Arn": { "Fn::Join": [ "", [ "arn:aws:codepipeline:", { "Ref": "AWS::Region" }, ":", { "Ref": "AWS::AccountId" }, ":", { "Ref": "AppPipeline" } ] ] }, "RoleArn": { "Fn::GetAtt": [ "EventRole", "Arn" ] }, "Id": "codepipeline-AppPipeline" } ] } } } } }

S3 소스 및 트레일을 사용하여 폴링 파이프라인을 마이그레이션하십시오. CloudTrail

Amazon S3 소스가 있는 파이프라인의 경우 변경 감지가 자동화되도록 파이프라인을 EventBridge 수정하십시오. 다음 방법 중에서 선택하여 마이그레이션을 구현하세요.

S3 소스 및 CloudTrail 트레일을 사용하여 폴링 파이프라인을 마이그레이션합니다 (). CLI

다음 단계에 따라 폴링 (주기적 검사) 을 사용하는 파이프라인을 편집하여 이벤트를 대신 사용하도록 하십시오. EventBridge 파이프라인을 생성하려면 파이프라인, 스테이지, 액션 생성 단원을 참조하십시오.

Amazon S3를 사용하여 이벤트 기반 파이프라인을 빌드하려면 파이프라인의 PollForSourceChanges 파라미터를 편집한 후 다음 리소스를 생성합니다.

  • AWS CloudTrail Amazon S3가 이벤트를 기록하는 데 사용할 수 있는 트레일, 버킷 및 버킷 정책

  • EventBridge 이벤트

  • IAM EventBridge 이벤트에서 파이프라인을 시작하도록 허용하는 역할

AWS CloudTrail 트레일을 생성하고 로깅을 활성화하려면

를 사용하여 트레일을 AWS CLI 만들려면 다음과 같이 지정하여 create-trail 명령을 호출합니다.

  • 추적 이름입니다.

  • AWS CloudTrail에 대한 버킷 정책을 이미 적용한 버킷입니다.

자세한 내용은 AWS 명령줄 인터페이스를 사용하여 트레일 만들기를 참조하십시오.

  1. create-trail 명령을 호출하고 --name--s3-bucket-name 파라미터를 포함시킵니다.

    이렇게 변경하는 이유는 무엇입니까? 이렇게 하면 S3 소스 버킷에 필요한 CloudTrail 트레일이 생성됩니다.

    다음 명령은 --name--s3-bucket-name을 사용하여 my-trail이라는 추적과 amzn-s3-demo-source-bucket이라는 버킷을 생성합니다.

    aws cloudtrail create-trail --name my-trail --s3-bucket-name amzn-s3-demo-source-bucket
  2. start-logging 명령을 호출하고 --name 파라미터를 포함시킵니다.

    이렇게 변경하는 이유는 무엇입니까? 이 명령은 원본 버킷에 대한 CloudTrail 로깅을 시작하고 이벤트를 로 EventBridge 전송합니다.

    예제:

    다음 명령은 --name을 사용하여 my-trail이라는 추적에서 로깅을 시작합니다.

    aws cloudtrail start-logging --name my-trail
  3. put-event-selectors 명령을 호출하고 --trail-name--event-selectors 파라미터를 포함시킵니다. 이벤트 선택기를 사용하여 트레일에서 원본 버킷의 데이터 이벤트를 기록하고 해당 이벤트를 EventBridge 규칙에 전송하도록 지정합니다.

    이렇게 변경하는 이유는 무엇입니까? 이 명령은 이벤트를 필터링합니다.

    예제:

    다음 명령은 --trail-name--event-selectors를 사용하여 소스 버킷 및 amzn-s3-demo-source-bucket/myFolder라는 접두사에 대한 데이터 이벤트 관리를 지정합니다.

    aws cloudtrail put-event-selectors --trail-name my-trail --event-selectors '[{ "ReadWriteType": "WriteOnly", "IncludeManagementEvents":false, "DataResources": [{ "Type": "AWS::S3::Object", "Values": ["arn:aws:s3:::amzn-s3-demo-source-bucket/myFolder/file.zip"] }] }]'
Amazon S3를 이벤트 소스 및 CodePipeline 대상으로 사용하여 EventBridge 규칙을 생성하고 권한 정책을 적용하려면
  1. 규칙을 EventBridge 호출하는 CodePipeline 데 사용할 권한을 부여합니다. 자세한 내용은 Amazon의 리소스 기반 정책 사용을 참조하십시오. EventBridge

    1. 다음 샘플을 사용하여 서비스 역할을 EventBridge 맡을 수 있는 신뢰 정책을 생성하십시오. 이름을 trustpolicyforEB.json로 지정합니다.

      { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "events.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
    2. 다음 명령을 사용하여 Role-for-MyRule 역할을 생성한 후 신뢰 정책에 연결합니다.

      이렇게 변경하는 이유는 무엇입니까? 이 신뢰 정책을 역할에 추가하면 에 대한 권한이 생성됩니다 EventBridge.

      aws iam create-role --role-name Role-for-MyRule --assume-role-policy-document file://trustpolicyforEB.json
    3. 이름이 지정된 파이프라인에 대해 여기에 표시된 대로 권한 정책을 JSON 생성합니다MyFirstPipeline. 권한 정책 이름을 permissionspolicyforEB.json으로 지정합니다.

      { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "codepipeline:StartPipelineExecution" ], "Resource": [ "arn:aws:codepipeline:us-west-2:80398EXAMPLE:MyFirstPipeline" ] } ] }
    4. 다음 명령을 사용하여 앞에서 생성한 Role-for-MyRule 역할에 새로운 CodePipeline-Permissions-Policy-for-EB 권한 정책을 연결합니다.

      aws iam put-role-policy --role-name Role-for-MyRule --policy-name CodePipeline-Permissions-Policy-For-EB --policy-document file://permissionspolicyforEB.json
  2. put-rule 명령을 호출하고 --name, --event-pattern--role-arn 파라미터를 포함시킵니다.

    다음 샘플 명령은 MyS3SourceRule이라는 역할 별칭을 생성합니다.

    aws events put-rule --name "MyS3SourceRule" --event-pattern "{\"source\":[\"aws.s3\"],\"detail-type\":[\"AWS API Call via CloudTrail\"],\"detail\":{\"eventSource\":[\"s3.amazonaws.com\"],\"eventName\":[\"CopyObject\",\"PutObject\",\"CompleteMultipartUpload\"],\"requestParameters\":{\"bucketName\":[\"amzn-s3-demo-source-bucket\"],\"key\":[\"my-key\"]}}} --role-arn "arn:aws:iam::ACCOUNT_ID:role/Role-for-MyRule"
  3. CodePipeline 대상으로 추가하려면 put-targets 명령을 호출하고 --rule--targets 매개변수를 포함시키십시오.

    다음 명령은 MyS3SourceRule이라는 규칙에 대해 대상 Id가 숫자 1로 구성됨을 지정하며, 규칙에 대한 대상 목록에서 대상 1로 표시됩니다. 이 명령은 또한 파이프라인에 대한 예제 ARN를 지정합니다. 파이프라인은 리포지토리에서 변경이 발생하면 시작됩니다.

    aws events put-targets --rule MyS3SourceRule --targets Id=1,Arn=arn:aws:codepipeline:us-west-2:80398EXAMPLE:TestPipeline
파이프라인 PollForSourceChanges 파라미터를 편집하려면
중요

이 방법으로 파이프라인을 생성할 때 명시적으로 false로 설정되지 않은 경우 PollForSourceChanges 파라미터 기본값은 true입니다. 이벤트 기반 변경 감지를 추가할 때는 출력에 파라미터를 추가하고 false로 설정하여 폴링을 비활성화해야 합니다. 그렇지 않으면 파이프라인이 단일 소스 변경 시 두 번 시작됩니다. 세부 정보는 PollForSourceChanges 파라미터에 대한 유효한 설정을 참조하세요.

  1. get-pipeline명령을 실행하여 파이프라인 구조를 JSON 파일에 복사합니다. 예를 들어, MyFirstPipeline라는 파이프라인의 경우 다음 명령을 입력합니다.

    aws codepipeline get-pipeline --name MyFirstPipeline >pipeline.json

    이 명령은 아무 것도 반환하지 않지만 생성한 파일이 명령을 실행한 디렉터리에 표시되어야 합니다.

  2. 일반 텍스트 편집기에서 JSON 파일을 열고 이 예제와 같이 이름이 지정된 버킷의 PollForSourceChanges 파라미터를 변경하여 소스 amzn-s3-demo-source-bucket 스테이지를 false 편집합니다.

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

    "configuration": { "S3Bucket": "amzn-s3-demo-source-bucket", "PollForSourceChanges": "false", "S3ObjectKey": "index.zip" },
  3. get-pipeline명령을 사용하여 검색한 파이프라인 구조로 작업하는 경우 파일에서 metadata 라인을 제거해야 합니다. JSON 이렇게 하지 않으면 update-pipeline 명령에서 사용할 수 없습니다. "metadata": { } 행과, "created", "pipelineARN""updated" 필드를 제거합니다.

    예를 들어, 구조에서 다음 행을 삭제합니다.

    "metadata": { "pipelineArn": "arn:aws:codepipeline:region:account-ID:pipeline-name", "created": "date", "updated": "date" },

    파일을 저장합니다.

  4. 변경 내용을 적용하려면 파이프라인 JSON 파일을 지정하여 update-pipeline 명령을 실행합니다.

    중요

    파일 이름 앞에 file://를 포함해야 합니다. 이 명령에 필수적입니다.

    aws codepipeline update-pipeline --cli-input-json file://pipeline.json

    이 명령은 편집한 파이프라인의 전체 구조를 반환합니다.

    참고

    update-pipeline 명령을 실행하면 파이프라인이 중지됩니다. update-pipeline 명령을 실행할 때 파이프라인을 통해 개정을 실행하는 중이라면 해당 실행이 중지됩니다. 업데이트된 파이프라인을 통해 해당 개정을 실행하려면 파이프라인을 수동으로 시작해야 합니다. start-pipeline-execution 명령을 사용하여 수동으로 파이프라인을 시작합니다.

S3 소스 및 CloudTrail 트레일 (AWS CloudFormation 템플릿) 을 사용하여 폴링 파이프라인을 마이그레이션합니다.

폴링에서 이벤트 기반 변경 감지로 Amazon S3 소스가 있는 파이프라인을 편집하려면 다음 단계를 수행합니다.

Amazon S3를 사용하여 이벤트 기반 파이프라인을 빌드하려면 해당 파이프라인의 PollForSourceChanges 파라미터를 편집한 후 다음 리소스를 템플릿에 추가합니다.

  • EventBridge 모든 Amazon S3 이벤트를 기록해야 합니다. Amazon S3가 발생 이벤트를 로깅하기 위해 사용할 수 있는 AWS CloudTrail 추적, 버킷 및 버킷 정책을 생성해야 합니다. 자세한 내용은 추적에 대한 데이터 이벤트 로깅추적에 대한 관리 이벤트 로깅을 참조하세요.

  • EventBridge 이 이벤트에서 파이프라인을 시작할 수 있도록 허용하는 규칙 및 IAM 역할

를 AWS CloudFormation 사용하여 파이프라인을 생성하고 관리하는 경우 템플릿에는 다음과 같은 콘텐츠가 포함됩니다.

참고

PollForSourceChanges라고 하는 소스 단계의 Configuration 속성. 템플릿에 해당 속성이 포함되어 있지 않으면 기본적으로 PollForSourceChangestrue로 설정됩니다.

YAML
AppPipeline: Type: AWS::CodePipeline::Pipeline Properties: RoleArn: !GetAtt CodePipelineServiceRole.Arn Stages: - Name: Source Actions: - Name: SourceAction ActionTypeId: Category: Source Owner: AWS Version: 1 Provider: S3 OutputArtifacts: - Name: SourceOutput Configuration: S3Bucket: !Ref SourceBucket S3ObjectKey: !Ref S3SourceObjectKey PollForSourceChanges: true RunOrder: 1 ...
JSON
"AppPipeline": { "Type": "AWS::CodePipeline::Pipeline", "Properties": { "RoleArn": { "Fn::GetAtt": ["CodePipelineServiceRole", "Arn"] }, "Stages": [ { "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": true }, "RunOrder": 1 } ] }, ...
Amazon S3를 이벤트 소스 및 CodePipeline 대상으로 사용하여 EventBridge 규칙을 생성하고 권한 정책을 적용하려면
  1. 템플릿의 아래에서 Resources AWS::IAM::Role AWS CloudFormation 리소스를 사용하여 이벤트가 파이프라인을 시작하도록 허용하는 IAM 역할을 구성합니다. 이 항목은 두 가지 정책을 사용하는 역할을 만듭니다.

    • 첫 번째 정책은 가 역할을 수임하도록 허용합니다.

    • 두 번째 정책은 파이프라인을 시작할 권한을 부여합니다.

    이렇게 변경하는 이유는 무엇입니까? AWS::IAM::Role리소스를 추가하면 AWS CloudFormation 권한을 생성할 수 있습니다 EventBridge. 이 리소스는 AWS 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" } ] ] ...
  2. AWS::Events::Rule AWS CloudFormation 리소스를 사용하여 EventBridge 규칙을 추가합니다. 이 이벤트 패턴은 Amazon S3 소스 버킷의 CopyObject, PutObjectCompleteMultipartUpload를 모니터링하는 이벤트를 생성합니다. 또한 파이프라인 대상도 포함하세요. 이 규칙은 CopyObject, PutObject 또는 CompleteMultipartUpload 발생 시 대상 파이프라인에서 StartPipelineExecution을 호출합니다.

    이렇게 변경하는 이유는 무엇입니까? AWS::Events::Rule리소스를 추가하면 이벤트를 생성할 AWS CloudFormation 수 있습니다. 이 리소스는 AWS 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" } ] } } }, ...
  3. 이 코드 조각을 첫 번째 템플릿에 추가하여 교차 스택 기능을 허용하세요.

    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" } } ...
  4. 업데이트된 템플릿을 로컬 컴퓨터에 저장하고 AWS CloudFormation 콘솔을 엽니다.

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

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

  7. 실행을 선택합니다.

파이프라인 PollForSourceChanges 파라미터를 편집하려면
중요

이 방법으로 파이프라인을 생성할 때 명시적으로 false로 설정되지 않은 경우 PollForSourceChanges 파라미터 기본값은 true입니다. 이벤트 기반 변경 감지를 추가할 때는 출력에 파라미터를 추가하고 false로 설정하여 폴링을 비활성화해야 합니다. 그렇지 않으면 파이프라인이 단일 소스 변경 시 두 번 시작됩니다. 세부 정보는 PollForSourceChanges 파라미터에 대한 유효한 설정을 참조하세요.

  • 템플릿에서 PollForSourceChangesfalse로 변경합니다. PollForSourceChanges를 파이프라인 정의에 포함하지 않은 경우 추가하고 false로 설정하세요.

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

    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 }
Amazon S3 파이프라인 CloudTrail 리소스용 두 번째 템플릿을 만들려면
  • 별도의 템플릿에서 Resources AWS::S3::BucketAWS::S3::BucketPolicy, 및 AWS::CloudTrail::Trail AWS CloudFormation 리소스를 사용하여 간단한 버킷 정의 및 추적을 제공하십시오 CloudTrail.

    이렇게 변경하는 이유는 무엇입니까? 현재 계정당 트레일 5개로 제한되어 있으므로 CloudTrail 트레일을 별도로 생성하고 관리해야 합니다. (의 한도를 참조하십시오 AWS CloudTrail.) 하지만 단일 추적에 많은 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 } } } } ...

를 AWS CloudFormation 사용하여 이러한 리소스를 생성하면 리포지토리의 파일이 생성되거나 업데이트될 때 파이프라인이 트리거됩니다.

참고

여기에서 중단하지 마십시오. 파이프라인이 생성되었더라도 Amazon S3 파이프라인에 사용할 두 번째 AWS CloudFormation 템플릿을 생성해야 합니다. 두 번째 템플릿을 생성하지 않으면 파이프라인에 변경 감지 기능이 없습니다.

YAML
Resources: SourceBucket: Type: AWS::S3::Bucket Properties: VersioningConfiguration: Status: Enabled CodePipelineArtifactStoreBucket: Type: AWS::S3::Bucket CodePipelineArtifactStoreBucketPolicy: Type: AWS::S3::BucketPolicy Properties: Bucket: !Ref CodePipelineArtifactStoreBucket PolicyDocument: Version: 2012-10-17 Statement: - Sid: DenyUnEncryptedObjectUploads Effect: Deny Principal: '*' Action: s3:PutObject Resource: !Join [ '', [ !GetAtt CodePipelineArtifactStoreBucket.Arn, '/*' ] ] Condition: StringNotEquals: s3:x-amz-server-side-encryption: aws:kms - Sid: DenyInsecureConnections Effect: Deny Principal: '*' Action: s3:* Resource: !Join [ '', [ !GetAtt CodePipelineArtifactStoreBucket.Arn, '/*' ] ] Condition: Bool: aws:SecureTransport: false CodePipelineServiceRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: Service: - codepipeline.amazonaws.com Action: sts:AssumeRole Path: / Policies: - PolicyName: AWS-CodePipeline-Service-3 PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - codecommit:CancelUploadArchive - codecommit:GetBranch - codecommit:GetCommit - codecommit:GetUploadArchiveStatus - codecommit:UploadArchive Resource: 'resource_ARN' - Effect: Allow Action: - codedeploy:CreateDeployment - codedeploy:GetApplicationRevision - codedeploy:GetDeployment - codedeploy:GetDeploymentConfig - codedeploy:RegisterApplicationRevision Resource: 'resource_ARN' - Effect: Allow Action: - codebuild:BatchGetBuilds - codebuild:StartBuild Resource: 'resource_ARN' - Effect: Allow Action: - devicefarm:ListProjects - devicefarm:ListDevicePools - devicefarm:GetRun - devicefarm:GetUpload - devicefarm:CreateUpload - devicefarm:ScheduleRun Resource: 'resource_ARN' - Effect: Allow Action: - lambda:InvokeFunction - lambda:ListFunctions Resource: 'resource_ARN' - Effect: Allow Action: - iam:PassRole Resource: 'resource_ARN' - Effect: Allow Action: - elasticbeanstalk:* - ec2:* - elasticloadbalancing:* - autoscaling:* - cloudwatch:* - s3:* - sns:* - cloudformation:* - rds:* - sqs:* - ecs:* Resource: 'resource_ARN' AppPipeline: Type: AWS::CodePipeline::Pipeline Properties: Name: s3-events-pipeline RoleArn: !GetAtt CodePipelineServiceRole.Arn Stages: - 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 - Name: Beta Actions: - Name: BetaAction InputArtifacts: - Name: SourceOutput ActionTypeId: Category: Deploy Owner: AWS Version: 1 Provider: CodeDeploy Configuration: ApplicationName: !Ref ApplicationName DeploymentGroupName: !Ref BetaFleet RunOrder: 1 ArtifactStore: Type: S3 Location: !Ref CodePipelineArtifactStoreBucket 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 ] ] EventRule: Type: AWS::Events::Rule Properties: EventPattern: source: - aws.s3 detail-type: - 'AWS API Call via CloudTrail' detail: eventSource: - s3.amazonaws.com eventName: - PutObject - CompleteMultipartUpload resources: ARN: - !Join [ '', [ !GetAtt SourceBucket.Arn, '/', !Ref SourceObjectKey ] ] Targets: - Arn: !Join [ '', [ 'arn:aws:codepipeline:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':', !Ref AppPipeline ] ] RoleArn: !GetAtt EventRole.Arn Id: codepipeline-AppPipeline Outputs: SourceBucketARN: Description: "S3 bucket ARN that Cloudtrail will use" Value: !GetAtt SourceBucket.Arn Export: Name: SourceBucketARN
JSON
"Resources": { "SourceBucket": { "Type": "AWS::S3::Bucket", "Properties": { "VersioningConfiguration": { "Status": "Enabled" } } }, "CodePipelineArtifactStoreBucket": { "Type": "AWS::S3::Bucket" }, "CodePipelineArtifactStoreBucketPolicy": { "Type": "AWS::S3::BucketPolicy", "Properties": { "Bucket": { "Ref": "CodePipelineArtifactStoreBucket" }, "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Sid": "DenyUnEncryptedObjectUploads", "Effect": "Deny", "Principal": "*", "Action": "s3:PutObject", "Resource": { "Fn::Join": [ "", [ { "Fn::GetAtt": [ "CodePipelineArtifactStoreBucket", "Arn" ] }, "/*" ] ] }, "Condition": { "StringNotEquals": { "s3:x-amz-server-side-encryption": "aws:kms" } } }, { "Sid": "DenyInsecureConnections", "Effect": "Deny", "Principal": "*", "Action": "s3:*", "Resource": { "Fn::Join": [ "", [ { "Fn::GetAtt": [ "CodePipelineArtifactStoreBucket", "Arn" ] }, "/*" ] ] }, "Condition": { "Bool": { "aws:SecureTransport": false } } } ] } } }, "CodePipelineServiceRole": { "Type": "AWS::IAM::Role", "Properties": { "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": [ "codepipeline.amazonaws.com" ] }, "Action": "sts:AssumeRole" } ] }, "Path": "/", "Policies": [ { "PolicyName": "AWS-CodePipeline-Service-3", "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "codecommit:CancelUploadArchive", "codecommit:GetBranch", "codecommit:GetCommit", "codecommit:GetUploadArchiveStatus", "codecommit:UploadArchive" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "codedeploy:CreateDeployment", "codedeploy:GetApplicationRevision", "codedeploy:GetDeployment", "codedeploy:GetDeploymentConfig", "codedeploy:RegisterApplicationRevision" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "codebuild:BatchGetBuilds", "codebuild:StartBuild" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "devicefarm:ListProjects", "devicefarm:ListDevicePools", "devicefarm:GetRun", "devicefarm:GetUpload", "devicefarm:CreateUpload", "devicefarm:ScheduleRun" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "lambda:InvokeFunction", "lambda:ListFunctions" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "iam:PassRole" ], "Resource": "resource_ARN" }, { "Effect": "Allow", "Action": [ "elasticbeanstalk:*", "ec2:*", "elasticloadbalancing:*", "autoscaling:*", "cloudwatch:*", "s3:*", "sns:*", "cloudformation:*", "rds:*", "sqs:*", "ecs:*" ], "Resource": "resource_ARN" } ] } } ] } }, "AppPipeline": { "Type": "AWS::CodePipeline::Pipeline", "Properties": { "Name": "s3-events-pipeline", "RoleArn": { "Fn::GetAtt": [ "CodePipelineServiceRole", "Arn" ] }, "Stages": [ { "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 } ] }, { "Name": "Beta", "Actions": [ { "Name": "BetaAction", "InputArtifacts": [ { "Name": "SourceOutput" } ], "ActionTypeId": { "Category": "Deploy", "Owner": "AWS", "Version": 1, "Provider": "CodeDeploy" }, "Configuration": { "ApplicationName": { "Ref": "ApplicationName" }, "DeploymentGroupName": { "Ref": "BetaFleet" } }, "RunOrder": 1 } ] } ], "ArtifactStore": { "Type": "S3", "Location": { "Ref": "CodePipelineArtifactStoreBucket" } } } }, "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" } ] ] } } ] } } ] } }, "EventRule": { "Type": "AWS::Events::Rule", "Properties": { "EventPattern": { "source": [ "aws.s3" ], "detail-type": [ "AWS API Call via CloudTrail" ], "detail": { "eventSource": [ "s3.amazonaws.com" ], "eventName": [ "PutObject", "CompleteMultipartUpload" ], "resources": { "ARN": [ { "Fn::Join": [ "", [ { "Fn::GetAtt": [ "SourceBucket", "Arn" ] }, "/", { "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" } ] } } }, "Outputs" : { "SourceBucketARN" : { "Description" : "S3 bucket ARN that Cloudtrail will use", "Value" : { "Fn::GetAtt": ["SourceBucket", "Arn"] }, "Export" : { "Name" : "SourceBucketARN" } } } } ...

GitHub 버전 1 소스 작업의 폴링 파이프라인을 연결로 마이그레이션합니다.

외부 리포지토리의 연결을 사용하도록 GitHub 버전 1 소스 작업을 마이그레이션할 수 있습니다. GitHub버전 1 소스 작업이 있는 파이프라인에 권장되는 변경 감지 방법입니다.

GitHub 버전 1 소스 작업이 있는 파이프라인의 경우 GitHub 버전 2 작업을 사용하도록 파이프라인을 수정하여 변경 감지가 자동화되도록 하는 것이 좋습니다. AWS CodeConnections연결 관련 작업에 대한 자세한 내용은 GitHub 연결 섹션을 참조하세요.

GitHub (콘솔) 에 대한 연결 생성

콘솔을 사용하여 연결을 생성할 수 GitHub 있습니다.

1단계: 버전 1 교체 GitHub 작업

파이프라인 편집 페이지를 사용하여 버전 1 GitHub 작업을 버전 2 GitHub 작업으로 교체하십시오.

버전 1 GitHub 작업을 교체하려면
  1. CodePipeline 콘솔에 로그인합니다.

  2. 파이프라인을 선택한 다음 편집을 선택합니다. 소스 단계에서 단계 편집을 선택합니다. 작업 업데이트를 권장하는 메시지가 표시됩니다.

  3. 액션 제공자에서 GitHub (버전 2) 를 선택합니다.

  4. 다음 중 하나를 수행합니다.

    • 공급자와의 연결을 아직 생성하지 않은 경우 연결에서 Connect to를 선택합니다 GitHub. 2단계: 연결 만들기로 GitHub 진행하십시오.

    • 연결에서 공급자와의 연결을 이미 생성한 경우 연결을 선택합니다. 3단계: 연결에 대한 소스 작업 저장으로 이동합니다.

2단계: 연결 만들기 GitHub

연결을 생성하도록 선택하면 Connect to GitHub 페이지가 표시됩니다.

연결을 만들려면 GitHub
  1. GitHub 연결 설정에서 연결 이름은 연결 이름에 표시됩니다.

    앱에서 GitHub 앱 설치를 선택하거나 새 앱 설치를 선택하여 앱을 생성합니다.

    참고

    특정 공급자에 대한 모든 연결에 대해 하나의 앱을 설치합니다. 이미 앱을 설치한 경우 GitHub 앱을 선택하고 이 단계를 건너뛰십시오.

  2. 의 인증 페이지가 GitHub 표시되면 자격 증명으로 로그인한 다음 계속을 선택하십시오.

  3. 앱 설치 페이지에서 앱이 사용자 GitHub 계정에 연결을 시도하고 있다는 메시지가 표시됩니다. AWS CodeStar

    참고

    앱은 GitHub 계정당 한 번만 설치합니다. 이전에 앱을 설치한 경우 구성을 선택하여 앱 설치의 수정 페이지로 이동하거나 뒤로 버튼을 사용하여 콘솔로 돌아갈 수 있습니다.

  4. AWS CodeStar설치 페이지에서 설치를 선택합니다.

  5. Connect to GitHub 페이지에 새 설치의 연결 ID가 표시됩니다. 연결을 선택합니다.

3단계: GitHub 소스 액션 저장

작업 편집 페이지에서 업데이트를 완료하여 새 소스 작업을 저장합니다.

GitHub 소스 액션을 저장하려면
  1. 리포지토리에서 타사 리포지토리의 이름을 입력합니다. 브랜치에서, 파이프라인에서 소스 변경 사항을 감지할 브랜치를 입력합니다.

    참고

    리포지토리에 다음 예와 같이 owner-name/repository-name을 입력합니다.

    my-account/my-repository
  2. 출력 아티팩트 형식에서 아티팩트의 형식을 선택합니다.

  3. 출력 아티팩트에서 이 작업에 대한 출력 아티팩트의 이름을 유지할 수 있습니다(예: SourceArtifact). 완료를 선택하여 작업 편집 페이지를 닫습니다.

  4. 완료를 선택하여 단계 편집 페이지를 닫습니다. 저장을 선택하여 파이프라인 편집 페이지를 닫습니다.

GitHub (CLI) 에 대한 연결 만들기

AWS Command Line Interface (AWS CLI) 를 사용하여 연결을 만들 수 GitHub 있습니다.

이렇게 하려면 create-connection 명령을 사용합니다.

중요

OR를 통해 생성된 AWS CloudFormation 연결은 기본적으로 PENDING 상태입니다. AWS CLI CLI AWS CloudFormation OR로 연결을 만든 후 콘솔을 사용하여 연결을 편집하여 상태를 설정합니다AVAILABLE.

연결을 만들려면 GitHub
  1. 터미널(Linux, macOS, Unix) 또는 명령 프롬프트(Windows)를 엽니다. AWS CLI 를 사용하여 연결에 --connection-name 대해 --provider-type 및 를 지정하여 create-connection 명령을 실행합니다. 이 예제에서 타사 공급자 이름은 GitHub이고 지정된 연결 이름은 MyConnection입니다.

    aws codeconnections create-connection --provider-type GitHub --connection-name MyConnection

    성공하면 이 명령은 다음과 유사한 연결 ARN 정보를 반환합니다.

    { "ConnectionArn": "arn:aws:codeconnections:us-west-2:account_id:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f" }
  2. 콘솔을 사용하여 연결을 완료합니다.

GitHub 버전 1 소스 작업의 폴링 파이프라인을 웹후크로 마이그레이션합니다.

웹후크를 사용하여 소스 리포지토리의 변경 사항을 감지하도록 파이프라인을 마이그레이션할 수 있습니다. GitHub 웹후크로의 마이그레이션은 GitHub 버전 1 작업에만 해당됩니다.

중요

CodePipeline 웹후크를 생성할 때 자체 자격 증명을 사용하거나 여러 웹후크에 동일한 비밀 토큰을 재사용하지 마십시오. 최적의 보안을 위해 생성하는 각 웹후크에 대해 고유한 비밀 토큰을 생성하십시오. 보안 토큰은 사용자가 제공하는 임의의 문자열로, 웹후크 페이로드의 무결성과 신뢰성을 보호하기 위해 CodePipeline 전송되는 웹후크 페이로드를 계산하고 서명하는 데 GitHub 사용됩니다. 자체 자격 증명을 사용하거나 여러 웹후크에 동일한 토큰을 재사용하면 보안 취약성이 발생할 수 있습니다.

폴링 파이프라인을 웹훅으로 마이그레이션 (GitHub 버전 1 소스 액션) (콘솔)

GitHub 버전 1 소스 작업의 경우 CodePipeline 콘솔을 사용하여 웹후크를 사용하여 소스 리포지토리의 변경 사항을 감지하도록 파이프라인을 업데이트할 수 있습니다. GitHub

다음 단계에 따라 대신 사용할 폴링 (주기적 검사) 을 사용하는 파이프라인을 편집하세요. EventBridge 파이프라인을 생성하려면 파이프라인, 스테이지, 액션 생성 단원을 참조하십시오.

콘솔을 사용할 경우 해당 파이프라인에 대한 PollForSourceChanges 파라미터가 변경됩니다. GitHub 웹후크가 자동으로 생성되고 등록됩니다.

파이프라인 소스 단계를 편집하려면
  1. http://console.aws.amazon.com/codesuite/codepipeline/home 에서 AWS Management Console 로그인하고 CodePipeline 콘솔을 엽니다.

    AWS 계정과 연결된 모든 파이프라인의 이름이 표시됩니다.

  2. [Name]에서 편집할 파이프라인의 이름을 선택합니다. 이렇게 하면 파이프라인 각 단계의 각 작업 상태를 포함하여 파이프라인의 세부 정보 보기가 열립니다.

  3. 파이프라인 세부 정보 페이지에서 [Edit]를 선택합니다.

  4. 편집 단계에서 소스 작업의 편집 아이콘을 선택합니다.

  5. 변경 감지 옵션을 확장하고 Amazon CloudWatch Events 사용을 선택하여 변경 발생 시 파이프라인을 자동으로 시작합니다 (권장).

    소스 변경을 감지하기 위해 웹후크를 GitHub 생성하라는 메시지가 표시됩니다. AWS CodePipeline 그러면 웹후크가 자동으로 CodePipeline 생성됩니다. 아래 옵션에서 옵트아웃할 수 있습니다. 업데이트를 선택합니다. 웹후크 외에도 다음을 CodePipeline 생성합니다.

    • 무작위로 생성되어 연결을 승인하는 데 사용되는 비밀입니다. GitHub

    • 리전의 퍼블릭 엔드포인트를 사용하여 생성된 웹후크URL.

    CodePipeline 웹후크를 에 등록합니다. GitHub 를 URL 구독하여 리포지토리 이벤트를 수신합니다.

  6. 파이프라인 편집을 마쳤으면 [Save pipeline changes]를 선택하여 요약 페이지로 돌아갑니다.

    파이프라인에 대해 생성될 Webhook의 이름을 표시하는 메시지가 나타납니다. [Save and continue]를 선택합니다.

  7. 작업을 테스트하려면 를 사용하여 파이프라인의 소스 단계에 지정된 소스에 변경 내용을 커밋하여 변경 내용을 릴리스하십시오. AWS CLI

폴링 파이프라인을 웹후크 (GitHub 버전 1 소스 액션) 로 마이그레이션 () CLI

대시 Webhook를 사용하도록 정기적 확인을 사용하는 파이프라인을 편집하려면 다음 단계를 수행합니다. 파이프라인을 생성하려면 파이프라인, 스테이지, 액션 생성 단원을 참조하십시오.

이벤트 기반 파이프라인을 빌드하려면 파이프라인의 PollForSourceChanges 파라미터를 편집한 후 다음 리소스를 수동으로 생성합니다.

  • GitHub 웹후크 및 권한 부여 매개변수

Webhook를 생성하고 등록하려면
참고

OR를 사용하여 파이프라인을 생성하고 웹후크를 추가할 때는 정기 검사를 비활성화해야 합니다. CLI AWS CloudFormation 주기적 점검을 비활성화하지 않으려면 아래의 마지막 절차에서 설명한 대로 PollForSourceChanges 파라미터를 명시적으로 추가하고 false로 설정해야 합니다. 그렇지 않으면 CLI 또는 AWS CloudFormation 파이프라인의 PollForSourceChanges 기본값은 true이며 파이프라인 구조 출력에 표시되지 않습니다. PollForSourceChanges 기본값에 대한 자세한 내용은 을 참조하십시오. PollForSourceChanges 파라미터에 대한 유효한 설정

  1. 텍스트 편집기에서 만들려는 웹훅용 JSON 파일을 만들고 저장합니다. my-webhook라는 Webhook에 이 샘플 파일을 사용합니다.

    { "webhook": { "name": "my-webhook", "targetPipeline": "pipeline_name", "targetAction": "source_action_name", "filters": [{ "jsonPath": "$.ref", "matchEquals": "refs/heads/{Branch}" }], "authentication": "GITHUB_HMAC", "authenticationConfiguration": { "SecretToken": "secret" } } }
  2. put-webhook 명령을 호출하고 --cli-input--region 파라미터를 포함시킵니다.

    다음 샘플 명령은 파일과 함께 웹후크를 만듭니다. webhook_json JSON

    aws codepipeline put-webhook --cli-input-json file://webhook_json.json --region "eu-central-1"
  3. 이 예제에 표시된 출력에서는 라는 웹후크에 대해 URL 및 ARN 가 반환됩니다. my-webhook

    { "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:ACCOUNT_ID:webhook:my-webhook" }, "tags": [{ "key": "Project", "value": "ProjectA" }] }

    이 예제는 Webhook에 Project 태그 키와 ProjectA 값을 포함하여 Webhook에 태그 지정을 추가합니다. 에서 CodePipeline 리소스에 태그를 지정하는 방법에 대한 자세한 내용은 을 참조하십시오. 리소스에 태그 지정

  4. register-webhook-with-third-party 명령을 호출하고 --webhook-name 파라미터를 포함시킵니다.

    다음 샘플 명령은 my-webhook이라는 Webhook을 등록합니다.

    aws codepipeline register-webhook-with-third-party --webhook-name my-webhook
파이프라인 파라미터를 편집하려면 PollForSourceChanges
중요

이 방법으로 파이프라인을 생성할 때 명시적으로 false로 설정되지 않은 경우 PollForSourceChanges 파라미터 기본값은 true입니다. 이벤트 기반 변경 감지를 추가할 때는 출력에 파라미터를 추가하고 false로 설정하여 폴링을 비활성화해야 합니다. 그렇지 않으면 파이프라인이 단일 소스 변경 시 두 번 시작됩니다. 세부 정보는 PollForSourceChanges 파라미터에 대한 유효한 설정을 참조하세요.

  1. get-pipeline명령을 실행하여 파이프라인 구조를 JSON 파일에 복사합니다. 예를 들어 MyFirstPipeline이라는 파이프라인에 대해 다음 명령을 입력합니다.

    aws codepipeline get-pipeline --name MyFirstPipeline >pipeline.json

    이 명령은 아무 것도 반환하지 않지만 생성한 파일이 명령을 실행한 디렉터리에 표시되어야 합니다.

  2. 일반 텍스트 편집기에서 JSON 파일을 열고 파라미터를 변경하거나 추가하여 소스 스테이지를 편집합니다PollForSourceChanges. 이 예시에서는 UserGitHubRepo라는 리포지토리의 경우 파라미터가 false로 설정됩니다.

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

    "configuration": { "Owner": "name", "Repo": "UserGitHubRepo", "PollForSourceChanges": "false", "Branch": "main", "OAuthToken": "****" },
  3. get-pipeline명령을 사용하여 검색한 파이프라인 구조로 작업하는 경우 파일에서 metadata 라인을 제거하여 JSON 파일의 구조를 편집해야 합니다. 이렇게 하지 않으면 update-pipeline 명령에서 사용할 수 없습니다. JSON파일의 파이프라인 구조에서: "created""pipelineARN", { }"updated" 필드를 포함한 "metadata" 섹션을 제거합니다.

    예를 들어, 구조에서 다음 행을 삭제합니다.

    "metadata": { "pipelineArn": "arn:aws:codepipeline:region:account-ID:pipeline-name", "created": "date", "updated": "date" },

    파일을 저장합니다.

  4. 변경 내용을 적용하려면 다음과 같이 파이프라인 JSON 파일을 지정하여 update-pipeline 명령을 실행합니다.

    중요

    파일 이름 앞에 file://를 포함해야 합니다. 이 명령에 필수적입니다.

    aws codepipeline update-pipeline --cli-input-json file://pipeline.json

    이 명령은 편집한 파이프라인의 전체 구조를 반환합니다.

    참고

    update-pipeline 명령을 실행하면 파이프라인이 중지됩니다. update-pipeline 명령을 실행할 때 파이프라인을 통해 개정을 실행하는 중이라면 해당 실행이 중지됩니다. 업데이트된 파이프라인을 통해 해당 개정을 실행하려면 파이프라인을 수동으로 시작해야 합니다. start-pipeline-execution 명령을 사용하여 수동으로 파이프라인을 시작합니다.

푸시 이벤트에 대한 파이프라인 업데이트 (GitHub 버전 1 소스 액션) (AWS CloudFormation 템플릿)

다음 단계에 따라 GitHub 소스 포함 파이프라인을 정기 점검 (폴링) 에서 웹후크를 사용한 이벤트 기반 변경 감지로 업데이트하세요.

를 사용하여 이벤트 기반 파이프라인을 구축하려면 파이프라인의 PollForSourceChanges 파라미터를 편집한 다음 템플릿에 웹후크 리소스를 추가합니다. AWS CodeCommit GitHub

를 AWS CloudFormation 사용하여 파이프라인을 만들고 관리하는 경우 템플릿에는 다음과 같은 콘텐츠가 있습니다.

참고

소스 단계의 PollForSourceChanges 구성 속성을 메모합니다. 템플릿에 해당 속성이 포함되어 있지 않으면 기본적으로 PollForSourceChangestrue로 설정됩니다.

YAML
Resources: AppPipeline: Type: AWS::CodePipeline::Pipeline Properties: Name: github-polling-pipeline RoleArn: !GetAtt CodePipelineServiceRole.Arn Stages: - Name: Source Actions: - Name: SourceAction ActionTypeId: Category: Source Owner: ThirdParty Version: 1 Provider: GitHub OutputArtifacts: - Name: SourceOutput Configuration: Owner: !Ref GitHubOwner Repo: !Ref RepositoryName Branch: !Ref BranchName OAuthToken: {{resolve:secretsmanager:MyGitHubSecret:SecretString:token}} PollForSourceChanges: true RunOrder: 1 ...
JSON
"AppPipeline": { "Type": "AWS::CodePipeline::Pipeline", "Properties": { "Name": "github-polling-pipeline", "RoleArn": { "Fn::GetAtt": [ "CodePipelineServiceRole", "Arn" ] }, "Stages": [ { "Name": "Source", "Actions": [ { "Name": "SourceAction", "ActionTypeId": { "Category": "Source", "Owner": "ThirdParty", "Version": 1, "Provider": "GitHub" }, "OutputArtifacts": [ { "Name": "SourceOutput" } ], "Configuration": { "Owner": { "Ref": "GitHubOwner" }, "Repo": { "Ref": "RepositoryName" }, "Branch": { "Ref": "BranchName" }, "OAuthToken": "{{resolve:secretsmanager:MyGitHubSecret:SecretString:token}}", "PollForSourceChanges": true }, "RunOrder": 1 } ] }, ...
템플릿에서 파라미터를 추가하고 Webhook를 만들려면

자격 증명을 저장하는 AWS Secrets Manager 데 사용하는 것이 좋습니다. Secrets Manager를 사용하는 경우 Secrets Manager에서 보안 파라미터를 이미 구성하고 저장했어야 합니다. 이 예제에서는 웹훅의 GitHub 자격 증명을 위해 Secrets Manager에 대한 동적 참조를 사용합니다. 자세한 내용은 동적 참조를 사용하여 템플릿 값 지정을 참조하십시오.

중요

보안 파라미터를 전달할 때는 값을 템플릿에 직접 입력하지 마십시오. 값은 일반 텍스트로 렌더링되므로 읽을 수 있습니다. 보안상의 이유로 AWS CloudFormation 템플릿에 일반 텍스트를 사용하여 자격 증명을 저장하지 마십시오.

OR를 사용하여 파이프라인을 생성하고 웹후크를 추가할 때는 정기 검사를 비활성화해야 합니다. CLI AWS CloudFormation

참고

주기적 점검을 비활성화하지 않으려면 아래의 마지막 절차에서 설명한 대로 PollForSourceChanges 파라미터를 명시적으로 추가하고 false로 설정해야 합니다. 그렇지 않으면 CLI 또는 AWS CloudFormation 파이프라인의 PollForSourceChanges 기본값은 true이며 파이프라인 구조 출력에 표시되지 않습니다. PollForSourceChanges 기본값에 대한 자세한 내용은 을 참조하십시오. PollForSourceChanges 파라미터에 대한 유효한 설정

  1. 템플릿에서 Resources에 파라미터를 추가합니다.

    YAML
    Parameters: GitHubOwner: Type: String ...
    JSON
    { "Parameters": { "BranchName": { "Description": "GitHub branch name", "Type": "String", "Default": "main" }, "GitHubOwner": { "Type": "String" }, ...
  2. AWS::CodePipeline::Webhook AWS CloudFormation 리소스를 사용하여 웹후크를 추가합니다.

    참고

    지정한 TargetAction은 파이프라인에 정의된 소스 작업의 Name 속성과 일치해야 합니다.

    RegisterWithThirdParty 설정된 true 경우 에 연결된 사용자가 필수 범위를 설정할 OAuthToken 수 있는지 확인하십시오. GitHub 토큰과 웹후크에는 다음과 같은 GitHub 범위가 필요합니다.

    • repo - 퍼블릭 및 프라이빗 리포지토리에서 파이프라인으로 아티팩트를 읽고 가져올 수 있도록 완전히 제어하는 데 사용됩니다.

    • admin:repo_hook - 리포지토리 후크를 완전히 제어하는 데 사용됩니다.

    그렇지 않으면 GitHub 404를 반환합니다. 반환된 404에 대한 자세한 내용은 https://help.github.com/articles/about-webhooks 단원을 참조하십시오.

    YAML
    AppPipelineWebhook: Type: AWS::CodePipeline::Webhook Properties: Authentication: GITHUB_HMAC AuthenticationConfiguration: SecretToken: {{resolve:secretsmanager:MyGitHubSecret:SecretString:token}} Filters: - JsonPath: "$.ref" MatchEquals: refs/heads/{Branch} TargetPipeline: !Ref AppPipeline TargetAction: SourceAction Name: AppPipelineWebhook TargetPipelineVersion: !GetAtt AppPipeline.Version RegisterWithThirdParty: true ...
    JSON
    "AppPipelineWebhook": { "Type": "AWS::CodePipeline::Webhook", "Properties": { "Authentication": "GITHUB_HMAC", "AuthenticationConfiguration": { "SecretToken": "{{resolve:secretsmanager:MyGitHubSecret:SecretString:token}}" }, "Filters": [{ "JsonPath": "$.ref", "MatchEquals": "refs/heads/{Branch}" }], "TargetPipeline": { "Ref": "AppPipeline" }, "TargetAction": "SourceAction", "Name": "AppPipelineWebhook", "TargetPipelineVersion": { "Fn::GetAtt": [ "AppPipeline", "Version" ] }, "RegisterWithThirdParty": true } }, ...
  3. 업데이트된 템플릿을 로컬 컴퓨터에 저장한 다음 AWS CloudFormation 콘솔을 엽니다.

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

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

  6. 실행을 선택합니다.

파이프라인 PollForSourceChanges 파라미터를 편집하려면
중요

이 방법으로 파이프라인을 생성할 때 명시적으로 false로 설정되지 않은 경우 PollForSourceChanges 파라미터 기본값은 true입니다. 이벤트 기반 변경 감지를 추가할 때는 출력에 파라미터를 추가하고 false로 설정하여 폴링을 비활성화해야 합니다. 그렇지 않으면 파이프라인이 단일 소스 변경 시 두 번 시작됩니다. 세부 정보는 PollForSourceChanges 파라미터에 대한 유효한 설정을 참조하세요.

  • 템플릿에서 PollForSourceChangesfalse로 변경합니다. PollForSourceChanges를 파이프라인 정의에 포함하지 않은 경우 추가하고 false로 설정하세요.

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

    YAML
    Name: Source Actions: - Name: SourceAction ActionTypeId: Category: Source Owner: ThirdParty Version: 1 Provider: GitHub OutputArtifacts: - Name: SourceOutput Configuration: Owner: !Ref GitHubOwner Repo: !Ref RepositoryName Branch: !Ref BranchName OAuthToken: {{resolve:secretsmanager:MyGitHubSecret:SecretString:token}} PollForSourceChanges: false RunOrder: 1
    JSON
    { "Name": "Source", "Actions": [{ "Name": "SourceAction", "ActionTypeId": { "Category": "Source", "Owner": "ThirdParty", "Version": 1, "Provider": "GitHub" }, "OutputArtifacts": [{ "Name": "SourceOutput" }], "Configuration": { "Owner": { "Ref": "GitHubOwner" }, "Repo": { "Ref": "RepositoryName" }, "Branch": { "Ref": "BranchName" }, "OAuthToken": "{{resolve:secretsmanager:MyGitHubSecret:SecretString:token}}", PollForSourceChanges: false }, "RunOrder": 1 }]

를 사용하여 이러한 리소스를 생성하면 지정된 GitHub 리포지토리에 정의된 웹후크가 생성됩니다. AWS CloudFormation커밋 시 파이프라인이 트리거됩니다.

YAML
Parameters: GitHubOwner: Type: String Resources: AppPipelineWebhook: Type: AWS::CodePipeline::Webhook Properties: Authentication: GITHUB_HMAC AuthenticationConfiguration: SecretToken: {{resolve:secretsmanager:MyGitHubSecret:SecretString:token}} Filters: - JsonPath: "$.ref" MatchEquals: refs/heads/{Branch} TargetPipeline: !Ref AppPipeline TargetAction: SourceAction Name: AppPipelineWebhook TargetPipelineVersion: !GetAtt AppPipeline.Version RegisterWithThirdParty: true AppPipeline: Type: AWS::CodePipeline::Pipeline Properties: Name: github-events-pipeline RoleArn: !GetAtt CodePipelineServiceRole.Arn Stages: - Name: Source Actions: - Name: SourceAction ActionTypeId: Category: Source Owner: ThirdParty Version: 1 Provider: GitHub OutputArtifacts: - Name: SourceOutput Configuration: Owner: !Ref GitHubOwner Repo: !Ref RepositoryName Branch: !Ref BranchName OAuthToken: {{resolve:secretsmanager:MyGitHubSecret:SecretString:token}} PollForSourceChanges: false RunOrder: 1 ...
JSON
{ "Parameters": { "BranchName": { "Description": "GitHub branch name", "Type": "String", "Default": "main" }, "RepositoryName": { "Description": "GitHub repository name", "Type": "String", "Default": "test" }, "GitHubOwner": { "Type": "String" }, "ApplicationName": { "Description": "CodeDeploy application name", "Type": "String", "Default": "DemoApplication" }, "BetaFleet": { "Description": "Fleet configured in CodeDeploy", "Type": "String", "Default": "DemoFleet" } }, "Resources": { ... }, "AppPipelineWebhook": { "Type": "AWS::CodePipeline::Webhook", "Properties": { "Authentication": "GITHUB_HMAC", "AuthenticationConfiguration": { "SecretToken": { "{{resolve:secretsmanager:MyGitHubSecret:SecretString:token}}" } }, "Filters": [ { "JsonPath": "$.ref", "MatchEquals": "refs/heads/{Branch}" } ], "TargetPipeline": { "Ref": "AppPipeline" }, "TargetAction": "SourceAction", "Name": "AppPipelineWebhook", "TargetPipelineVersion": { "Fn::GetAtt": [ "AppPipeline", "Version" ] }, "RegisterWithThirdParty": true } }, "AppPipeline": { "Type": "AWS::CodePipeline::Pipeline", "Properties": { "Name": "github-events-pipeline", "RoleArn": { "Fn::GetAtt": [ "CodePipelineServiceRole", "Arn" ] }, "Stages": [ { "Name": "Source", "Actions": [ { "Name": "SourceAction", "ActionTypeId": { "Category": "Source", "Owner": "ThirdParty", "Version": 1, "Provider": "GitHub" }, "OutputArtifacts": [ { "Name": "SourceOutput" } ], "Configuration": { "Owner": { "Ref": "GitHubOwner" }, "Repo": { "Ref": "RepositoryName" }, "Branch": { "Ref": "BranchName" }, "OAuthToken": "{{resolve:secretsmanager:MyGitHubSecret:SecretString:token}}", "PollForSourceChanges": false }, "RunOrder": 1 ...