

# CodeCommit source actions and EventBridge
<a name="triggering"></a>

To add a CodeCommit source action in CodePipeline, you can choose either to: 
+ Use the CodePipeline console **Create pipeline** wizard ([Create a custom pipeline (console)](pipelines-create.md#pipelines-create-console)) or **Edit action** page to choose the **CodeCommit** provider option. The console creates an EventBridge rule that starts your pipeline when the source changes.
+ Use the AWS CLI to add the action configuration for the `CodeCommit` action and create additional resources as follows:
  + Use the `CodeCommit` example action configuration in [CodeCommit source action reference](action-reference-CodeCommit.md) to create your action as shown in [Create a pipeline (CLI)](pipelines-create.md#pipelines-create-cli).
  + The change detection method defaults to starting the pipeline by polling the source. You should disable periodic checks and create the change detection rule manually. Use one of the following methods: [Create an EventBridge rule for a CodeCommit source (console)](pipelines-trigger-source-repo-changes-console.md), [Create an EventBridge rule for a CodeCommit source (CLI)](pipelines-trigger-source-repo-changes-cli.md), or [Create an EventBridge rule for a CodeCommit source (CloudFormation template)](pipelines-trigger-source-repo-changes-cfn.md).

**Topics**
+ [

# Create an EventBridge rule for a CodeCommit source (console)
](pipelines-trigger-source-repo-changes-console.md)
+ [

# Create an EventBridge rule for a CodeCommit source (CLI)
](pipelines-trigger-source-repo-changes-cli.md)
+ [

# Create an EventBridge rule for a CodeCommit source (CloudFormation template)
](pipelines-trigger-source-repo-changes-cfn.md)

# Create an EventBridge rule for a CodeCommit source (console)
<a name="pipelines-trigger-source-repo-changes-console"></a>

**Important**  
If you use the console to create or edit your pipeline, your EventBridge rule is created for you.

**To create an EventBridge rule for use in CodePipeline operations**

1. Open the Amazon EventBridge console at [https://console.aws.amazon.com/events/](https://console.aws.amazon.com/events/).

1. In the navigation pane, choose **Rules**. Leave the default bus selected or choose an event bus. Choose **Create rule**.

1. In **Name**, enter a name for your rule.

1. Under **Rule type**, choose **Rule with an event pattern**. Choose **Next**.

1. Under **Event source**, choose **AWS events or EventBridge partner events**.

1. Under **Sample event type**, choose **AWS events**.

1. In **Sample events**, type CodeCommit as the keyword to filter on. Choose **CodeCommit Repository State Change**.

1. Under **Creation method**, choose **Customer pattern (JSON editor)**.

   Paste the event pattern provided below. The following is a sample CodeCommit event pattern in the **Event** window for a `MyTestRepo` repository with a branch named `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. In **Targets**, choose **CodePipeline**.

1. Enter the pipeline ARN for the pipeline to be started by this rule.
**Note**  
You can find the pipeline ARN in the metadata output after you run the **get-pipeline** command. The pipeline ARN is constructed in this format:   
arn:aws:codepipeline:*region*:*account*:*pipeline-name*  
Sample pipeline ARN:  
`arn:aws:codepipeline:us-east-2:80398EXAMPLE:MyFirstPipeline`

1. To create or specify an IAM service role that grants EventBridge permissions to invoke the target associated with your EventBridge rule (in this case, the target is CodePipeline): 
   + Choose **Create a new role for this specific resource** to create a service role that gives EventBridge permissions to your start your pipeline executions.
   + Choose **Use existing role** to enter a service role that gives EventBridge permissions to your start your pipeline executions.

1. (Optional) To specify source overrides with a specific image ID, use the input transformer to pass the data as a JSON parameters. You can also use the input transformer to pass pipeline variables.
   + Expand **Additional settings**.

     Under **Configure target input**, choose **Configure input transformer**.

     In the dialog window, choose **Enter my own**. In the **Input path** box, type the following key-value pairs.

     ```
     {"revisionValue": "$.detail.image-digest"}
     ```
   + In the **Template** box, type the following key-value pairs.

     ```
     {
         "sourceRevisions": [
             {
                 "actionName": "Source",
                 "revisionType": "COMMIT_ID",
                 "revisionValue": "<revisionValue>"
             }
         ],
         "variables": [
             {
                 "name": "Branch_Name",
                 "value": "value"
             }
         ]
     }
     ```
   + Choose **Confirm**.

1. Choose **Next**.

1. On the **Tags** page, choose **Next**.

1. On the **Review and create** page, review the rule configuration. If you're satisfied with the rule, choose **Create rule**.

# Create an EventBridge rule for a CodeCommit source (CLI)
<a name="pipelines-trigger-source-repo-changes-cli"></a>

Call the **put-rule** command, specifying:
+ A name that uniquely identifies the rule you are creating. This name must be unique across all of the pipelines you create with CodePipeline associated with your AWS account.
+ The event pattern for the source and detail fields used by the rule. For more information, see [Amazon EventBridge and Event Patterns](http://docs.aws.amazon.com/eventbridge/latest/userguide/eb-events.html).<a name="proc-cli-event-codecommit"></a>

**To create an EventBridge rule with CodeCommit as the event source and CodePipeline as the target**

1. Add permissions for EventBridge to use CodePipeline to invoke the rule. For more information, see [Using resource-based policies for Amazon EventBridge](http://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-resource-based.html).

   1. Use the following sample to create the trust policy that allows EventBridge to assume the service role. Name the trust policy `trustpolicyforEB.json`.

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

****  

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

------

   1. Use the following command to create the `Role-for-MyRule` role and attach the trust policy.

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

   1. Create the permissions policy JSON, as shown in this sample, for the pipeline named `MyFirstPipeline`. Name the permissions policy `permissionspolicyforEB.json`.

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

****  

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

------

   1. Use the following command to attach the `CodePipeline-Permissions-Policy-for-EB` permissions policy to the `Role-for-MyRule` role.

      **Why am I making this change?** Adding this policy to the role creates permissions for EventBridge.

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

1. Call the **put-rule** command and include the `--name`, `--event-pattern` , and`--role-arn` parameters.

   **Why am I making this change?** This command enables CloudFormation to create the event.

   The following sample command creates a rule called `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. To add CodePipeline as a target, call the **put-targets** command and include the following parameters:
   + The `--rule` parameter is used with the `rule_name` you created by using **put-rule**. 
   + The `--targets` parameter is used with the list `Id` of the target in the list of targets and the `ARN` of the target pipeline.

   The following sample command specifies that for the rule called `MyCodeCommitRepoRule`, the target `Id` is composed of the number one, indicating that in a list of targets for the rule, this is target 1. The sample command also specifies an example `ARN` for the pipeline. The pipeline starts when something changes in the repository.

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

1. (Optional) To configure an input transformer with source overrides for a specific image ID, use the following JSON in your CLI command. The following example configures an override where:
   + The `actionName`, `Source` in this example, is the dynamic value, defined at pipeline creation, not derived from the source event.
   + The `revisionType`, `COMMIT_ID` in this example, is the dynamic value, defined at pipeline creation, not derived from the source event.
   + The `revisionValue`, <*revisionValue*> in this example, is derived from the source event variable.

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

**To edit your pipeline's PollForSourceChanges parameter**
**Important**  
When you create a pipeline with this method, the `PollForSourceChanges` parameter defaults to true if it is not explicitly set to false. When you add event-based change detection, you must add the parameter to your output and set it to false to disable polling. Otherwise, your pipeline starts twice for a single source change. For details, see [Valid settings for the `PollForSourceChanges` parameter](PollForSourceChanges-defaults.md).

1. Run the **get-pipeline** command to copy the pipeline structure into a JSON file. For example, for a pipeline named `MyFirstPipeline`, run the following command: 

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

   This command returns nothing, but the file you created should appear in the directory where you ran the command.

1. Open the JSON file in any plain-text editor and edit the source stage by changing the `PollForSourceChanges` parameter to `false`, as shown in this example.

   **Why am I making this change?** Changing this parameter to `false` turns off periodic checks so you can use event-based change detection only.

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

1. If you are working with the pipeline structure retrieved using the **get-pipeline** command, remove the `metadata` lines from the JSON file. Otherwise, the **update-pipeline** command cannot use it. Remove the `"metadata": { }` lines and the `"created"`, `"pipelineARN"`, and `"updated"` fields.

   For example, remove the following lines from the structure: 

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

   Save the file.

1. To apply your changes, run the **update-pipeline** command, specifying the pipeline JSON file:
**Important**  
Be sure to include `file://` before the file name. It is required in this command.

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

   This command returns the entire structure of the edited pipeline.
**Note**  
The **update-pipeline** command stops the pipeline. If a revision is being run through the pipeline when you run the **update-pipeline** command, that run is stopped. You must manually start the pipeline to run that revision through the updated pipeline. Use the **`start-pipeline-execution`** command to manually start your pipeline.

# Create an EventBridge rule for a CodeCommit source (CloudFormation template)
<a name="pipelines-trigger-source-repo-changes-cfn"></a>



To use CloudFormation to create a rule, update your template as shown here.<a name="proc-cfn-event-codecommit"></a>

**To update your pipeline CloudFormation template and create EventBridge rule**

1. In the template, under `Resources`, use the `AWS::IAM::Role` CloudFormation resource to configure the IAM role that allows your event to start your pipeline. This entry creates a role that uses two policies:
   + The first policy allows the role to be assumed.
   + The second policy provides permissions to start the pipeline.

   **Why am I making this change?** Adding the `AWS::IAM::Role` resource enables CloudFormation to create permissions for EventBridge. This resource is added to your CloudFormation stack.

------
#### [ 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. In the template, under `Resources`, use the `AWS::Events::Rule` CloudFormation resource to add an EventBridge rule. This event pattern creates an event that monitors push changes to your repository. When EventBridge detects a repository state change, the rule invokes `StartPipelineExecution` on your target pipeline.

   **Why am I making this change? ** Adding the `AWS::Events::Rule` resource enables CloudFormation to create the event. This resource is added to your CloudFormation stack.

------
#### [ 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. (Optional) To configure an input transformer with source overrides for a specific image ID, use the following YAML snippet. The following example configures an override where:
   + The `actionName`, `Source` in this example, is the dynamic value, defined at pipeline creation, not derived from the source event.
   + The `revisionType`, `COMMIT_ID` in this example, is the dynamic value, defined at pipeline creation, not derived from the source event.
   + The `revisionValue`, <*revisionValue*> in this example, is derived from the source event variable.
   + The output variables for `BranchName` and `Value` are specified.

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

1. Save the updated template to your local computer, and then open the CloudFormation console.

1. Choose your stack, and then choose **Create Change Set for Current Stack**. 

1. Upload the template, and then view the changes listed in CloudFormation. These are the changes to be made to the stack. You should see your new resources in the list. 

1. Choose **Execute**.<a name="proc-cfn-flag-codecommit"></a>

**To edit your pipeline's PollForSourceChanges parameter**
**Important**  
In many cases, the `PollForSourceChanges` parameter defaults to true when you create a pipeline. When you add event-based change detection, you must add the parameter to your output and set it to false to disable polling. Otherwise, your pipeline starts twice for a single source change. For details, see [Valid settings for the `PollForSourceChanges` parameter](PollForSourceChanges-defaults.md).
+ In the template, change `PollForSourceChanges` to `false`. If you did not include `PollForSourceChanges` in your pipeline definition, add it and set it to `false`.

  **Why am I making this change?** Changing this parameter to `false` turns off periodic checks so you can use event-based change detection only.

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

------