

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

# ポーリングパイプラインをイベントベースの変更検出の使用に移行する
<a name="update-change-detection"></a>

AWS CodePipeline は、コードが変更されるたびにパイプラインを開始するなど、完全なend-to-endの継続的配信をサポートします。コードの変更時にパイプラインを開始するために、イベントベースの変更検出とポーリングの 2 つの方法がサポートされています。パイプラインにはイベントベースの変更検出を使用することをお勧めします。

ここで説明する手順を使用して、ポーリングパイプラインからイベントベースの変更検出方法に移行 (更新) します。

パイプラインに推奨されるイベントベースの変更検出方法は、CodeCommit などのパイプラインソースによって決まります。その場合、例えば、ポーリングパイプラインを EventBridge によるイベントベースの変更検出に移行する必要があります。

## ポーリングパイプラインを移行する方法
<a name="update-change-detection-overview"></a>

ポーリングパイプラインを移行するには、ポーリングパイプラインを選択した後、推奨されるイベントベースの変更検出方法を選択します。
+ [アカウント内のポーリングパイプラインの表示](#update-change-detection-view-polling) のステップを使用して、ポーリングパイプラインを選択します。
+ 表でパイプラインのソースタイプを見つけて、ポーリングパイプラインの移行に使用する実装の手順を選択します。各セクションには、CLI や CloudFormationの使用など、複数の移行方法があります。


<table>
<thead>
  <tr><th colspan="3">パイプラインを推奨される変更検出方法に移行する方法</th></tr>
  <tr><th>パイプラインソース</th><th>イベントベースの検出 (推奨方法)</th><th>移行手順</th></tr>
</thead>
<tbody>
  <tr><td>AWS CodeCommit</td><td>EventBridge (推奨)。</td><td>「[CodeCommit ソースを使用してポーリングパイプラインを移行する](#update-change-detection-codecommit)」を参照してください。</td></tr>
  <tr><td>Amazon S3</td><td>EventBridge およびイベント通知を有効にしたバケット (推奨)。</td><td>「[イベントに対応した S3 ソースを使用してポーリングパイプラインを移行する](#update-change-detection-S3-event)」を参照してください。</td></tr>
  <tr><td>Amazon S3</td><td>EventBridge と証 AWS CloudTrail 跡。</td><td>「[S3 ソースと CloudTrail 証跡を使用してポーリングパイプラインを移行する](#update-change-detection-S3)」を参照してください。</td></tr>
  <tr><td>GitHub (GitHub アプリ経由)</td><td>Connections (推奨)</td><td>「[GitHub (OAuth アプリ経由) ソースアクションのポーリングパイプラインを接続に移行する](#update-change-detection-github-connection)」を参照してください。</td></tr>
  <tr><td>GitHub (OAuth アプリ経由)</td><td>ウェブフック</td><td>「[GitHub (OAuth アプリ経由) ソースアクションのポーリングパイプラインを Webhook に移行する](#update-change-detection-github-webhooks)」を参照してください。</td></tr>
</tbody>
</table>


**重要**  
GitHub (OAuth アプリ経由) アクションを含むパイプラインなど、該当するパイプラインアクション設定の更新では、ソースアクションの設定内で `PollForSourceChanges` パラメータを明示的に *false* に設定して、パイプラインのポーリングを停止する必要があります。その結果、例えば、EventBridge ルールを設定すると同時に `PollForSourceChanges` パラメータを省略することで、イベントベースの変更検出とポーリングの*両方*を使用するようにパイプラインを誤って設定する可能性があります。これにより、パイプラインが重複して実行される可能性があり、パイプラインはポーリング中のパイプラインの合計数の制限に対してカウントされます。この制限はデフォルトではイベントベースのパイプラインよりもかなり低くなっています。詳細については、「[AWS の CodePipeline 中のクォータ](limits.md)」を参照してください。



## アカウント内のポーリングパイプラインの表示
<a name="update-change-detection-view-polling"></a>

最初のステップとして、以下のスクリプトのいずれかを使用して、アカウント内のどのパイプラインに対してポーリングが設定されているかを確認します。これらがイベントベースの変更検出に移行するパイプラインです。

### アカウント内のポーリングパイプラインの表示 (スクリプト)
<a name="update-change-detection-view-polling-script"></a>

以下の手順でスクリプトを使用して、アカウントでポーリングを使用しているパイプラインを特定します。

1. ターミナルウィンドウを開き、次のいずれかの操作を行います。
   + 以下のコマンドを実行して、**PollingPipelinesExtractor.sh** という名前の新しいスクリプトを作成します。

     ```
     vi PollingPipelinesExtractor.sh
     ```
   + Python スクリプトを使用するには、以下のコマンドを実行して、**PollingPipelinesExtractor.py** という名前の新しい Python スクリプトを作成します。

     ```
     vi PollingPipelinesExtractor.py
     ```

1. 以下のコードをコピーして、**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))
     ```

1. パイプラインがあるリージョンごとに、そのリージョンに対してこのスクリプトを実行する必要があります。スクリプトを実行するには、以下のいずれかの操作を行います。
   + 以下のコマンドを実行して、**PollingPipelinesExtractor.sh** という名前のスクリプトを実行します。この例で、リージョンは us-west-2 です。

     ```
     ./PollingPipelinesExtractor.sh us-west-2
     ```
   + Python スクリプトを使用する場合は、以下のコマンドを実行して、**PollingPipelinesExtractor.py** という名前の Python スクリプトを実行します。この例で、リージョンは 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 ソースアクションリファレンス](action-reference-S3.md) で「Amazon S3 のソースアクションの設定パラメータ」など、「パイプラインのソースアクションの設定パラメータ」を参照してください。

   このスクリプトは、アカウント内のポーリングパイプラインのリストを含む .csv ファイルも生成し、その .csv ファイルを現在の作業フォルダに保存します。

## CodeCommit ソースを使用してポーリングパイプラインを移行する
<a name="update-change-detection-codecommit"></a>

EventBridge を使用してポーリングパイプラインを移行して、CodeCommit ソースリポジトリまたは Amazon S3 ソースバケットの変更を検出できるようにすることができます。

**CodeCommit** - CodeCommit ソースを使用するパイプラインでは、変更検出が EventBridge を通じて自動化されるようにパイプラインを修正します。以下のいずれかの方法で移行を実装します。
+ **コンソール: **[ポーリングパイプラインを移行する (CodeCommit または Amazon S3 ソース) (コンソール)](#update-change-detection-console-codecommit-S3)
+ **CLI: **[ポーリングパイプラインを移行する (CodeCommit ソース) (CLI)](#update-change-detection-cli-codecommit)
+ **CloudFormation: ** [ポーリングパイプラインの移行 (CodeCommit ソース) (CloudFormation テンプレート)](#update-change-detection-cfn-codecommit)

### ポーリングパイプラインを移行する (CodeCommit または Amazon S3 ソース) (コンソール)
<a name="update-change-detection-console-codecommit-S3"></a>

CodePipeline コンソールで、EventBridge を使用して CodeCommit ソースリポジトリまたは Amazon S3 ソースバケットの変更を検出するように、パイプラインを更新できます。

**注記**  
コンソールを使用して CodeCommit ソースリポジトリや Amazon S3 ソースバケットを含むパイプラインを編集すると、ルールと IAM ロールが自動的に作成されます。を使用してパイプライン AWS CLI を編集する場合は、EventBridge ルールと IAM ロールを自分で作成する必要があります。詳細については、「[CodeCommit ソースアクションと EventBridge](triggering.md)」を参照してください。

定期的なチェックを使用しているパイプラインを編集するには、これらの手順を使用します。パイプラインを作成する場合は、「[パイプライン、ステージ、アクションを作成する](pipelines-create.md)」を参照してください。

**パイプラインソースステージを編集するには**

1. にサインイン AWS マネジメントコンソール し、[http://console.aws.amazon.com/codesuite/codepipeline/home](https://console.aws.amazon.com/codesuite/codepipeline/home) で CodePipeline コンソールを開きます。

    AWS アカウントに関連付けられているすべてのパイプラインの名前が表示されます。

1. **[名前]** で、編集するパイプラインの名前を選択します。これにより、パイプラインの詳細ビューが開いて、パイプラインの各ステージの各アクションの状態などがわかります。

1. パイプライン詳細ページで、[**編集**] を選択します。

1. [**Edit (編集)**] ステージで、ソースアクションの編集アイコンを選択します。

1. [**Change Detection Options (変更検出オプション)**] を展開し、[**Use CloudWatch Events to automatically start my pipeline when a change occurs (recommended)**] を選択します。

   このパイプラインに対して作成される EventBridge ルールを示すメッセージが表示されます。**[更新]** を選択します。

   Amazon S3 ソースを含むパイプラインを更新する場合は、以下のメッセージが表示されます。**[更新]** を選択します。

1. パイプラインの編集が終わったら、[**パイプラインの変更を保存**] を選択して概要ページに戻ります。

   パイプラインに対して作成される EventBridge ルールの名前を示すメッセージが表示されます。**[保存して続行]** を選択します。

1. アクションをテストするには、 を使用して変更をリリース AWS CLI し、パイプラインのソースステージで指定されたソースに変更をコミットします。

### ポーリングパイプラインを移行する (CodeCommit ソース) (CLI)
<a name="update-change-detection-cli-codecommit"></a>

EventBridge ルールを使用してパイプラインを開始するためにポーリング (定期的なチェック) を使用しているパイプラインを編集するには、以下の手順に従います。パイプラインを作成する場合は、「[パイプライン、ステージ、アクションを作成する](pipelines-create.md)」を参照してください。

CodeCommit でイベント駆動型パイプラインを構築するには、パイプラインの `PollForSourceChanges` パラメータを編集してから、以下のリソースを作成します。
+ EventBridge イベント
+ このイベントによるパイプラインの開始を許可する IAM ロール<a name="proc-cli-flag-codecommit"></a>

**パイプラインの PollForSourceChanges パラメータを編集するには**
**重要**  
このメソッドを使用してパイプラインを作成すると、`PollForSourceChanges` パラメータはデフォルトで true になります (ただし、明示的に false に設定した場合は除きます)。イベントベースの変更検出を追加する場合は、このパラメータを出力に追加する必要があります。ポーリングを無効にするには、このパラメータを false に設定します。そうしないと、1 つのソース変更に対してパイプラインが 2 回起動されます。詳細については、「[`PollForSourceChanges` パラメータの有効な設定](PollForSourceChanges-defaults.md)」を参照してください

1. **get-pipeline** コマンドを実行して、パイプライン構造を JSON ファイルにコピーします。例えば、`MyFirstPipeline` という名前のパイプラインに対して、以下のコマンドを実行します。

   ```
   aws codepipeline get-pipeline --name {{MyFirstPipeline}} >{{pipeline.json}}
   ```

   このコマンドは何も返しませんが、作成したファイルは、コマンドを実行したディレクトリにあります。

1. 任意のプレーンテキストエディタで JSON ファイルを開き、以下に示しているように、`PollForSourceChanges` パラメータを `false` に変更してソースステージを編集します。

   **この変更を行う理由** このパラメータを `false` に変更すると、定期的チェックがオフになるため、イベントベースの変更検出のみ使用することができます。

   ```
   "configuration": {
       {{"PollForSourceChanges": "false",}}
       "BranchName": "main",
       "RepositoryName": "MyTestRepo"
   },
   ```

1. **get-pipeline** コマンドを使用して取得したパイプライン構造を使用している場合、JSON ファイルから `metadata` 行を削除します。それ以外の場合は、**update-pipeline** コマンドで使用することはできません。`"metadata": { }` 行と、`"created"`、`"pipelineARN"`、`"updated"` フィールドを削除します。

   例えば、構造から以下の行を削除します。

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

   ファイルを保存します。

1. 変更を適用するには、パイプライン JSON ファイルを指定して、**update-pipeline** コマンドを実行します。
**重要**  
ファイル名の前に必ず `file://` を含めてください。このコマンドでは必須です。

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

   このコマンドは、編集したパイプラインの構造全体を返します。
**注記**  
**update-pipeline** コマンドは、パイプラインを停止します。**update-pipeline** コマンドを実行したときにパイプラインによりリビジョンが実行されている場合、その実行は停止します。更新されたパイプラインによりそのリビジョンを実行するには、パイプラインを手動で開始する必要があります。パイプラインを手動で開始するには **`start-pipeline-execution`** コマンドを使用します。<a name="proc-cli-event-codecommit"></a>

**CodeCommit をイベントソースとして、CodePipeline をターゲットとして EventBridge ルールを作成するには**

1. EventBridge が CodePipeline を使用してルールを呼び出すためのアクセス許可を追加します。詳細については、 デベロッパーガイドの [[Amazon EventBridge のリソースベースのポリシーを使用する](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-resource-based.html)] を参照してください。

   1. 次のサンプルを使用して、EventBridge にサービスロールの引き受けを許可する信頼ポリシーを作成します。信頼ポリシーに `trustpolicyforEB.json` と名前を付けます。

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Principal": {
                      "Service": "events.amazonaws.com"
                  },
                  "Action": "sts:AssumeRole"
              }
          ]
      }
      ```

------

   1. 次のコマンドを使用して、`Role-for-MyRule` ロールを作成し、信頼ポリシーをアタッチします。

      ```
      aws iam create-role --role-name Role-for-MyRule --assume-role-policy-document file://trustpolicyforEB.json
      ```

   1. 次のサンプルに示すように、`MyFirstPipeline` というパイプラインに対して、アクセス権限ポリシー JSON を作成します。アクセス権限ポリシーに `permissionspolicyforEB.json` と名前を付けます。

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "codepipeline:StartPipelineExecution"
                  ],
                  "Resource": [
                      "arn:aws:codepipeline:us-west-2:{{111122223333}}:MyFirstPipeline"
                  ]
              }
          ]
      }
      ```

