

# Amazon ECR source actions and EventBridge resources
<a name="create-cwe-ecr-source"></a>

To add an Amazon ECR 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 **Amazon ECR** provider option. The console creates an EventBridge rule that starts your pipeline when the source changes.
+ Use the CLI to add the action configuration for the `ECR` action and create additional resources as follows:
  + Use the `ECR` example action configuration in [Amazon ECR source action reference](action-reference-ECR.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 an Amazon ECR source (console)](create-cwe-ecr-source-console.md), [Create an EventBridge rule for an Amazon ECR source (CLI)](create-cwe-ecr-source-cli.md), or [Create an EventBridge rule for an Amazon ECR source (CloudFormation template)](create-cwe-ecr-source-cfn.md).

**Topics**
+ [Create an EventBridge rule for an Amazon ECR source (console)](create-cwe-ecr-source-console.md)
+ [Create an EventBridge rule for an Amazon ECR source (CLI)](create-cwe-ecr-source-cli.md)
+ [Create an EventBridge rule for an Amazon ECR source (CloudFormation template)](create-cwe-ecr-source-cfn.md)

# Create an EventBridge rule for an Amazon ECR source (console)
<a name="create-cwe-ecr-source-console"></a>

**To create an EventBridge rule for use in CodePipeline operations (Amazon ECR source)**

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 **Events**.

1. Choose **Create rule**, and then under **Event source**, from **Service Name**, choose **Elastic Container Registry (ECR)**.

1. In **Event Source**, choose **Event Pattern**.

   Choose **Edit**, and then paste the following example event pattern in the **Event Source** window for a `eb-test` repository with an image tag of `cli-testing`:

   ```
   {
       "detail-type": [
           "ECR Image Action"
       ],
       "source": [
           "aws.ecr"
       ],
       "detail": {
           "action-type": [
               "PUSH"
           ],
           "image-tag": [
               "latest"
           ],
           "repository-name": [
               "eb-test"
           ],
           "result": [
               "SUCCESS"
           ]
       }
   }
   ```
**Note**  
To view the full event pattern supported for Amazon ECR events, see [Amazon ECR Events and EventBridge](https://docs.aws.amazon.com/AmazonECR/latest/userguide/ecr-eventbridge.html) or [Amazon Elastic Container Registry Events](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html#ecr-event-types).

1. Choose **Save**.

   In the **Event Pattern Preview** pane, view the rule.

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. 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": "IMAGE_DIGEST",
                 "revisionValue": "<revisionValue>"
             }
         ],
          "variables": [
             {
                 "name": "Variable_Name",
                 "value": "Variable_Value"
             }
         ]
     }
     ```
   + Choose **Confirm**.

1. Review your rule setup to make sure it meets your requirements.

1. Choose **Configure details**.

1. On the **Configure rule details** page, enter a name and description for the rule, and then choose **State** to enable the rule.

1. If you're satisfied with the rule, choose **Create rule**.

# Create an EventBridge rule for an Amazon ECR source (CLI)
<a name="create-cwe-ecr-source-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).

**To create an EventBridge rule with Amazon ECR 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?** You must create an event with a rule that specifies how an image push must be made, and a target that names the pipeline to be started by the event.

   The following sample command creates a rule called `MyECRRepoRule`.

   ```
   aws events put-rule --name "MyECRRepoRule" --event-pattern "{\"detail-type\":[\"ECR Image Action\"],\"source\":[\"aws.ecr\"],\"detail\":{\"action-type\":[\"PUSH\"],\"image-tag\":[\"latest\"],\"repository-name\":[\"eb-test\"],\"result\":[\"SUCCESS\"]}}}" --role-arn "arn:aws:iam::ACCOUNT_ID:role/Role-for-MyRule"
   ```
**Note**  
To view the full event pattern supported for Amazon ECR events, see [Amazon ECR Events and EventBridge](https://docs.aws.amazon.com/AmazonECR/latest/userguide/ecr-eventbridge.html) or [Amazon Elastic Container Registry Events](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html#ecr-event-types).

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 `MyECRRepoRule`, 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 and the example `RoleArn` for the rule. The pipeline starts when something changes in the repository.

   ```
   aws events put-targets --rule MyECRRepoRule --targets Id=1,Arn=arn:aws:codepipeline:us-west-2:80398EXAMPLE:TestPipeline,RoleArn=arn:aws:iam::80398EXAMPLE:role/Role-for-MyRule
   ```

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`, `IMAGE_DIGEST` 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": "ARN",
               "InputTransformer": {
                   "InputPathsMap": {
                       "revisionValue": "$.detail.image-digest"
                   },
                   "InputTemplate": {
                       "sourceRevisions": [
                           {
                               "actionName": "Source",
                               "revisionType": "IMAGE_DIGEST",
                               "revisionValue": "<revisionValue>"
                           }
                       ]
                   }
               }
           }
       ]
   }
   ```

# Create an EventBridge rule for an Amazon ECR source (CloudFormation template)
<a name="create-cwe-ecr-source-cfn"></a>



To use CloudFormation to create a rule, use the template snippet as shown here.

**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?** You must create a role that can be assumed by EventBridge to start an execution in our pipeline.

------
#### [ 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: !Sub arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${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::Sub": "arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${AppPipeline}"
                                   }
                               }
                           ]
                       }
                   }
               ]
           }
       }
   }
   ...
   ```

