

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# CodeCommit 源操作和 EventBridge
<a name="triggering"></a>

要在中添加 CodeCommit 源动作 CodePipeline，可以选择以下任一选项：
+ 使用 CodePipeline 控制台的 “**创建管道**” 向导 ([创建自定义管道（控制台）](pipelines-create.md#pipelines-create-console)) 或 **“编辑” 操作**页面选择**CodeCommit**提供者选项。控制台会创建一条 EventBridge规则，当源发生变化时，该规则会启动您的管道。
+ 使用 AWS CLI 为操作添加操作配置并创建其他资源，如下所示：`CodeCommit`
  + 使用 [CodeCommit 源操作参考](action-reference-CodeCommit.md) 中的 `CodeCommit` 示例操作配置来创建操作，如[创建管道（CLI）](pipelines-create.md#pipelines-create-cli) 中所示。
  + 更改检测方法默认为通过轮询源来启动管道。应禁用定期检查并手动创建更改检测规则。使用以下方法之一：[为 CodeCommit 来源创建 EventBridge 规则（控制台）](pipelines-trigger-source-repo-changes-console.md)、[为 CodeCommit 源创建 EventBridge 规则 (CLI)](pipelines-trigger-source-repo-changes-cli.md)或[为 CodeCommit 来源（CloudFormation 模板）创建 EventBridge 规则](pipelines-trigger-source-repo-changes-cfn.md)。

**Topics**
+ [为 CodeCommit 来源创建 EventBridge 规则（控制台）](pipelines-trigger-source-repo-changes-console.md)
+ [为 CodeCommit 源创建 EventBridge 规则 (CLI)](pipelines-trigger-source-repo-changes-cli.md)
+ [为 CodeCommit 来源（CloudFormation 模板）创建 EventBridge 规则](pipelines-trigger-source-repo-changes-cfn.md)

# 为 CodeCommit 来源创建 EventBridge 规则（控制台）
<a name="pipelines-trigger-source-repo-changes-console"></a>

**重要**  
如果您使用控制台创建或编辑管道，则会为您创建 EventBridge 规则。

**创建用于 CodePipeline 操作的 EventBridge 规则**

1. 打开 Amazon EventBridge 控制台，网址为[https://console.aws.amazon.com/events/](https://console.aws.amazon.com/events/)。

1. 在导航窗格中，选择**规则**。保留选中的默认总线或选择一个事件总线。选择 **Create rule**（创建规则）。

1. 在**名称**中，输入规则的名称。

1. 对于**规则类型**，选择**具有事件模式的规则**。选择**下一步**。

1. 在 “**事件来源**” 下，选择**AWS 事件或 EventBridge 合作伙伴事件**。

1. 在**示例事件类型**下，选择 **AWS 事件**。

1. 在**示例事件**中，键入 CodeCommit 作为要筛选的关键字。选择 “**CodeCommit 存储库状态更改”**。

1. 在**创建方法**下，选择**自定义模式（JSON 编辑器）**。

   粘贴下面提供的事件模式。以下是带有名为的分支的`MyTestRepo`存储库的 “**事件**” 窗口中的示例 CodeCommit事件模式`main`：

   ```
   {
     "source": [
       "aws.codecommit"
     ],
     "detail-type": [
       "CodeCommit Repository State Change"
     ],
     "resources": [
       "arn:aws:codecommit:us-west-2:80398EXAMPLE:MyTestRepo"
     ],
     "detail": {
       "referenceType": [
         "branch"
       ],
       "referenceName": [
         "main"
       ]
     }
   }
   ```

1. 在**目标**中，选择**CodePipeline**。

1. 输入该规则将启动的管道的管道 ARN。
**注意**  
在运行 **get-pipeline** 命令后，您可以在元数据输出中找到管道 ARN。管道 ARN 是使用以下格式构造的：  
arn: aws: codepiline::: *region* *account* *pipeline-name*  
示例管道 ARN：  
`arn:aws:codepipeline:us-east-2:80398EXAMPLE:MyFirstPipeline`

1. 要创建或指定一个 IAM 服务角色以授予调用与您的 EventBridge 规则关联的目标的 EventBridge 权限（在本例中，目标是 CodePipeline），请执行以下操作：
   + 选择 “**为此特定资源创建新角色**” 以创建服务角色，该角色 EventBridge授予您启动管道执行的权限。
   + 选择 “**使用现有角色**” 输入一个服务角色，该角色 EventBridge 授予您启动管道执行的权限。

1. （可选）要使用特定映像 ID 指定源覆盖，请使用输入转换器将数据作为 JSON 参数传递。您也可以使用输入转换器来传递管道变量。
   + 展开**其他设置**。

     对于**配置目标输入**，选择**配置输入转换器**。

     在对话框窗口中，选择**输入我自己的**。在**输入路径**框中，键入以下键值对。

     ```
     {"revisionValue": "$.detail.image-digest"}
     ```
   + 在**模板**框中，键入以下键值对。

     ```
     {
         "sourceRevisions": [
             {
                 "actionName": "Source",
                 "revisionType": "COMMIT_ID",
                 "revisionValue": "<revisionValue>"
             }
         ],
         "variables": [
             {
                 "name": "Branch_Name",
                 "value": "value"
             }
         ]
     }
     ```
   + 选择**确认**。

1. 选择**下一步**。

1. 在**标签**页面上，选择**下一步**。

1. 在**查看和创建**页面上，检查规则配置。如果您对规则满意，请选择 **Create rule**。

# 为 CodeCommit 源创建 EventBridge 规则 (CLI)
<a name="pipelines-trigger-source-repo-changes-cli"></a>

调用 **put-rule** 命令，在命令中指定：
+ 唯一地标识创建的规则的名称。在您创建的与 AWS 账户 CodePipeline 关联的所有管道中，此名称必须是唯一的。
+ 规则使用的源事件模式和详细信息字段。有关更多信息，请参阅 [Amazon EventBridge 和事件模式](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-events.html)。<a name="proc-cli-event-codecommit"></a>

**创建以事件源 CodeCommit 为目标的 EventBridge 规则 CodePipeline**

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"
                       }
                   ]
               }
           }
       ]
   }
   ```<a name="proc-cli-flag-codecommit"></a>

**编辑管道的 PollForSourceChanges 参数**
**重要**  
使用此方法创建管道时，如果 `PollForSourceChanges` 参数未明确设置为 false，则默认为 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`** 命令手动启动您的管道。

# 为 CodeCommit 来源（CloudFormation 模板）创建 EventBridge 规则
<a name="pipelines-trigger-source-repo-changes-cfn"></a>



 CloudFormation 要使用创建规则，请更新您的模板，如下所示。<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* > 是从源事件变量派生的。
   + `BranchName` 和 `Value` 的输出变量已指定。

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

1. 将更新的模板保存到本地计算机，然后打开 CloudFormation 控制台。

1. 选择堆栈，然后选择**为当前堆栈创建更改集**。

1. 上传模板，然后查看 CloudFormation中列出的更改。这些是要对堆栈进行的更改。您应在列表中看到新资源。

1. 选择**执行**。<a name="proc-cfn-flag-codecommit"></a>

**编辑管道的 PollForSourceChanges 参数**
**重要**  
许多情况下，当您创建管道时，`PollForSourceChanges` 参数默认为 true。添加基于事件的更改检测时，必须将参数添加到输出并将其设置为 false 以禁用轮询。否则，您的管道将针对单个源更改启动两次。有关更多信息，请参阅 [`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
      }
    ]
  },
  ```

------