------

   1. 次のコマンドを使用して、`Role-for-MyRule` ロールに `CodePipeline-Permissions-Policy-for-EB` アクセス権限ポリシーをアタッチします。

      **この変更を行う理由** ロールにこのポリシーを追加すると、EventBridge に対するアクセス許可が作成されます。

      ```
      aws iam put-role-policy --role-name Role-for-MyRule --policy-name CodePipeline-Permissions-Policy-For-EB --policy-document file://permissionspolicyforEB.json
      ```

1. **put-rule** コマンドを呼び出し、`--name`、`--event-pattern`、`--role-arn` パラメータを含めます。

   **この変更を行う理由** このコマンドでは、 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"
   ```

1. CodePipeline をターゲットとして追加するには、**put-targets** コマンドを呼び出し、次のパラメータを含めます。
   + `--rule` パラメータは、**put-rule** を使用して作成した `rule_name` で使用されます。
   + `--targets` パラメータは、ターゲットリストのリスト `Id` とターゲットパイプラインの `ARN` で使用されます。

   次のサンプルコマンドでは、`MyCodeCommitRepoRule` と呼ばれるルールに対して指定し、ターゲット `Id` は 1 番で構成されています。これは、ルールのターゲットのリストが何であるかを示し、この場合は ターゲット 1 です。このサンプルコマンドでは、パイプラインのサンプルの `ARN` も指定されます。パイプラインは、リポジトリ内に変更が加えられると開始します。

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

1. (オプション) 特定のイメージ ID のソースオーバーライドを使用して入力トランスフォーマーを設定するには、CLI コマンドで次の JSON を使用します。次の例では、以下のオーバーライドを設定します。
   + `actionName` は (この例では `Source`)、ソースイベントから派生したものではなく、パイプラインの作成時に定義された動的な値です。
   + `revisionType` は (この例では `COMMIT_ID`)、ソースイベントから派生したものではなく、パイプラインの作成時に定義された動的な値です。
   + `revisionValue` は (この例では <{{revisionValue}}>)、ソースイベント変数から派生しています。

   ```
   {
       "Rule": "my-rule",
       "Targets": [
           {
               "Id": "MyTargetId",
               "Arn": "{{pipeline-ARN}}",
               "InputTransformer": {
                   "sourceRevisions": {
                       "actionName": "Source",
                       "revisionType": "COMMIT_ID",
                       "revisionValue": "<{{revisionValue}}>"
                   },
                   "variables": [
                       {
                           "name": "{{Branch_Name}}",
                           "value": "value"
                       }
                   ]
               }
           }
       ]
   }
   ```

### ポーリングパイプラインの移行 (CodeCommit ソース) (CloudFormation テンプレート)
<a name="update-change-detection-cfn-codecommit"></a>

を使用してイベント駆動型パイプラインを構築するには AWS CodeCommit、パイプラインの `PollForSourceChanges`パラメータを編集し、テンプレートに次のリソースを追加します。
+ EventBridge ルール
+ EventBridge ルールの IAM ロール

 CloudFormation を使用してパイプラインを作成および管理する場合、テンプレートには次のようなコンテンツが含まれます。

**注記**  
`PollForSourceChanges` と呼ばれるソースステージの `Configuration` プロパティ。プロパティがテンプレートに含まれていない場合、`PollForSourceChanges` はデフォルトで `true` に設定されます。

------
#### [ 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
        }]
    },
```