------

1. In the template, under `Resources`, use the `AWS::Events::Rule` CloudFormation resource to add an EventBridge rule for the Amazon ECR source. This event pattern creates an event that monitors commits to your repository. When EventBridge detects a repository state change, the rule invokes `StartPipelineExecution` on your target pipeline.

   **Why am I making this change? ** You must create an event with a rule that specifies how an image push must be made, and a target that names the pipeline to be started by the event.

   This snippet uses an image named `eb-test` with a tag of `latest`.

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

   ```
   EventRule:
     Type: 'AWS::Events::Rule'
     Properties:
       EventPattern:
         detail:
           action-type: [PUSH]
           image-tag: [latest]
           repository-name: [eb-test]
           result: [SUCCESS]
         detail-type: [ECR Image Action]
         source: [aws.ecr]
       Targets:
         - Arn: !Sub arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${AppPipeline}
           RoleArn: !GetAtt 
             - EventRole
             - Arn
           Id: codepipeline-AppPipeline
   ```

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

   ```
   {
       "EventRule": {
           "Type": "AWS::Events::Rule",
           "Properties": {
               "EventPattern": {
                   "detail": {
                       "action-type": [
                           "PUSH"
                       ],
                       "image-tag": [
                           "latest"
                       ],
                       "repository-name": [
                           "eb-test"
                       ],
                       "result": [
                           "SUCCESS"
                       ]
                   },
                   "detail-type": [
                       "ECR Image Action"
                   ],
                   "source": [
                       "aws.ecr"
                   ]
               },
               "Targets": [
                   {
                       "Arn": {
                           "Fn::Sub": "arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${AppPipeline}"
                       },
                       "RoleArn": {
                           "Fn::GetAtt": [
                               "EventRole",
                               "Arn"
                           ]
                       },
                       "Id": "codepipeline-AppPipeline"
                   }
               ]
           }
       }
   },
   ```

------
**Note**  
To view the full event pattern supported for Amazon ECR events, see [Amazon ECR Events and EventBridge](https://docs.aws.amazon.com/AmazonECR/latest/userguide/ecr-eventbridge.html) or [Amazon Elastic Container Registry Events](https://docs.aws.amazon.com/eventbridge/latest/userguide/event-types.html#ecr-event-types).

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`, `IMAGE_DIGEST` 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: ARN
     InputTransformer:
       InputPathsMap:
         revisionValue: "$.detail.image-digest"
       InputTemplate:
         sourceRevisions:
           actionName: Source
           revisionType: IMAGE_DIGEST
           revisionValue: '<revisionValue>'
   ```

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