

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 遷移輪詢管道以使用事件型變更偵測
<a name="update-change-detection"></a>

AWS CodePipeline 支援完整、end-to-end持續交付，其中包括在程式碼變更時啟動管道。有兩種支援的方法來在程式碼變更時啟動管道：事件型變更偵測和輪詢。我們建議對管道使用事件型變更偵測。

使用此處包含的程序，將輪詢管道遷移 （更新） 至管道的事件型變更偵測方法。

管道的建議事件型變更偵測方法取決於管道來源，例如 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>連線 （建議）</td><td>請參閱 [將 GitHub （透過 OAuth 應用程式） 來源動作的輪詢管道遷移至連線](#update-change-detection-github-connection)。</td></tr>
  <tr><td>GitHub （透過 OAuth 應用程式）</td><td>Webhooks</td><td>請參閱 [將 GitHub （透過 OAuth 應用程式） 來源動作的輪詢管道遷移至 Webhook](#update-change-detection-github-webhooks)。</td></tr>
</tbody>
</table>


**重要**  
對於適用的管道動作組態更新，例如具有 GitHub (viaOAuth 應用程式） 動作的管道，您必須在來源動作的組態中明確將 `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 指令碼，請執行下列命令來建立新的 python 指令碼，名為 **PollingPipelinesExtractor.py**。

     ```
     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 來源動作組態參數[Amazon S3 來源動作參考](action-reference-S3.md)。

   請注意，此指令碼也會產生 .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 管理主控台 並開啟 CodePipeline 主控台，網址為 https：//[http://console.aws.amazon.com/codesuite/codepipeline/home](https://console.aws.amazon.com/codesuite/codepipeline/home)。

   與 AWS 您的帳戶相關聯的所有管道名稱都會顯示。

1. 在 **Name (名稱)** 中，選擇您想編輯的管道名稱。這會開啟管道的詳細檢視，包含管道中各階段的每項動作之每項狀態。

1. 在管道詳細資訊頁面上，選擇 **Edit (編輯)**。

1. 在 **Edit (編輯)** 階段中，選擇來源動作上的編輯圖示。

1. 展開 **Change Detection Options (變更偵測選項)**，然後選擇 **Use CloudWatch Events to automatically start my pipeline when a change occurs (recommended) (使用 CloudWatch 事件以在發生變更時自動啟動我的管道 (建議))**。

   隨即出現一則訊息，顯示要為此管道建立的 EventBridge 規則。選擇**更新**。

   如果您要更新具有 Amazon S3 來源的管道，您會看到下列訊息。選擇**更新**。

1. 當您完成管道編輯後，請選擇 **Save pipeline changes (儲存管道變更)**​ 以返回摘要頁面。

   訊息會顯示要為您的管道建立的 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 參數**
**重要**  
當您使用這個方法建立管道時，如果沒有明確設為 false，則 `PollForSourceChanges` 參數會預設為 true。當新增基於事件的變更偵測時，您必須將該參數新增到輸出，並將其設為 false 以停用輪詢。否則，您的管道會針對單一來源變更啟動兩次。如需詳細資訊，請參閱[`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. 若要套用您的變更，請執行 **update-pipeline** 命令、指定管道 JSON 檔案：
**重要**  
請確認在檔案名稱之前包含 `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. 使用執行以下命令，將 `CodePipeline-Permissions-Policy-for-EB` 許可政策連接到 `Role-for-MyRule` 角色。

      **為什麼我會做出此變更？** 將此政策新增至角色會建立 EventBridge 的許可。

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

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 角色。此項目會建立一個使用兩個政策的角色：
   + 第一個政策允許要承擔的角色。
   + 第二個政策提供啟動管道的許可。

   **為什麼我會做出此變更？** 新增 `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}}> 衍生自來源事件變數。
   + `Value` 指定 `BranchName`和 的輸出變數。

   ```
   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. 選擇您的堆疊，然後選擇 **Create Change Set for Current Stack (建立目前堆疊的變更集)**。

1. 上傳範本，然後檢視 CloudFormation中所列的變更。這些是會針對堆疊進行的變更。您應該會在清單中看到新資源。

1. 選擇 **Execute (執行)**。<a name="proc-cfn-flag-codecommit"></a>

**編輯管道的 PollForSourceChanges 參數**
**重要**  
在許多情況下，當您建立管道時，`PollForSourceChanges` 參數會預設為 true。當新增基於事件的變更偵測時，您必須將該參數新增到輸出，並將其設為 false 以停用輪詢。否則，您的管道會針對單一來源變更啟動兩次。如需詳細資訊，請參閱[`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. 使用執行以下命令，將新的 `CodePipeline-Permissions-Policy-for-EB` 許可政策連接到您所建立的 `Role-for-MyRule` 角色。

      ```
      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 參數**
**重要**  
當您使用這個方法建立管道時，如果沒有明確設為 false，則 `PollForSourceChanges` 參數會預設為 true。當新增基於事件的變更偵測時，您必須將該參數新增到輸出，並將其設為 false 以停用輪詢。否則，您的管道會針對單一來源變更啟動兩次。如需詳細資訊，請參閱[`PollForSourceChanges` 參數的有效設定](PollForSourceChanges-defaults.md)。

1. 執行 **get-pipeline** 命令，將管道結構複製到 JSON 檔案。例如，針對名為 `MyFirstPipeline` 的管道，執行下列命令：

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

   此命令不會傳回任何內容，但您建立的檔案應該會顯示在您執行命令的目錄中。

1. 在任何純文字編輯器中開啟 JSON 檔案，然後將名為 `amzn-s3-demo-source-bucket` 之儲存貯體的 `PollForSourceChanges` 參數變更為 `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. 若要套用您的變更，請執行 **update-pipeline** 命令、指定管道 JSON 檔案：
**重要**  
請確認在檔案名稱之前包含 `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 角色。此項目會建立一個使用兩個政策的角色：
   + 第一個政策允許要承擔的角色。
   + 第二個政策提供啟動管道的許可。

   **為什麼我會做出此變更？** 新增`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. 選擇您的堆疊，然後選擇 **Create Change Set for Current Stack (建立目前堆疊的變更集)**。

1. 上傳您的更新範本，然後檢視中 CloudFormation所列的變更。這些是會針對堆疊進行的變更。您應該會在清單中看到新資源。

1. 選擇 **Execute (執行)**。<a name="proc-cfn-flag-s3"></a>

**編輯管道的 PollForSourceChanges 參數**
**重要**  
當您使用這個方法建立管道時，如果沒有明確設為 false，則 `PollForSourceChanges` 參數會預設為 true。當新增基於事件的變更偵測時，您必須將該參數新增到輸出，並將其設為 false 以停用輪詢。否則，您的管道會針對單一來源變更啟動兩次。如需詳細資訊，請參閱[`PollForSourceChanges` 參數的有效設定](PollForSourceChanges-defaults.md)。
+ 在範本中，將 `PollForSourceChanges` 變更為 `false`。如果您並未在管道定義中包含 `PollForSourceChanges`，請新增它，並將其設為 `false`。

  **為什麼我會做出此變更？** 將 `PollForSourceChanges`變更為 `false` 會關閉定期檢查，因此您只能使用事件型變更偵測。

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

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

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

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

------

**Example**  
當您使用 CloudFormation 建立這些資源時，您的管道會在儲存庫中的檔案建立或更新時觸發。  
不要在此處停止。雖然您的管道已建立，但您必須為 Amazon S3 管道建立第二個 CloudFormation 範本。如果您未建立第二個範本，您的管道不會有任何變更偵測功能。

```
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. 使用執行以下命令，將新的 `CodePipeline-Permissions-Policy-for-EB` 許可政策連接到您所建立的 `Role-for-MyRule` 角色。

      ```
      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 參數**
**重要**  
當您使用這個方法建立管道時，如果沒有明確設為 false，則 `PollForSourceChanges` 參數會預設為 true。當新增基於事件的變更偵測時，您必須將該參數新增到輸出，並將其設為 false 以停用輪詢。否則，您的管道會針對單一來源變更啟動兩次。如需詳細資訊，請參閱[`PollForSourceChanges` 參數的有效設定](PollForSourceChanges-defaults.md)。

1. 執行 **get-pipeline** 命令，將管道結構複製到 JSON 檔案。例如，針對名為 `MyFirstPipeline` 的管道，執行下列命令：

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

   此命令不會傳回任何內容，但您建立的檔案應該會顯示在您執行命令的目錄中。

1. 在任何純文字編輯器中開啟 JSON 檔案，然後將名為 `amzn-s3-demo-source-bucket` 之儲存貯體的 `PollForSourceChanges` 參數變更為 `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. 若要套用您的變更，請執行 **update-pipeline** 命令、指定管道 JSON 檔案：
**重要**  
請確認在檔案名稱之前包含 `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 角色。此項目會建立一個使用兩個政策的角色：
   + 第一個政策允許要承擔的角色。
   + 第二個政策提供啟動管道的許可。

   **為什麼我會做出此變更？** 新增`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 來源儲存貯體`CompleteMultipartUpload`上監控 `CopyObject`、 `PutObject`和 。此外，會包含您管道的目標。當 `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. 選擇您的堆疊，然後選擇 **Create Change Set for Current Stack (建立目前堆疊的變更集)**。

1. 上傳您的更新範本，然後檢視中 CloudFormation所列的變更。這些是會針對堆疊進行的變更。您應該會在清單中看到新資源。

1. 選擇 **Execute (執行)**。<a name="proc-cfn-flag-s3"></a>

**編輯管道的 PollForSourceChanges 參數**
**重要**  
當您使用這個方法建立管道時，如果沒有明確設為 false，則 `PollForSourceChanges` 參數會預設為 true。當新增基於事件的變更偵測時，您必須將該參數新增到輸出，並將其設為 false 以停用輪詢。否則，您的管道會針對單一來源變更啟動兩次。如需詳細資訊，請參閱[`PollForSourceChanges` 參數的有效設定](PollForSourceChanges-defaults.md)。
+ 在範本中，將 `PollForSourceChanges` 變更為 `false`。如果您並未在管道定義中包含 `PollForSourceChanges`，請新增它，並將其設為 `false`。

  **為什麼我會做出此變更？** 將 `PollForSourceChanges`變更為 `false` 會關閉定期檢查，因此您只能使用事件型變更偵測。

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

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

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

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

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

**為 Amazon S3 管道的 CloudTrail 資源建立第二個範本**
+ 在個別範本的 下`Resources`，使用 `AWS::S3::Bucket`、 `AWS::S3::BucketPolicy`和 `AWS::CloudTrail::Trail` CloudFormation 資源為 CloudTrail 提供簡單的儲存貯體定義和線索。

  **為什麼要進行這項變更？ ** 鑑於每個帳戶的目前限制為 5 個線索，必須分別建立和管理 CloudTrail 線索。（請參閱 [中的限制 AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/WhatIsCloudTrail-Limits.html)。) 不過，您可以在單一線索上包含許多 Amazon S3 儲存貯體，因此您可以建立一次線索，然後視需要為其他管道新增 Amazon S3 儲存貯體。將下列內容貼至您的第二個範例範本檔案中。

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

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

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

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

------

**Example**  
當您使用 CloudFormation 建立這些資源時，您的管道會在儲存庫中的檔案建立或更新時觸發。  
不要在此處停止。雖然您的管道已建立，但您必須為 Amazon S3 管道建立第二個 CloudFormation 範本。如果您未建立第二個範本，您的管道不會有任何變更偵測功能。

```
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：儲存連線的來源動作。

#### 步驟 2：建立 GitHub 的連線
<a name="update-change-detection-github-connection-console-install"></a>

選擇建立連線後，會顯示**連線至 GitHub** 頁面。

**建立連至 GitHub 的連線**

1. 在 **GitHub 連線設定**下，您的連線名稱會顯示在**連線名稱**中。

   在 **GitHub Apps (GitHub 應用程式)** 底下，選擇應用程式安裝，或選擇 **Install a new app (安裝新應用程式)** 以建立安裝。
**注意**  
您可以為您連至特定供應商的所有連線安裝一個應用程式。如果您已安裝 GitHub 應用程式，請選擇它並略過此步驟。

1. 如果顯示 GitHub 的授權頁面，請使用您的登入資料登入，然後選擇繼續。

1. 在應用程式安裝頁面上，訊息顯示 AWS CodeStar 應用程式正在嘗試連線到您的 GitHub 帳戶。
**注意**  
您只能為每個 GitHub 帳戶安裝一次應用程式。如果您先前已安裝應用程式，可以選擇 **Configure (設定)**，繼續前往應用程式安裝的修改頁面，或者您可以使用上一步按鈕返回主控台。

1. 在**安裝 AWS CodeStar**頁面上，選擇**安裝**。

1. 在**連線至 GitHub** 頁面上，會顯示新安裝的連線 ID。選擇**連線**。

#### 步驟 3：儲存您的 GitHub 來源動作
<a name="update-change-detection-github-connection-console-save"></a>

在**編輯動作**頁面上完成更新，以儲存新的來源動作。

**儲存您的 GitHub 來源動作**

1. 在**儲存庫**中，輸入第三方儲存庫的名稱。在**分支**中，輸入您希望管道偵測來源變更的分支。
**注意**  
在**儲存庫**中，輸入 `owner-name/repository-name`，如本範例所示：  

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

1. 在**輸出成品格式**中，選擇成品的格式。
   + 若要使用預設方法儲存 GitHub 動作的輸出成品，請選擇 **CodePipeline 預設**。動作會從 GitHub 儲存庫存取檔案，並將成品存放在管道成品存放區中的 ZIP 檔案中。
   + 若要存放包含儲存庫 URL 參考的 JSON 檔案，以便下游動作可以直接執行 Git 命令，請選擇 **Full clone (完整複製)**。此選項只能由 CodeBuild 下游動作使用。

     如果您選擇此選項，您將需要更新 CodeBuild 專案服務角色的許可，如 所示[新增連線至 Bitbucket、GitHub、GitHub Enterprise Server 或 GitLab.com 的 CodeBuild GitClone 許可 GitLab.com](troubleshooting.md#codebuild-role-connections)。如需示範如何使用**完整複製**選項的教學課程，請參閱 [教學課程：搭配 GitHub 管道來源使用完整複製](tutorials-github-gitclone.md)。

1. 在**輸出成品**中，您可以保留此動作的輸出成品名稱，例如 `SourceArtifact`。選擇**完成**以關閉**編輯動作**頁面。

1. 選擇**完成**以關閉階段編輯頁面。選擇**儲存**以關閉管道編輯頁面。

### 建立連至 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)。使用 AWS CLI 執行 **create-connection**命令，`--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 Webhook 時，請勿使用您自己的登入資料，或在多個 Webhook 之間重複使用相同的秘密字符。為了獲得最佳安全性，請為您建立的每個 Webhook 產生唯一的秘密字符。秘密字符是您提供的任意字串，GitHub 用來計算和簽署傳送至 CodePipeline 的 Webhook 承載，以保護 Webhook 承載的完整性和真實性。在多個 Webhook 中使用您自己的登入資料或重複使用相同的字符可能會導致安全漏洞。

### 將輪詢管道遷移至 Webhook (GitHub （透過 OAuth 應用程式） 來源動作） （主控台）
<a name="update-change-detection-console-github"></a>

對於 GitHub （透過 OAuth 應用程式） 來源動作，您可以使用 CodePipeline 主控台來更新管道，以使用 Webhook 來偵測 GitHub 來源儲存庫中的變更。

請依照下列步驟編輯正在使用輪詢 （定期檢查） 的管道，以改用 EventBridge。如果您想要建立管道，請參閱[建立管道、階段和動作](pipelines-create.md)。

使用主控台時，會為您變更管道的 `PollForSourceChanges` 參數。為您建立並註冊 GitHub Webhook。

**編輯管道來源階段**

1. 登入 AWS 管理主控台 並開啟 CodePipeline 主控台，網址為 https：//[http://console.aws.amazon.com/codesuite/codepipeline/home](https://console.aws.amazon.com/codesuite/codepipeline/home)。

   與 AWS 您的帳戶相關聯的所有管道名稱都會顯示。

1. 在 **Name (名稱)** 中，選擇您想編輯的管道名稱。這會開啟管道的詳細檢視，包含管道中各階段的每項動作之每項狀態。

1. 在管道詳細資訊頁面上，選擇 **Edit (編輯)**。

1. 在 **Edit (編輯)** 階段中，選擇來源動作上的編輯圖示。

1. 展開 **Change detection options (變更偵測選項)**，然後選擇 **Use Amazon CloudWatch Events to automatically start my pipeline when a change occurs (recommended) (使用 Amazon CloudWatch 事件以在發生變更時自動啟動我的管道 (建議))**。

   隨即顯示一則訊息，告知 CodePipeline 在 GitHub 中建立 Webhook 以偵測來源變更： AWS CodePipeline 會為您建立 Webhook。您可以在下列選項中選擇退出。選擇**更新**。除了 Webhook 之外，CodePipeline 還會建立下列項目：
   + 一個秘密，其是隨機產生的，並用來授權與 GitHub 的連線。
   + Webhook URL，這是使用區域的公有端點所產生。

   CodePipeline 向 GitHub 註冊 Webhook。這將訂閱 URL 以接收儲存庫事件。

1. 當您完成管道編輯後，請選擇 **Save pipeline changes (儲存管道變更)**​ 以返回摘要頁面。

   訊息顯示要為管道建立的 Webhook 名稱。選擇**儲存並繼續**。

1. 若要測試您的動作，請使用 AWS CLI 將變更遞交至管道來源階段中指定的來源，以釋出變更。

### 將輪詢管道遷移至 Webhook (GitHub （透過 OAuth 應用程式） 來源動作） (CLI)
<a name="update-change-detection-cli-github"></a>

請遵循下列步驟來編輯正在使用定期檢查的管道，以改用 Webhook。如果您想要建立管道，請參閱[建立管道、階段和動作](pipelines-create.md)。

若要建置事件驅動型管道，您可以編輯管道的 `PollForSourceChanges` 參數，然後手動建立以下資源：
+ GitHub Webhook 和授權參數<a name="proc-cli-gh-webhook"></a>

**建立和註冊您的 Webhook**
**注意**  
當您使用 CLI 或 CloudFormation 建立管道並新增 Webhook 時，您必須停用定期檢查。若要停用定期檢查，您必須明確新增 `PollForSourceChanges` 參數，並將其設為 false，如以下最終程序中所詳述。否則，CLI 或 CloudFormation 管道的預設值為 `PollForSourceChanges` true，且不會顯示在管道結構輸出中。如需有關 PollForSourceChanges 預設值的詳細資訊，請參閱 [`PollForSourceChanges` 參數的有效設定](PollForSourceChanges-defaults.md)。

1. 在文字編輯器中，為您想建立的 webhook 建立並儲存一個 JSON 檔案。為名為 `my-webhook`的 Webhook 使用此範例檔案：

   ```
   {
       "webhook": {
           "name": "my-webhook",
   	 "targetPipeline": "{{pipeline_name}}",
   	 "targetAction": "{{source_action_name}}",
   	 "filters": [{
   	     "jsonPath": "$.ref",
   	     "matchEquals": "refs/heads/{Branch}"
   	 }],
   	 "authentication": "GITHUB_HMAC",
   	 "authenticationConfiguration": {
   	     "SecretToken": "{{secret}}"
   	 }
       }
   }
   ```

1. 呼叫 **put-webhook** 命令，並包含 `--cli-input` 和 `--region` 參數。

   以下命令範例會利用 `webhook_json` JSON 檔案建立一個 Webhook。

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

1. 在此範例顯示的輸出中，會針對名為 `my-webhook` 的 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"
       }]
   }
   ```

   此範例透過在 Webhook 上包含 `Project` 標籤索引鍵和 `ProjectA` 值，將標籤新增到 Webhook。如需在 CodePipeline 中標記資源的詳細資訊，請參閱 [標記 資源](tag-resources.md)。

1. 呼叫 **register-webhook-with-third-party** 命令並加入 `--webhook-name` 參數。

   以下範例命令會註冊名為 `my-webhook` 的 Webhook。

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

**編輯管道的 PollForSourceChanges 參數**
**重要**  
當您使用這個方法建立管道時，如果沒有明確設為 false，則 `PollForSourceChanges` 參數會預設為 true。當新增基於事件的變更偵測時，您必須將該參數新增到輸出，並將其設為 false 以停用輪詢。否則，您的管道會針對單一來源變更啟動兩次。如需詳細資訊，請參閱[`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. 若要套用您的變更，請執行 **update-pipeline** 命令，並指定管道 JSON 檔案，與下面類似：
**重要**  
請確認在檔案名稱之前包含 `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>

請遵循下列步驟，使用 webhook 將您的管道 (具有 GitHub 來源) 從定期檢查 (輪詢) 更新為事件型變更偵測。

若要使用 建置事件驅動型管道 AWS CodeCommit，您可以編輯管道的 `PollForSourceChanges` 參數，然後將 GitHub Webhook 資源新增至範本。

如果您使用 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>

**在您的範本中新增參數並建立 Webhook**

我們強烈建議您使用 AWS Secrets Manager 來存放您的登入資料。如果您使用 Secrets Manager，則您必須已在 Secrets Manager 中設定並存放秘密參數。此範例針對 Webhook 的 GitHub 登入資料使用 Secrets Manager 的動態參考。如需詳細資訊，請參閱[使用動態參考來指定範本值](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-secretsmanager)。
**重要**  
傳遞機密參數時，請勿在範本中直接輸入值。此值渲染為純文字，因此為可讀取。基於安全考量，請勿在 CloudFormation 範本中使用純文字來存放您的登入資料。

當您使用 CLI 或 CloudFormation 建立管道並新增 Webhook 時，您必須停用定期檢查。
**注意**  
若要停用定期檢查，您必須明確新增 `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 資源來新增 Webhook。
**注意**  
您指定的 `TargetAction` 必須符合管道中定義之來源動作的 `Name` 屬性。

   如果 `RegisterWithThirdParty` 設為 `true`，請確定與 `OAuthToken` 關連的使用者可以設定 GitHub 中的所需範圍。字符和 Webhook 需要下列 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. 選擇您的堆疊，然後選擇 **Create Change Set for Current Stack (建立目前堆疊的變更集)**。

1. 上傳範本，然後檢視 CloudFormation中所列的變更。這些是會針對堆疊進行的變更。您應該會在清單中看到新資源。

1. 選擇 **Execute (執行)**。<a name="proc-cfn-flag-github"></a>

**編輯管道的 PollForSourceChanges 參數**
**重要**  
當您使用這個方法建立管道時，如果沒有明確設為 false，則 `PollForSourceChanges` 參數會預設為 true。當新增基於事件的變更偵測時，您必須將該參數新增到輸出，並將其設為 false 以停用輪詢。否則，您的管道會針對單一來源變更啟動兩次。如需詳細資訊，請參閱[`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，定義的 Webhook 會在指定的 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

...
```