------<a name="proc-cfn-event-codecommit"></a>

**パイプライン CloudFormation テンプレートを更新して EventBridge ルールを作成するには**

1. テンプレートの で`Resources`、 `AWS::IAM::Role` CloudFormation リソースを使用して、イベントがパイプラインを開始できるようにする IAM ロールを設定します。このエントリによって、2 つのポリシーを使用するロールが作成されます。
   + 最初のポリシーでは、ロールを引き受けることを許可します。
   + 2 つめのポリシーでは、パイプラインを開始するアクセス権限が付与されます。

   **この変更を行う理由** `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. テンプレートの で`Resources`、 `AWS::Events::Rule` CloudFormation リソースを使用して EventBridge ルールを追加します。このイベントパターンは、リポジトリへの変更のプッシュをモニタリングするイベントを作成します。EventBridge でリポジトリの状態の変更が検出されると、ルールはターゲットパイプラインで `StartPipelineExecution` を呼び出します。

   **この変更を行う理由** `AWS::Events::Rule` リソースを追加すると CloudFormation 、 は イベントを作成できます。このリソースは 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"
         }
       ]
     }
   },
   ```

------

1. (オプション) 特定のイメージ ID のソースオーバーライドを使用して入力トランスフォーマーを設定するには、次の YAML スニペットを使用します。次の例では、以下のオーバーライドを設定します。
   + `actionName` は (この例では `Source`)、ソースイベントから派生したものではなく、パイプラインの作成時に定義された動的な値です。
   + `revisionType` は (この例では `COMMIT_ID`)、ソースイベントから派生したものではなく、パイプラインの作成時に定義された動的な値です。
   + `revisionValue` は (この例では <{{revisionValue}}>)、ソースイベント変数から派生しています。
   + `BranchName` および `Value` の出力変数が指定されます。

   ```
   Rule: my-rule
   Targets:
   - Id: MyTargetId
     Arn: pipeline-ARN
     InputTransformer:
       sourceRevisions:
         actionName: Source
         revisionType: COMMIT_ID
         revisionValue: <{{revisionValue}}>
       variables:
       - name: {{BranchName}}
         value: value
   ```

1. 更新されたテンプレートをローカルコンピュータに保存し、 CloudFormation コンソールを開きます。

1. スタックを選択し、[**既存スタックの変更セットの作成**] を選択します。

1. テンプレートをアップロードし、 CloudFormationに示された変更を表示します。これらがスタックに加えられる変更です。新しいリソースがリストに表示されています。

1. **[実行]** を選択してください。<a name="proc-cfn-flag-codecommit"></a>

**パイプラインの PollForSourceChanges パラメータを編集するには**
**重要**  
多くの場合、パイプラインの作成時に `PollForSourceChanges` パラメータはデフォルトで true になります。イベントベースの変更検出を追加する場合は、このパラメータを出力に追加する必要があります。ポーリングを無効にするには、このパラメータを false に設定します。そうしないと、1 つのソース変更に対してパイプラインが 2 回起動されます。詳細については、「[`PollForSourceChanges` パラメータの有効な設定](PollForSourceChanges-defaults.md)」を参照してください
+ テンプレートで、`PollForSourceChanges` を `false` に変更します。パイプライン定義に `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
      }
    ]
  },
  ```

------

**Example**  
これらのリソースを で作成すると CloudFormation、リポジトリ内のファイルが作成または更新されたときにパイプラインがトリガーされます。以下に示しているのは、最終的なテンプレートスニペットです。  

```
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


...
```

```
    "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 ソースを使用してポーリングパイプラインを移行する
<a name="update-change-detection-S3-event"></a>

Amazon S3 ソースを含むパイプラインでは、変更検出が EventBridge を通じて自動化され、イベント通知が有効になっているソースバケットを使用するように、パイプラインを修正します。これは、 CLI または を使用してパイプライン CloudFormation を移行する場合に推奨される方法です。

**注記**  
この方法では、イベント通知が有効になっているバケットを使用するため、別途 CloudTrail 証跡を作成する必要はありません。コンソールを使用する場合は、イベントルールと CloudTrail 証跡が自動的に設定されます。これらの手順については、「[S3 ソースと CloudTrail 証跡を使用してポーリングパイプラインを移行する](#update-change-detection-S3)」を参照してください。
+ **CLI: **[S3 ソースと CloudTrail 証跡を使用してポーリングパイプラインを移行する (CLI)](#update-change-detection-cli-S3)
+ **CloudFormation: **[S3 ソースと CloudTrail 証跡 (CloudFormation テンプレート) を使用してポーリングパイプラインを移行する](#update-change-detection-cfn-s3)

### イベントに対応した S3 ソースを使用してポーリングパイプラインを移行する (CLI)
<a name="update-change-detection-cli-S3-event"></a>

ポーリング (定期的なチェック) を使用しているパイプラインを、EventBridge のイベントを使用するように編集するには、次の手順に従います。パイプラインを作成する場合は、「[パイプライン、ステージ、アクションを作成する](pipelines-create.md)」を参照してください。

Amazon S3 でイベント駆動型パイプラインを構築するには、パイプラインの `PollForSourceChanges` パラメータを編集してから、以下のリソースを作成します。
+ EventBridge イベントバス
+ EventBridge イベントによるパイプラインの開始を許可する IAM ロール



**Amazon S3 をイベントソース、CodePipeline をターゲットとする EventBridge ルールを作成し、アクセス許可ポリシーを適用するには**

1. EventBridge が CodePipeline を使用してルールを呼び出すためのアクセス許可を付与します。詳細については、 デベロッパーガイドの [[Amazon EventBridge のリソースベースのポリシーを使用する](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-resource-based.html)] を参照してください。

   1. 次のサンプルを使用して、EventBridge にサービスロールの引き受けを許可する信頼ポリシーを作成します。このスクリプトに `trustpolicyforEB.json` という名前を付けます。

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Principal": {
                      "Service": "events.amazonaws.com"
                  },
                  "Action": "sts:AssumeRole"
              }
          ]
      }
      ```

------

   1. 次のコマンドを使用して、`Role-for-MyRule` ロールを作成し、信頼ポリシーをアタッチします。

      **この変更を行う理由** ロールにこの信頼ポリシーを追加すると、EventBridge に対するアクセス許可が作成されます。

      ```
      aws iam create-role --role-name Role-for-MyRule --assume-role-policy-document file://trustpolicyforEB.json
      ```

   1. 次に示すように、`MyFirstPipeline` という名前のパイプラインに対してアクセス許可ポリシー JSON を作成します。アクセス権限ポリシーに `permissionspolicyforEB.json` と名前を付けます。

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "codepipeline:StartPipelineExecution"
                  ],
                  "Resource": [
                      "arn:aws:codepipeline:us-west-2:{{111122223333}}:MyFirstPipeline"
                  ]
              }
          ]
      }
      ```

------

   1. 次のコマンドを実行して、作成した `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
      ```

1. **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"
   ```

1. 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
   ```<a name="proc-cli-flag-s3"></a>

**パイプラインの PollForSourceChanges パラメータを編集するには**
**重要**  
このメソッドを使用してパイプラインを作成すると、`PollForSourceChanges` パラメータはデフォルトで true になります (ただし、明示的に false に設定した場合は除きます)。イベントベースの変更検出を追加する場合は、このパラメータを出力に追加する必要があります。ポーリングを無効にするには、このパラメータを false に設定します。そうしないと、1 つのソース変更に対してパイプラインが 2 回起動されます。詳細については、「[`PollForSourceChanges` パラメータの有効な設定](PollForSourceChanges-defaults.md)」を参照してください

1. **get-pipeline** コマンドを実行して、パイプライン構造を JSON ファイルにコピーします。例えば、`MyFirstPipeline` という名前のパイプラインに対して、以下のコマンドを実行します。

   ```
   aws codepipeline get-pipeline --name {{MyFirstPipeline}} >{{pipeline.json}}
   ```

   このコマンドは何も返しませんが、作成したファイルは、コマンドを実行したディレクトリにあります。

1. この例に示すように、プレーンテキストエディタで JSON ファイルを開き、`PollForSourceChanges` という名前のバケットの `amzn-s3-demo-source-bucket` パラメータを `false` に変更してソースステージを編集します。

   **この変更を行う理由** このパラメータを `false` に設定すると、定期的チェックがオフになるため、イベントベースの変更検出のみ使用することができます。

   ```
   "configuration": {
       "S3Bucket": "amzn-s3-demo-source-bucket",
       {{"PollForSourceChanges": "false",}}
       "S3ObjectKey": "index.zip"
   },
   ```

1. **get-pipeline** コマンドを使用して取得したパイプライン構造を使用している場合、JSON ファイルから `metadata` 行を削除する必要があります。それ以外の場合は、**update-pipeline** コマンドで使用することはできません。`"metadata": { }` 行と、`"created"`、`"pipelineARN"`、`"updated"` フィールドを削除します。

   例えば、構造から以下の行を削除します。

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

   ファイルを保存します。

1. 変更を適用するには、パイプライン JSON ファイルを指定して、**update-pipeline** コマンドを実行します。
**重要**  
ファイル名の前に必ず `file://` を含めてください。このコマンドでは必須です。

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

   このコマンドは、編集したパイプラインの構造全体を返します。
**注記**  
**update-pipeline** コマンドは、パイプラインを停止します。**update-pipeline** コマンドを実行したときにパイプラインによりリビジョンが実行されている場合、その実行は停止します。更新されたパイプラインによりそのリビジョンを実行するには、パイプラインを手動で開始する必要があります。パイプラインを手動で開始するには **start-pipeline-execution** コマンドを使用します。

### イベントに対して S3 ソースを有効にしたポーリングパイプラインを移行する (CloudFormation テンプレート)
<a name="update-change-detection-cfn-S3-event"></a>

この手順は、ソースバケットでイベントが有効になっているパイプライン用です。

以下の手順を使用して、Amazon S3 ソースを含むパイプラインを、ポーリングからイベントベースの変更検出に編集します。

Amazon S3 でイベント駆動型パイプラインを構築するには、パイプラインの `PollForSourceChanges` パラメータを編集してから、以下のリソースをテンプレートに追加します。
+ このイベントによるパイプラインの開始を許可する EventBridge ルールと IAM ロール。

 CloudFormation を使用してパイプラインを作成および管理する場合、テンプレートには次のようなコンテンツが含まれます。

**注記**  
`PollForSourceChanges` と呼ばれるソースステージの `Configuration` プロパティ。テンプレートにプロパティが含まれていない場合、`PollForSourceChanges` はデフォルトで `true` に設定されます。

------
#### [ 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` CloudFormation リソースを使用して、イベントがパイプラインを開始できるようにする IAM ロールを設定します。このエントリによって、2 つのポリシーを使用するロールが作成されます。
   + 最初のポリシーでは、ロールを引き受けることを許可します。
   + 2 つめのポリシーでは、パイプラインを開始するアクセス権限が付与されます。

   **この変更を行う理由** `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 ソースバケット内のオブジェクトの作成または削除をモニタリングするイベントを作成します。さらに、パイプラインのターゲットも含めます。オブジェクトが作成されると、このルールによりターゲットパイプラインで `StartPipelineExecution` が呼び出されます。

   **この変更を行う理由** `AWS::Events::Rule` リソースを追加すると CloudFormation 、 は イベントを作成できます。このリソースは 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"
           }
         ]
       }
     }
   },
   
   ...
   ```

------

1. 更新したテンプレートをローカルコンピュータに保存し、 CloudFormation コンソールを開きます。

1. スタックを選択し、[**既存スタックの変更セットの作成**] を選択します。

1. 更新されたテンプレートをアップロードし、 CloudFormationに示された変更を表示します。これらがスタックに加えられる変更です。新しいリソースがリストに表示されています。

1. **[実行]** を選択してください。<a name="proc-cfn-flag-s3"></a>

**パイプラインの PollForSourceChanges パラメータを編集するには**
**重要**  
このメソッドを使用してパイプラインを作成すると、`PollForSourceChanges` パラメータはデフォルトで true になります (ただし、明示的に false に設定した場合は除きます)。イベントベースの変更検出を追加する場合は、このパラメータを出力に追加する必要があります。ポーリングを無効にするには、このパラメータを false に設定します。そうしないと、1 つのソース変更に対してパイプラインが 2 回起動されます。詳細については、「[`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
    }
  ```

------

**Example**  
 CloudFormation を使用してこれらのリソースを作成すると、リポジトリ内のファイルが作成または更新されたときにパイプラインがトリガーされます。  
ここで手順は終わりではありません。パイプラインは作成されますが、Amazon S3 パイプライン用の 2 番目の CloudFormation テンプレートを作成する必要があります。2 番目のテンプレートを作成しない場合、パイプラインに変更検出機能はありません。

```
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
```  
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "appconfig:StartDeployment",
                "appconfig:StopDeployment",
                "appconfig:GetDeployment"
            ],
            "Resource": [
                "arn:aws:appconfig:*:{{111122223333}}:application/[[Application]]",
                "arn:aws:appconfig:*:{{111122223333}}:application/[[Application]]/*",
                "arn:aws:appconfig:*:{{111122223333}}:deploymentstrategy/*"
            ],
            "Effect": "Allow"
        }
    ]
}
```

## S3 ソースと CloudTrail 証跡を使用してポーリングパイプラインを移行する
<a name="update-change-detection-S3"></a>

Amazon S3 ソースを含むパイプラインでは、変更検出が EventBridge を通じて自動化されるように、パイプラインを修正します。以下のいずれかの方法で移行を実装します。
+ **コンソール: **[ポーリングパイプラインを移行する (CodeCommit または Amazon S3 ソース) (コンソール)](#update-change-detection-console-codecommit-S3)
+ **CLI: **[S3 ソースと CloudTrail 証跡を使用してポーリングパイプラインを移行する (CLI)](#update-change-detection-cli-S3)
+ **CloudFormation: **[S3 ソースと CloudTrail 証跡 (CloudFormation テンプレート) を使用してポーリングパイプラインを移行する](#update-change-detection-cfn-s3)

### S3 ソースと CloudTrail 証跡を使用してポーリングパイプラインを移行する (CLI)
<a name="update-change-detection-cli-S3"></a>

ポーリング (定期的なチェック) を使用しているパイプラインを、EventBridge のイベントを使用するように編集するには、次の手順に従います。パイプラインを作成する場合は、「[パイプライン、ステージ、アクションを作成する](pipelines-create.md)」を参照してください。

Amazon S3 でイベント駆動型パイプラインを構築するには、パイプラインの `PollForSourceChanges` パラメータを編集してから、以下のリソースを作成します。
+ AWS CloudTrail Amazon S3 がイベントのログ記録に使用できる証跡、バケット、バケットポリシー。
+ EventBridge イベント
+ EventBridge イベントによるパイプラインの開始を許可する IAM ロール<a name="proc-cli-event-s3-createtrail"></a>

**AWS CloudTrail 証跡を作成し、ログ記録を有効にするには**

を使用して証跡 AWS CLI を作成するには、 **create-trail** コマンドを呼び出し、以下を指定します。
+ 証跡名。
+  AWS CloudTrailにバケットポリシーをすでに適用しているバケットです。

詳細については、[AWS 「コマンドラインインターフェイスを使用した証跡の作成](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-create-and-update-a-trail-by-using-the-aws-cli.html)」を参照してください。

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
   ```

1. **start-logging** コマンドを呼び出し、`--name` パラメータを含めます。

   **この変更を行う理由** これにより、ソースバケットの CloudTrail ロギングが開始され、EventBridge にイベントが送信されます。

   例:

   次のコマンドでは、`--name` を使用して、`my-trail` という名前の証跡のログ記録を開始します。

   ```
   aws cloudtrail start-logging --name my-trail
   ```

1. **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"] }] }]'
   ```<a name="proc-cli-event-s3-createrule"></a>

**Amazon S3 をイベントソース、CodePipeline をターゲットとする EventBridge ルールを作成し、アクセス許可ポリシーを適用するには**

1. EventBridge が CodePipeline を使用してルールを呼び出すためのアクセス許可を付与します。詳細については、 デベロッパーガイドの [[Amazon EventBridge のリソースベースのポリシーを使用する](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-resource-based.html)] を参照してください。

   1. 次のサンプルを使用して、EventBridge にサービスロールの引き受けを許可する信頼ポリシーを作成します。このスクリプトに `trustpolicyforEB.json` という名前を付けます。

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Principal": {
                      "Service": "events.amazonaws.com"
                  },
                  "Action": "sts:AssumeRole"
              }
          ]
      }
      ```

------

   1. 次のコマンドを使用して、`Role-for-MyRule` ロールを作成し、信頼ポリシーをアタッチします。

      **この変更を行う理由** ロールにこの信頼ポリシーを追加すると、EventBridge に対するアクセス許可が作成されます。

      ```
      aws iam create-role --role-name Role-for-MyRule --assume-role-policy-document file://trustpolicyforEB.json
      ```

   1. 次に示すように、`MyFirstPipeline` という名前のパイプラインに対してアクセス許可ポリシー JSON を作成します。アクセス権限ポリシーに `permissionspolicyforEB.json` と名前を付けます。

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

****  

      ```
      {
          "Version":"2012-10-17",		 	 	 
          "Statement": [
              {
                  "Effect": "Allow",
                  "Action": [
                      "codepipeline:StartPipelineExecution"
                  ],
                  "Resource": [
                      "arn:aws:codepipeline:us-west-2:{{111122223333}}:MyFirstPipeline"
                  ]
              }
          ]
      }
      ```

------

   1. 次のコマンドを実行して、作成した `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
      ```

1. **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"
   ```

1. 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
   ```

1. (オプション) 特定のイメージ ID のソースオーバーライドを使用して入力トランスフォーマーを設定するには、CLI コマンドで次の JSON を使用します。次の例では、以下のオーバーライドを設定します。
   + `actionName` は (この例では `Source`)、ソースイベントから派生したものではなく、パイプラインの作成時に定義された動的な値です。
   + `revisionType` は (この例では `S3_OBJECT_VERSION_ID`)、ソースイベントから派生したものではなく、パイプラインの作成時に定義された動的な値です。
   + `revisionValue` は (この例では <{{revisionValue}}>)、ソースイベント変数から派生しています。

   ```
   {
       "Rule": "my-rule",
       "Targets": [
           {
               "Id": "MyTargetId",
               "Arn": "ARN",
               "InputTransformer": {
                   "InputPathsMap": {
                       "revisionValue": "$.detail.object.version-id"
                   },
                   "InputTemplate": {
                       "sourceRevisions": {
                           "actionName": "Source",
                           "revisionType": "S3_OBJECT_VERSION_ID",
                           "revisionValue": "<{{revisionValue}}>"
                       }
                   }
               }
           }
       ]
   }
   ```<a name="proc-cli-flag-s3"></a>

**パイプラインの PollForSourceChanges パラメータを編集するには**
**重要**  
このメソッドを使用してパイプラインを作成すると、`PollForSourceChanges` パラメータはデフォルトで true になります (ただし、明示的に false に設定した場合は除きます)。イベントベースの変更検出を追加する場合は、このパラメータを出力に追加する必要があります。ポーリングを無効にするには、このパラメータを false に設定します。そうしないと、1 つのソース変更に対してパイプラインが 2 回起動されます。詳細については、「[`PollForSourceChanges` パラメータの有効な設定](PollForSourceChanges-defaults.md)」を参照してください

1. **get-pipeline** コマンドを実行して、パイプライン構造を JSON ファイルにコピーします。例えば、`MyFirstPipeline` という名前のパイプラインに対して、以下のコマンドを実行します。

   ```
   aws codepipeline get-pipeline --name {{MyFirstPipeline}} >{{pipeline.json}}
   ```

   このコマンドは何も返しませんが、作成したファイルは、コマンドを実行したディレクトリにあります。

1. この例に示すように、プレーンテキストエディタで JSON ファイルを開き、`PollForSourceChanges` という名前のバケットの `amzn-s3-demo-source-bucket` パラメータを `false` に変更してソースステージを編集します。

   **この変更を行う理由** このパラメータを `false` に設定すると、定期的チェックがオフになるため、イベントベースの変更検出のみ使用することができます。

   ```
   "configuration": {
       "S3Bucket": "amzn-s3-demo-source-bucket",
       {{"PollForSourceChanges": "false",}}
       "S3ObjectKey": "index.zip"
   },
   ```

1. **get-pipeline** コマンドを使用して取得したパイプライン構造を使用している場合、JSON ファイルから `metadata` 行を削除する必要があります。それ以外の場合は、**update-pipeline** コマンドで使用することはできません。`"metadata": { }` 行と、`"created"`、`"pipelineARN"`、`"updated"` フィールドを削除します。

   例えば、構造から以下の行を削除します。

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

   ファイルを保存します。

1. 変更を適用するには、パイプライン JSON ファイルを指定して、**update-pipeline** コマンドを実行します。
**重要**  
ファイル名の前に必ず `file://` を含めてください。このコマンドでは必須です。

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

   このコマンドは、編集したパイプラインの構造全体を返します。
**注記**  
**update-pipeline** コマンドは、パイプラインを停止します。**update-pipeline** コマンドを実行したときにパイプラインによりリビジョンが実行されている場合、その実行は停止します。更新されたパイプラインによりそのリビジョンを実行するには、パイプラインを手動で開始する必要があります。パイプラインを手動で開始するには **start-pipeline-execution** コマンドを使用します。

### S3 ソースと CloudTrail 証跡 (CloudFormation テンプレート) を使用してポーリングパイプラインを移行する
<a name="update-change-detection-cfn-s3"></a>

以下の手順を使用して、Amazon S3 ソースを含むパイプラインを、ポーリングからイベントベースの変更検出に編集します。

Amazon S3 でイベント駆動型パイプラインを構築するには、パイプラインの `PollForSourceChanges` パラメータを編集してから、以下のリソースをテンプレートに追加します。
+ EventBridge では、すべての Amazon S3 イベントをログに記録する必要があります。発生するイベントのロク記録に Amazon S3 が使用できる AWS CloudTrail 証跡、バケット、バケットポリシーを作成する必要があります。詳細については、「 [証跡のデータイベント](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html) 」と「 [管理イベントのログ記録](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-management-events-with-cloudtrail.html) 」を参照してください。
+ このイベントによるパイプラインの開始を許可する EventBridge ルールと IAM ロール。

 CloudFormation を使用してパイプラインを作成および管理する場合、テンプレートには次のようなコンテンツが含まれます。

**注記**  
`PollForSourceChanges` と呼ばれるソースステージの `Configuration` プロパティ。テンプレートにプロパティが含まれていない場合、`PollForSourceChanges` はデフォルトで `true` に設定されます。

------
#### [ 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
                            }
                        ]
                    },


...
```

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

**Amazon S3 をイベントソース、CodePipeline をターゲットとする EventBridge ルールを作成し、アクセス許可ポリシーを適用するには**

1. テンプレートの で`Resources`、 `AWS::IAM::Role` CloudFormation リソースを使用して、イベントがパイプラインを開始できるようにする IAM ロールを設定します。このエントリによって、2 つのポリシーを使用するロールが作成されます。
   + 最初のポリシーでは、ロールを引き受けることを許可します。
   + 2 つめのポリシーでは、パイプラインを開始するアクセス権限が付与されます。

   **この変更を行う理由** `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 パラメータを編集するには**
**重要**  
このメソッドを使用してパイプラインを作成すると、`PollForSourceChanges` パラメータはデフォルトで true になります (ただし、明示的に false に設定した場合は除きます)。イベントベースの変更検出を追加する場合は、このパラメータを出力に追加する必要があります。ポーリングを無効にするには、このパラメータを false に設定します。そうしないと、1 つのソース変更に対してパイプラインが 2 回起動されます。詳細については、「[`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 リソース用に 2 番目のテンプレートを作成するには**
+ 別のテンプレートの で`Resources`、、`AWS::S3::BucketPolicy`、および `AWS::S3::Bucket``AWS::CloudTrail::Trail` CloudFormation リソースを使用して、CloudTrail のシンプルなバケット定義と証跡を提供します。

  **この変更を行う理由** CloudTrail 証跡は、アカウントあたり 5 証跡を現在の制限として、個別に作成して管理する必要があります。(「 [の制限 AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/WhatIsCloudTrail-Limits.html)」を参照してください。) ただし、1 つの証跡に複数の Amazon S3 バケットを含めることができるため、いったん証跡を作成してから、必要に応じて他のパイプライン用に Amazon S3 バケットを追加できます。2 番目のサンプルテンプレートファイルに以下のコードを貼り付けます。

------
#### [ 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
        }
      }
    }
  }
  
  ...
  ```

------

**Example**  
 CloudFormation を使用してこれらのリソースを作成すると、リポジトリ内のファイルが作成または更新されたときにパイプラインがトリガーされます。  
ここで手順は終わりではありません。パイプラインは作成されますが、Amazon S3 パイプライン用の 2 番目の CloudFormation テンプレートを作成する必要があります。2 番目のテンプレートを作成しない場合、パイプラインに変更検出機能はありません。

```
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
```

```
    "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 (OAuth アプリ経由) ソースアクションのポーリングパイプラインを接続に移行する
<a name="update-change-detection-github-connection"></a>

GitHub (OAuth アプリ経由) ソースアクションを、外部リポジトリの接続を使用するように移行できます。これは、GitHub (OAuth アプリ経由) ソースアクションを含むパイプラインで推奨される変更検出方法です。

GitHub (OAuth アプリ経由) のソースアクションを含むパイプラインでは、GitHub (GitHub アプリ経由) のアクションを使用するようにパイプラインを修正し、 AWS CodeConnectionsを通じて変更検出を自動化することをお勧めします。接続の使用の詳細については、「[GitHub コネクション](connections-github.md)」を参照してください。



### GitHub (コンソール) への接続を作成する
<a name="update-change-detection-github-connection-console"></a>

コンソールを使用して、GitHub への接続を作成できます。

#### ステップ 1: GitHub (OAuth アプリ経由) アクションを置き換える
<a name="update-change-detection-github-connection-console-edit"></a>

パイプライン編集ページを使用して、GitHub (OAuth アプリ経由) アクションを GitHub (GitHub アプリ経由) アクションに置き換えます。

**GitHub (OAuth アプリ経由) アクションを置き換えるには**

1. CodePipeline コンソールにサインインします。

1. パイプラインを選択し、[**編集**] を選択します。ソースステージで、[**ステージを編集**] を選択します。アクションを更新することを推奨するメッセージが表示されます。

1. **[アクションプロバイダー]** で、**[GitHub (GitHub アプリ経由)]** を選択します。

1. 次のいずれかを行います。
   + [**接続**] でプロバイダへの接続をまだ作成していない場合は、[**GitHub への接続**] を選択します。ステップ 2: GitHub への接続を作成するに進みます。
   + [**接続**] でプロバイダへの接続を既に作成している場合は、その接続を選択します。ステップ 3： 接続のソースアクションを保存するに進みます。

#### ステップ２：GitHub への接続を作成する
<a name="update-change-detection-github-connection-console-install"></a>

接続の作成を選択した後、[**Connect to GitHub**] ページが表示されます。

**GitHub への接続を作成するには**

1. [**GitHub connection settings**] で、[**Connection name**] に接続名が表示されます。

   **[GitHub Apps]** で、アプリケーションのインストールを選択するか、**[Install a new app]** (新しいアプリケーションをインストールする) を選択してアプリケーションを作成します。
**注記**  
特定のプロバイダーへのすべての接続に対してアプリを 1 つインストールします。GitHub アプリをすでにをインストールしている場合は、これを選択してこのステップをスキップしてください。

1. GitHub の認可ページが表示されたら、認証情報を使用してログインし、続行を選択します。

1. アプリのインストールページで、 AWS CodeStar アプリが GitHub アカウントに接続しようとしていることを示すメッセージが表示されます。
**注記**  
アプリは、GitHub アカウントごとに 1 回だけインストールします。アプリをインストール済みである場合は、**Configure** (設定) をクリックしてアプリのインストールの変更ページに進むか、戻るボタンでコンソールに戻ることができます。

1. [** AWS CodeStarのインストール**] ページで、[**インストール**] を選択します。

1. [**Connect to GitHub**] ページで、新規インストールの接続 ID が GitHub Apps に表示されます。**接続** を選択します。

#### ステップ 3: GitHub のソースアクションを保存する
<a name="update-change-detection-github-connection-console-save"></a>

[**アクションを編集**] というページで更新を実行し、新しいソースアクションを保存します。

**GitHub のソースアクションを保存するには**

1. [**リポジトリ**] で、サードパーティーのリポジトリの名前を入力します。[**ブランチ**] で、パイプラインでソースの変更を検出するブランチを入力します。
**注記**  
[**Repository**] で、例に示すように `owner-name/repository-name` を入力します。  

   ```
   my-account/my-repository
   ```

1. [**Output artifact format (出力アーティファクトのフォーマット)**] で、アーティファクトのフォーマットを選択します。
   + デフォルトのメソッドを使用して GitHub アクションからの出力アーティファクトを保存するには、**CodePipeline default** を選択します。アクションは、Bitbucket リポジトリからファイルにアクセスし、パイプラインアーティファクトストアの ZIP ファイルにアーティファクトを保存します。
   + リポジトリへの URL 参照を含む JSON ファイルを保存して、ダウンストリームのアクションで Git コマンドを直接実行できるようにするには、[**Full clone (フルクローン)**] を選択します。このオプションは、CodeBuild ダウンストリームアクションでのみ使用できます。

      このオプションを選択した場合は、[Bitbucket、GitHub、GitHub Enterprise Server、または GitLab.com に接続するための CodeBuild GitClone アクセス許可を追加します。](troubleshooting.md#codebuild-role-connections) で示されるように CodeBuild プロジェクトサービスロールの権限を更新する必要があります。**フルクローン** オプションの使い方を紹介したチュートリアルは、[チュートリアル: CodeCommit パイプラインソースで完全なクローンを使用する](tutorials-github-gitclone.md) をご覧ください。

1. **出力アーティファクト**　の場合、`SourceArtifact` のようにこのアクションの出力アーティファクトの名前を保持できます。[**Done**] を選択して、[**アクションを編集**] ページを閉じます。

1. [**Done**] を選択して、ステージの編集ページを閉じます。[**Save**] を選択して、パイプラインの編集ページを閉じます。

### GitHub (CLI) への接続を作成する
<a name="update-change-detection-github-connection-cli"></a>

 AWS Command Line Interface (AWS CLI) を使用して GitHub への接続を作成できます。

これを行うには、**create-connection** コマンドを使用します。

**重要**  
 AWS CLI または を通じて作成された接続 AWS CloudFormation は、デフォルトで `PENDING`ステータスです。CLI または との接続を作成したら CloudFormation、コンソールを使用して接続を編集し、ステータスを にします`AVAILABLE`。

**GitHub への接続を作成するには**

1. ターミナル (Linux/macOS/Unix) またはコマンドプロンプト (Windows) を開きます。を使用して **create-connection** コマンド AWS CLI を実行し、接続`--connection-name`の `--provider-type`と を指定します。この例では、サードパーティープロバイダー名は `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"
   }
   ```

1. コンソールを使用して接続を完了します。

## GitHub (OAuth アプリ経由) ソースアクションのポーリングパイプラインを Webhook に移行する
<a name="update-change-detection-github-webhooks"></a>

パイプラインを移行して、Webhook を使用して GitHub ソースリポジトリ内の変更を検出するようにできます。この Webhook への移行は GitHub (OAuth アプリ経由) アクションのみが対象です。
+ **コンソール: **[ポーリングパイプラインを Webhook に移行する (GitHub (OAuth アプリ経由) ソースアクション) (コンソール)](#update-change-detection-console-github)
+ **CLI: **[ポーリングパイプラインを Webhook に移行する (GitHub (OAuth アプリ経由) ソースアクション) (CLI)](#update-change-detection-cli-github)
+ **CloudFormation: ** [プッシュイベントのパイプラインを更新する (GitHub (OAuth アプリ経由) ソースアクション) (CloudFormation テンプレート)](#update-change-detection-cfn-github)

**重要**  
CodePipeline ウェブフックを作成するときは、独自の認証情報を使用したり、複数のウェブフック間で同じシークレットトークンを再利用したりしないでください。セキュリティを最適化するには、作成するウェブフックごとに一意のシークレットトークンを生成します。シークレットトークンは、ユーザーが指定する任意の文字列で、ウェブフックペイロードの整合性と信頼性を保護するために、CodePipeline に送信するウェブフックペイロードを GitHub で計算して署名するために使用します。独自の認証情報を使用したり、複数のウェブフック間で同じトークンを再利用したりすると、セキュリティの脆弱性につながる可能性があります。

### ポーリングパイプラインを Webhook に移行する (GitHub (OAuth アプリ経由) ソースアクション) (コンソール)
<a name="update-change-detection-console-github"></a>

GitHub (OAuth アプリ経由) のソースアクションでは、CodePipeline コンソールを使用してパイプラインを更新し、ウェブフックを使用して GitHub ソースリポジトリの変更を検出できます。

ポーリング (定期的なチェック) を使用しているパイプラインを EventBridge のイベントを使用するように編集するには、次の手順に従います。パイプラインを作成する場合は、「[パイプライン、ステージ、アクションを作成する](pipelines-create.md)」を参照してください。

コンソールを使用すると、パイプラインの `PollForSourceChanges` パラメータが変更されます。GitHub ウェブフックが作成され、登録されます。

**パイプラインソースステージを編集するには**

1. にサインイン AWS マネジメントコンソール し、[http://console.aws.amazon.com/codesuite/codepipeline/home](https://console.aws.amazon.com/codesuite/codepipeline/home) で CodePipeline コンソールを開きます。

    AWS アカウントに関連付けられているすべてのパイプラインの名前が表示されます。

1. **[名前]** で、編集するパイプラインの名前を選択します。これにより、パイプラインの詳細ビューが開いて、パイプラインの各ステージの各アクションの状態などがわかります。

1. パイプライン詳細ページで、[**編集**] を選択します。

1. [**Edit (編集)**] ステージで、ソースアクションの編集アイコンを選択します。

1. [**Change detection options (変更検出オプション)**] を展開し、[**Use Amazon CloudWatch Events to automatically start my pipeline when a change occurs (recommended)**] を選択します。

   CodePipeline が GitHub でソースの変更を検出するためのウェブフックを作成することを知らせるメッセージが表示されます。 AWS CodePipeline がウェブフックを作成します。以下のオプションでオプトアウトできます。**[更新]** を選択します。CodePipeline では、ウェブフックのほかに以下が作成されます。
   + シークレット。ランダムに生成され、GitHub への接続を承認するために使用されます。
   + ウェブフック URL。リージョンのパブリックエンドポイントを使用して生成されます。

   CodePipeline は、ウェブフック を GitHub に登録します。これにより、レポジトリのイベントを受信するための URL がサブスクライブされます。

1. パイプラインの編集が終わったら、[**パイプラインの変更を保存**] を選択して概要ページに戻ります。

   パイプラインに対して作成されるウェブフックの名前を示すメッセージが表示されます。**[保存して続行]** を選択します。

1. アクションをテストするには、 を使用して変更をリリース AWS CLI し、パイプラインのソースステージで指定されたソースに変更をコミットします。

### ポーリングパイプラインを Webhook に移行する (GitHub (OAuth アプリ経由) ソースアクション) (CLI)
<a name="update-change-detection-cli-github"></a>

ウェブフックを使用するために定期的なチェックを使用しているパイプラインを編集するには、次の手順を使用します。パイプラインを作成する場合は、「[パイプライン、ステージ、アクションを作成する](pipelines-create.md)」を参照してください。

イベント駆動型パイプラインを構築するには、パイプラインの `PollForSourceChanges` パラメータを編集してから、以下のリソースを手動で作成します。
+ GitHub のウェブフックと承認パラメータ<a name="proc-cli-gh-webhook"></a>

**ウェブフックを作成して登録するには**
**注記**  
CLI または を使用してパイプライン CloudFormation を作成し、ウェブフックを追加する場合は、定期的なチェックを無効にする必要があります。定期的なチェックを無効にするには、以下の最終的な手順に詳述するとおり、`PollForSourceChanges` パラメータを明示的に追加して false に設定する必要があります。それ以外の場合、CLI または CloudFormation パイプラインのデフォルトは`PollForSourceChanges`デフォルトで true になり、パイプライン構造の出力には表示されません。PollForSourceChanges のデフォルトの詳細については、「[`PollForSourceChanges` パラメータの有効な設定](PollForSourceChanges-defaults.md)」を参照してください。

1. テキストエディタで、作成するウェブフックの JSON ファイルを作成して保存します。「`my-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}}"
   	 }
       }
   }
   ```

1. **put-webhook** コマンドを呼び出し、`--cli-input` および `--region` パラメータを含めます。

   次のサンプルコマンドは、`webhook_json` JSON ファイルで ウェブフックを作成します。

   ```
   aws codepipeline put-webhook --cli-input-json file://webhook_json.json --region "eu-central-1"
   ```

1. この例に示す出力では、`my-webhook` という名前のウェブフックに対して URL と ARN が返されます。

   ```
   {
       "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"
       }]
   }
   ```

   この例では、ウェブフックに`Project`タグキーと`ProjectA`値を含めることで、ウェブフックにタグ付けを追加します。CodePipeline の リソースのタグ付けの詳細については、[リソースのタグ付け](tag-resources.md) を参照してください。

1. **register-webhook-with-third-party** コマンドを呼び出し、`--webhook-name` パラメータを含めます。

   次のサンプルコマンドは、「`my-webhook`」という名前のウェブフックを登録します。

   ```
   aws codepipeline register-webhook-with-third-party --webhook-name my-webhook
   ```<a name="proc-cli-flag-github"></a>

**パイプラインの PollForSourceChanges パラメータを編集するには**
**重要**  
このメソッドを使用してパイプラインを作成すると、`PollForSourceChanges` パラメータはデフォルトで true になります (ただし、明示的に false に設定した場合は除きます)。イベントベースの変更検出を追加する場合は、このパラメータを出力に追加する必要があります。ポーリングを無効にするには、このパラメータを false に設定します。そうしないと、1 つのソース変更に対してパイプラインが 2 回起動されます。詳細については、「[`PollForSourceChanges` パラメータの有効な設定](PollForSourceChanges-defaults.md)」を参照してください

1. **get-pipeline** コマンドを実行して、パイプライン構造を JSON ファイルにコピーします。例えば、`MyFirstPipeline` という名前のパイプラインの場合は、以下のコマンドを入力します。

   ```
   aws codepipeline get-pipeline --name {{MyFirstPipeline}} >{{pipeline.json}}
   ```

   このコマンドは何も返しませんが、作成したファイルは、コマンドを実行したディレクトリにあります。

1. 任意のプレーンテキストエディタで JSON ファイルを開き、以下に示しているように、`PollForSourceChanges` パラメータを変更または追加してソースステージを編集します。この例では、`UserGitHubRepo` という名前のリポジトリで、パラメータを `false` に設定します。

   **この変更を行う理由** このパラメータを変更すると、定期的なチェックがオフになるため、イベントベースの変更検出のみ使用することができます。

   ```
   "configuration": {
       "Owner": "{{name}}",
       "Repo": "UserGitHubRepo",
       {{"PollForSourceChanges": "false",}}
       "Branch": "main",
       "OAuthToken": "****"
   },
   ```

1. **get-pipeline** コマンドを使用して取得されたパイプライン構造を操作している場合、ファイルから `metadata` 行を削除して JSON ファイルの構造を編集する必要があります。それ以外の場合は、**update-pipeline** コマンドで使用することはできません。JSON ファイルのパイプライン構造から `"metadata"` セクションを削除します (`{ }` 行と、`"created"`、`"pipelineARN"`、および `"updated"` フィールド)。

   例えば、構造から以下の行を削除します。

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

   ファイルを保存します。

1. 変更を適用するには、以下のように、パイプライン JSON ファイルを指定して、 **update-pipeline** コマンドを実行します。
**重要**  
ファイル名の前に必ず `file://` を含めてください。このコマンドでは必須です。

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

   このコマンドは、編集したパイプラインの構造全体を返します。
**注記**  
**update-pipeline** コマンドは、パイプラインを停止します。**update-pipeline** コマンドを実行したときにパイプラインによりリビジョンが実行されている場合、その実行は停止します。更新されたパイプラインによりそのリビジョンを実行するには、パイプラインを手動で開始する必要があります。パイプラインを手動で開始するには **start-pipeline-execution** コマンドを使用します。

### プッシュイベントのパイプラインを更新する (GitHub (OAuth アプリ経由) ソースアクション) (CloudFormation テンプレート)
<a name="update-change-detection-cfn-github"></a>

以下の手順に従って、GitHub ソースを含むパイプラインを、定期的なチェック (ポーリング) から、ウェブフックを使用したイベントベースの変更検出に更新します。

を使用してイベント駆動型パイプラインを構築するには AWS CodeCommit、パイプラインの `PollForSourceChanges`パラメータを編集し、GitHub ウェブフックリソースをテンプレートに追加します。

 CloudFormation を使用してパイプラインを作成および管理する場合、テンプレートには次のようなコンテンツがあります。

**注記**  
ソースステージ内の `PollForSourceChanges` 設定プロパティを書き留めます。テンプレートにプロパティが含まれていない場合、`PollForSourceChanges` はデフォルトで `true` に設定されます。

------
#### [ 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
                            }
                        ]
                    },


...
```

------<a name="proc-cfn-webhook-github"></a>

**テンプレートにパラメータを追加してウェブフックを作成するには**

を使用して認証情報 AWS Secrets Manager を保存することを強くお勧めします。Secrets Manager を使用する場合は、Secrets Manager でシークレットパラメータをすでに設定して保存しておく必要があります。この例では、ウェブフックの GitHub 認証情報に Secrets Manager への動的な参照を使用します。詳細については、「[動的な参照を使用してテンプレート値を指定する](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-secretsmanager)」を参照してください。
**重要**  
シークレットパラメータを渡すときは、値をテンプレートに直接入力しないでください。値はプレーンテキストとしてレンダリングされるため、読み取り可能です。セキュリティ上の理由から、 CloudFormation テンプレートにプレーンテキストを使用して認証情報を保存しないでください。

CLI または を使用してパイプライン CloudFormation を作成し、ウェブフックを追加する場合は、定期的なチェックを無効にする必要があります。
**注記**  
定期的なチェックを無効にするには、以下の最終的な手順に詳述するとおり、`PollForSourceChanges` パラメータを明示的に追加して false に設定する必要があります。それ以外の場合、CLI または CloudFormation パイプラインのデフォルトは`PollForSourceChanges`デフォルトで true になり、パイプライン構造の出力には表示されません。PollForSourceChanges のデフォルトの詳細については、「[`PollForSourceChanges` パラメータの有効な設定](PollForSourceChanges-defaults.md)」を参照してください。

1. テンプレートの `Resources` に、パラメータを追加します。

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

   ```
   Parameters:
           GitHubOwner:
             Type: String
   
   ...
   ```

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

   ```
   {
   	"Parameters": {
   		"BranchName": {
   			"Description": "GitHub branch name",
   			"Type": "String",
   			"Default": "main"
   		},
   		"GitHubOwner": {
   			"Type": "String"
   		},
   
   ...
   ```

------

1. `AWS::CodePipeline::Webhook` CloudFormation リソースを使用してウェブフックを追加します。
**注記**  
指定した `TargetAction` は、パイプラインで定義したソースアクションの `Name` プロパティと一致する必要があります。

   `RegisterWithThirdParty` が `true` に設定されている場合は、`OAuthToken` に関連付けられたユーザーが GitHub で必要なスコープを設定できることを確認してください。トークンとウェブフックには、以下の GitHub スコープが必要となります。
   + `repo` - パブリックおよびプライベートリポジトリからパイプラインにアーティファクトを読み込んでプルする完全制御に使用されます。
   + `admin:repo_hook` - リポジトリフックの完全制御に使用されます。

   それ以外の場合、GitHub から 404 が返されます。返される 404 の詳細については、「[https://help.github.com/articles/about-webhooks](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
       }
   },
   
   ...
   ```

------

1. 更新されたテンプレートをローカルコンピュータに保存し、 CloudFormation コンソールを開きます。

1. スタックを選択し、[**既存スタックの変更セットの作成**] を選択します。

1. テンプレートをアップロードし、 CloudFormationに示された変更を表示します。これらがスタックに加えられる変更です。新しいリソースがリストに表示されています。

1. **[実行]** を選択してください。<a name="proc-cfn-flag-github"></a>

**パイプラインの PollForSourceChanges パラメータを編集するには**
**重要**  
このメソッドを使用してパイプラインを作成すると、`PollForSourceChanges` パラメータはデフォルトで true になります (ただし、明示的に false に設定した場合は除きます)。イベントベースの変更検出を追加する場合は、このパラメータを出力に追加する必要があります。ポーリングを無効にするには、このパラメータを false に設定します。そうしないと、1 つのソース変更に対してパイプラインが 2 回起動されます。詳細については、「[`PollForSourceChanges` パラメータの有効な設定](PollForSourceChanges-defaults.md)」を参照してください
+ テンプレートで、`PollForSourceChanges` を `false` に変更します。パイプライン定義に `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
      }]
  ```

------

**Example**  
これらのリソースを で作成すると CloudFormation、定義されたウェブフックが指定された GitHub リポジトリに作成されます。パイプラインはコミット時にトリガーされます。  

```
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

...
```

```
{
    "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

...
```