

# Manage triggers for an AWS CodeCommit repository
<a name="how-to-notify"></a>

You can configure a CodeCommit repository so that code pushes or other events trigger actions, such as sending a notification from Amazon Simple Notification Service (Amazon SNS) or invoking a function in AWS Lambda. You can create up to 10 triggers for each CodeCommit repository.

Triggers are commonly configured to:
+ Send emails to subscribed users every time someone pushes to the repository.
+ Notify an external build system to start a build after someone pushes to the main branch of the repository.

Scenarios like notifying an external build system require writing a Lambda function to interact with other applications. The email scenario simply requires creating an Amazon SNS topic. 

This topic shows you how to set permissions that allow CodeCommit to trigger actions in Amazon SNS and Lambda. It also includes links to examples for creating, editing, testing, and deleting triggers.

**Topics**
+ [Create the resource and add permissions for CodeCommit](#how-to-notify-permissions)
+ [Example: Create an AWS CodeCommit trigger for an Amazon SNS topic](how-to-notify-sns.md)
+ [Example: Create an AWS CodeCommit trigger for an AWS Lambda function](how-to-notify-lambda.md)
+ [Example: Create a trigger in AWS CodeCommit for an existing AWS Lambda function](how-to-notify-lambda-cc.md)
+ [Edit triggers for an AWS CodeCommit repository](how-to-notify-edit.md)
+ [Test triggers for an AWS CodeCommit repository](how-to-notify-test.md)
+ [Delete triggers from an AWS CodeCommit repository](how-to-notify-delete.md)

## Create the resource and add permissions for CodeCommit
<a name="how-to-notify-permissions"></a>

You can integrate Amazon SNS topics and Lambda functions with triggers in CodeCommit, but you must first create and then configure resources with a policy that grants CodeCommit the permissions to interact with those resources. You must create the resource in the same AWS Region as the CodeCommit repository. For example, if the repository is in US East (Ohio) (us-east-2), the Amazon SNS topic or Lambda function must be in US East (Ohio).
+ For Amazon SNS topics, you do not need to configure additional IAM policies or permissions if the Amazon SNS topic is created using the same account as the CodeCommit repository. You can create the CodeCommit trigger as soon as you have created and subscribed to the Amazon SNS topic. 
  + For more information about creating topics in Amazon SNS, see the [Amazon SNS documentation](https://docs.aws.amazon.com/sns/latest/dg/GettingStarted.html).
  + For information about using Amazon SNS to send messages to Amazon SQS queues, see [Sending Messages to Amazon SQS Queues](https://docs.aws.amazon.com/sns/latest/dg/SendMessageToSQS.html) in the *Amazon SNS Developer Guide*.
  + For information about using Amazon SNS to invoke a Lambda function, see [Invoking Lambda Functions](https://docs.aws.amazon.com/sns/latest/dg/sns-lambda.html) in the *Amazon SNS Developer Guide*.
+ You can configure Lambda functions by creating the trigger in the Lambda console as part of the function. This is the simplest method, because triggers created in the Lambda console automatically include the permissions required for CodeCommit to invoke the Lambda function. If you create the trigger in CodeCommit, you must include a policy to allow CodeCommit to invoke the function. For more information, see [Create a trigger for an existing Lambda function](how-to-notify-lambda-cc.md).

# Example: Create an AWS CodeCommit trigger for an Amazon SNS topic
<a name="how-to-notify-sns"></a>

You can create a trigger for a CodeCommit repository so that events in that repository trigger notifications from an Amazon Simple Notification Service (Amazon SNS) topic. You might want to create a trigger to an Amazon SNS topic to enable users to subscribe to notifications about repository events, such as the deletion of branches. You can also take advantage of the integration of Amazon SNS topics with other services, such as Amazon Simple Queue Service (Amazon SQS) and AWS Lambda. 

**Note**  
You must point the trigger to an existing Amazon SNS topic that is the action taken in response to repository events. For more information about creating and subscribing to Amazon SNS topics, see [Getting Started with Amazon Simple Notification Service](https://docs.aws.amazon.com/sns/latest/dg/GettingStarted.html). 
Amazon SNS FIFO (first in, first out) topics are not supported for CodeCommit triggers. 

**Topics**
+ [Create a trigger to an Amazon SNS topic for a CodeCommit repository (console)](#how-to-notify-sns-console)
+ [Create a trigger to an Amazon SNS topic for a CodeCommit repository (AWS CLI)](#how-to-notify-sns-cli)

## Create a trigger to an Amazon SNS topic for a CodeCommit repository (console)
<a name="how-to-notify-sns-console"></a>

1. Open the CodeCommit console at [https://console.aws.amazon.com/codesuite/codecommit/home](https://console.aws.amazon.com/codesuite/codecommit/home).

1. In **Repositories**, choose the repository where you want to create triggers for repository events.

1. In the navigation pane for the repository, choose **Settings**, and then choose **Triggers**.

1. Choose **Create trigger**, and then do the following:.
   + In **Trigger name**, enter a name for the trigger (for example, *MyFirstTrigger*).
   + In **Events**, choose the repository events that trigger the Amazon SNS topic to send notifications. 

     If you choose **All repository events**, you cannot choose any other events. To choose a subset of events, remove **All repository events**, and then choose one or more events from the list. For example, if you want the trigger to run only when a user creates a branch or tag in the CodeCommit repository, remove **All repository events**, and then choose **Create branch or tag**.
   + If you want the trigger to apply to all branches of the repository, in **Branches**, leave the selection blank, as this default option applies the trigger to all branches automatically. If you want this trigger to apply to specific branches only, choose up to 10 branch names from the list of repository branches.
   + In **Choose the service to use**, choose **Amazon SNS**.
   + In **Amazon SNS**, choose a topic name from the list or enter the ARN for the topic.
**Note**  
Amazon SNS FIFO (first in, first out) topics are not supported for CodeCommit triggers. You must choose an Amazon SNS topic that has its type set to Standard. 
   + In **Custom data**, provide any optional information you want included in the notification sent by the Amazon SNS topic (for example, an IRC channel name developers use when discussing development in this repository). This field is a string. It cannot be used to pass any dynamic parameters. 

    

1. (Optional) Choose **Test trigger**. This step helps you confirm have correctly configured access between CodeCommit and the Amazon SNS topic. It uses the Amazon SNS topic to send a test notification using data from your repository, if available. If no real data is available, the test notification contains sample data. 

1. Choose **Create trigger** to finish creating the trigger.

## Create a trigger to an Amazon SNS topic for a CodeCommit repository (AWS CLI)
<a name="how-to-notify-sns-cli"></a>

You can also use the command line to create a trigger for an Amazon SNS topic in response to CodeCommit repository events, such as when someone pushes a commit to your repository. 

**To create a trigger for an Amazon SNS topic**

1. Open a plain-text editor and create a JSON file that specifies:
   + The Amazon SNS topic name.
**Note**  
Amazon SNS FIFO (first in, first out) topics are not supported for CodeCommit triggers. You must choose an Amazon SNS topic that has its type set to Standard. 
   + The repository and branches you want to monitor with this trigger. (If you do not specify any branches, the trigger applies to all branches in the repository.)
   + The events that activate this trigger.

    Save the file. 

   For example, to create a trigger for a repository named *MyDemoRepo* that publishes all repository events to an Amazon SNS topic named *MySNSTopic* for two branches, *main* and *preprod*:

   ```
   {
       "repositoryName": "MyDemoRepo",
       "triggers": [
           {
               "name": "MyFirstTrigger",
               "destinationArn": "arn:aws:sns:us-east-2:111122223333:MySNSTopic",
               "customData": "",
               "branches": [
                   "main", "preprod"
               ],
               "events": [
                   "all"
               ]
           }
       ]
   }
   ```

   There must be a trigger block in the JSON for each trigger for a repository. To create more than one trigger for the repository, include more than one trigger block in the JSON. Remember that all triggers created in this file are for the specified repository. You cannot create triggers for multiple repositories in a single JSON file. For example, if you wanted to create two triggers for a repository, you can create a JSON file with two trigger blocks. In the following example, no branches are specified for the second trigger, so that trigger applies to all branches:

    

   ```
   {
       "repositoryName": "MyDemoRepo",
       "triggers": [
           {
               "name": "MyFirstTrigger",
               "destinationArn": "arn:aws:sns:us-east-2:111122223333:MySNSTopic",
               "customData": "",
               "branches": [
                   "main", "preprod"
               ],
               "events": [
                   "all"
               ]
           },
           {
               "name": "MySecondTrigger",
               "destinationArn": "arn:aws:sns:us-east-2:111122223333:MySNSTopic2",
               "customData": "",
               "branches": [],
               "events": [
                   "updateReference", "deleteReference"
               ]
           }
       ]
   }
   ```

   You can create triggers for events you specify, such as when a commit is pushed to a repository. Event types include:
   + `all` for all events in the specified repository and branches.
   + `updateReference` for when commits are pushed to the specified repository and branches.
   + `createReference` for when a new branch or tag is created in the specified repository.
   + `deleteReference` for when a branch or tag is deleted in the specified repository.
**Note**  
You can use more than one event type in a trigger. However, if you specify `all`, you cannot specify other events. 

   To see the full list of valid event types, at the terminal or command prompt, enter **aws codecommit put-repository-triggers help**. 

   In addition, you can include a string in `customData` (for example, an IRC channel name developers use when discussing development in this repository). This field is a string. It cannot be used to pass any dynamic parameters. This string is appended as an attribute to the CodeCommit JSON returned in response to the trigger.

1. (Optional) At a terminal or command prompt, run the **test-repository-triggers** command. This test uses sample data from the repository (or generates sample data if no data is available) to send a notification to the subscribers of the Amazon SNS topic. For example, the following is used to test that the JSON in the trigger file named *trigger.json* is valid and that CodeCommit can publish to the Amazon SNS topic: 

   ```
   aws codecommit test-repository-triggers --cli-input-json file://trigger.json
   ```

   If successful, this command returns information similar to the following:

   ```
   {
       "successfulExecutions": [
           "MyFirstTrigger"
       ],
       "failedExecutions": []
   }
   ```

1. At a terminal or command prompt, run the **put-repository-triggers** command to create the trigger in CodeCommit. For example, to use a JSON file named *trigger.json* to create the trigger:

   `aws codecommit put-repository-triggers --cli-input-json file://trigger.json`

   This command returns a [configuration ID](https://docs.aws.amazon.com/codecommit/latest/APIReference/API_PutRepositoryTriggers.html#-PutRepositoryTriggers-response-configurationId), similar to the following:

   ```
   {
       "configurationId": "0123456-I-AM-AN-EXAMPLE"
   }
   ```

1. To view the configuration of the trigger, run the **get-repository-triggers** command, specifying the name of the repository:

   `aws codecommit get-repository-triggers --repository-name MyDemoRepo`

   This command returns the structure of all triggers configured for the repository, similar to the following:

   ```
   {
       "configurationId": "0123456-I-AM-AN-EXAMPLE",
       "triggers": [
           {
               "events": [
                   "all"
               ],
               "destinationArn": "arn:aws:sns:us-east-2:111122223333:MySNSTopic",
               "branches": [
                   "main",
                   "preprod"
               ],
               "name": "MyFirstTrigger",
               "customData": "Project ID 12345"
           }
       ]
   }
   ```

1. To test the functionality of the trigger itself, make and push a commit to the repository where you configured the trigger. You should see a response from the Amazon SNS topic. For example, if you configured the Amazon SNS topic to send an email, you should see an email from Amazon SNS in the email account subscribed to the topic.

   The following is example output from an email sent from Amazon SNS in response to a push to a CodeCommit repository:

   ```
   {  
     "Records":[  
        {  
           "awsRegion":"us-east-2",
           "codecommit":{
              "references" : [
                 {
                       "commit":"317f8570EXAMPLE",
                       "created":true,
                       "ref":"refs/heads/NewBranch"
                 },
                 {
                       "commit":"4c925148EXAMPLE",
                       "ref":"refs/heads/preprod",
                 }
               ]
             },
           "eventId":"11111-EXAMPLE-ID",
           "eventName":"ReferenceChange",
           "eventPartNumber":1,
           "eventSource":"aws:codecommit",
           "eventSourceARN":"arn:aws:codecommit:us-east-2:111122223333:MyDemoRepo",
           "eventTime":"2016-02-09T00:08:11.743+0000",
           "eventTotalParts":1,
           "eventTriggerConfigId":"0123456-I-AM-AN-EXAMPLE",
           "eventTriggerName":"MyFirstTrigger",
           "eventVersion":"1.0",
           "customData":"Project ID 12345", 
           "userIdentityARN":"arn:aws:iam::111122223333:user/JaneDoe-CodeCommit",
        }
     ]
   }
   ```

# Example: Create an AWS CodeCommit trigger for an AWS Lambda function
<a name="how-to-notify-lambda"></a>

You can create a trigger for a CodeCommit repository so that events in the repository invoke a Lambda function. In this example, you create a Lambda function that returns the URL used to clone the repository to an Amazon CloudWatch log. 

**Topics**
+ [Create the Lambda function](#how-to-notify-lambda-create-function)
+ [View the trigger for the Lambda function in the AWS CodeCommit repository](#how-to-notify-lam-view)

## Create the Lambda function
<a name="how-to-notify-lambda-create-function"></a>

When you use the Lambda console to create the function, you can also create a CodeCommit trigger for the Lambda function. The following steps include a sample Lambda function. The sample is available in two languages: JavaScript and Python. The function returns the URLs used for cloning a repository to a CloudWatch log.

**To create a Lambda function using a Lambda blueprint**

1. Sign in to the AWS Management Console and open the AWS Lambda console at [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/).

1. On the **Lambda Functions** page, choose **Create function**. (If you have not used Lambda before, choose **Get Started Now**.)

1. On the **Create function** page, choose **Author from scratch**. In **Function Name**, provide a name for the function, for example *MyLambdaFunctionforCodeCommit*. In **Runtime**, choose the language you want to use to write your function, and then choose **Create function**.

1. On the **Configuration** tab, choose **Add trigger**.

1.  In **Trigger configuration**, choose **CodeCommit** from the services drop-down list.   
![\[Creating a repository from the console\]](http://docs.aws.amazon.com/codecommit/latest/userguide/images/codecommit-lambda-trigger.png)

    
   + In **Repository name**, choose the name of the repository where you want to configure a trigger that uses the Lambda function in response to repository events.
   + In **Trigger name**, enter a name for the trigger (for example, *MyLambdaFunctionTrigger*).
   + In **Events**, choose the repository events that trigger the Lambda function. If you choose **All repository events**, you cannot choose any other events. If you want to choose a subset of events, clear **All repository events**, and then choose the events you want from the list. For example, if you want the trigger to run only when a user creates a tag or a branch in the AWS CodeCommit repository, remove **All repository events**, and then choose **Create branch or tag**.
   + If you want the trigger to apply to all branches of the repository, in **Branches**, choose **All branches**. Otherwise, choose **Specific branches**. The default branch for the repository is added by default. You can keep or delete this branch from the list. Choose up to 10 branch names from the list of repository branches.
   + (Optional) In **Custom data**, enter information you want included in the Lambda function (for example, the name of the IRC channel used by developers to discuss development in the repository). This field is a string. It cannot be used to pass any dynamic parameters.

   Choose **Add**.

1. On the **Configuration** page, in **Function Code**, in Code entry type, choose Edit code inline.. In  **Runtime**, choose **Node.js**. If you want to create a sample Python function, choose **Python**.

1. In **Code entry type**, choose **Edit code inline**, and then replace the hello world code with one of the two following samples.

   For Node.js:

   ```
   import {
     CodeCommitClient,
     GetRepositoryCommand,
   } from "@aws-sdk/client-codecommit";
   
   const codecommit = new CodeCommitClient({ region: "your-region" });
   
   /**
    * @param {{ Records: { codecommit: { references: { ref: string }[] }, eventSourceARN: string  }[]} event
    */
   export const handler = async (event) => {
     // Log the updated references from the event
     const references = event.Records[0].codecommit.references.map(
       (reference) => reference.ref,
     );
     console.log("References:", references);
   
     // Get the repository from the event and show its git clone URL
     const repository = event.Records[0].eventSourceARN.split(":")[5];
     const params = {
       repositoryName: repository,
     };
   
     try {
       const data = await codecommit.send(new GetRepositoryCommand(params));
       console.log("Clone URL:", data.repositoryMetadata.cloneUrlHttp);
       return data.repositoryMetadata.cloneUrlHttp;
     } catch (error) {
       console.error("Error:", error);
       throw new Error(
         `Error getting repository metadata for repository ${repository}`,
       );
     }
   };
   ```

   For Python:

   ```
   import json
   import boto3
   
   codecommit = boto3.client("codecommit")
   
   
   def lambda_handler(event, context):
       # Log the updated references from the event
       references = {
           reference["ref"]
           for reference in event["Records"][0]["codecommit"]["references"]
       }
       print("References: " + str(references))
   
       # Get the repository from the event and show its git clone URL
       repository = event["Records"][0]["eventSourceARN"].split(":")[5]
       try:
           response = codecommit.get_repository(repositoryName=repository)
           print("Clone URL: " + response["repositoryMetadata"]["cloneUrlHttp"])
           return response["repositoryMetadata"]["cloneUrlHttp"]
       except Exception as e:
           print(e)
           print(
               "Error getting repository {}. Make sure it exists and that your repository is in the same region as this function.".format(
                   repository
               )
           )
           raise e
   ```

1. In the **Permissions** tab, in **Execution role**, choose the role to open it in the IAM console. Edit the attached policy to add `GetRepository` permission for the repository you want to use the trigger.

## View the trigger for the Lambda function in the AWS CodeCommit repository
<a name="how-to-notify-lam-view"></a>

After you have created the Lambda function, you can view and test the trigger in AWS CodeCommit. Testing the trigger runs the function in response to the repository events you specify.

**To view and test the trigger for the Lambda function**

1. Open the CodeCommit console at [https://console.aws.amazon.com/codesuite/codecommit/home](https://console.aws.amazon.com/codesuite/codecommit/home).

1. In **Repositories**, choose the repository where you want to view triggers.

1. In the navigation pane for the repository, choose **Settings**, and then choose **Triggers**.

1. Review the list of triggers for the repository. You should see the trigger you created in the Lambda console. Choose it from the list and then choose **Test trigger**. This option attempts to invoke the function with sample data about your repository, including the most recent commit ID for the repository. (If no commit history exists, sample values consisting of zeroes are generated instead.) This helps you confirm that you have correctly configured access between AWS CodeCommit and the Lambda function.

1. To further verify the functionality of the trigger, make and push a commit to the repository where you configured the trigger. You should see a response from the Lambda function on the **Monitoring** tab for that function in the Lambda console. From the **Monitoring** tab, choose **View logs in CloudWatch**. The CloudWatch console opens in a new tab and displays events for your function. Select the log stream from the list that corresponds to the time you pushed your commit. You should see event data similar to the following:

   ```
   START RequestId: 70afdc9a-EXAMPLE Version: $LATEST
   2015-11-10T18:18:28.689Z	70afdc9a-EXAMPLE	References: [ 'refs/heads/main' ]
   2015-11-10T18:18:29.814Z	70afdc9a-EXAMPLE	Clone URL: https://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyDemoRepo
   END RequestId: 70afdc9a-EXAMPLE
   REPORT RequestId: 70afdc9a-EXAMPLE Duration: 1126.87 ms Billed Duration: 1200 ms Memory Size: 128 MB Max Memory Used: 14 MB
   ```

# Example: Create a trigger in AWS CodeCommit for an existing AWS Lambda function
<a name="how-to-notify-lambda-cc"></a>

The easiest way to create a trigger that invokes a Lambda function is to create that trigger in the Lambda console. This built-in integration ensures that CodeCommit has the permissions required to run the function. To add a trigger for an existing Lambda function, go to the Lambda console, and choose the function. On the **Triggers** tab for the function, follow the steps in **Add trigger**. These steps are similar to the ones in [Create the Lambda function](how-to-notify-lambda.md#how-to-notify-lambda-create-function).

You can also create a trigger for a Lambda function in a CodeCommit repository. Doing so requires that you choose an existing Lambda function to invoke. It also requires that you manually configure the permissions required for CodeCommit to run the function.

**Topics**
+ [Manually configure permissions to allow CodeCommit to run a Lambda function](#how-to-notify-lam-perm)
+ [Create a trigger for the Lambda function in a CodeCommit repository (console)](#how-to-notify-lam-console)
+ [Create a trigger to a Lambda function for a CodeCommit repository (AWS CLI)](#how-to-notify-lam-cli)

## Manually configure permissions to allow CodeCommit to run a Lambda function
<a name="how-to-notify-lam-perm"></a>

If you create a trigger in CodeCommit that invokes a Lambda function, you must manually configure the permissions that allow CodeCommit to run the Lambda function. To avoid this manual configuration, consider creating the trigger for the function in the Lambda console instead.<a name="how-to-notify-lambda-create-function-perm"></a>

**To allow CodeCommit to run a Lambda function**

1. Open a plain-text editor and create a JSON file that specifies the Lambda function name, the details of the CodeCommit repository, and the actions you want to allow in Lambda, similar to the following:

   ```
   {
       "FunctionName": "MyCodeCommitFunction", 
       "StatementId": "1", 
       "Action": "lambda:InvokeFunction", 
       "Principal": "codecommit.amazonaws.com", 
       "SourceArn": "arn:aws:codecommit:us-east-1:111122223333:MyDemoRepo", 
       "SourceAccount": "111122223333"
   }
   ```

1. Save the file as a JSON file with a name that is easy for you to remember (for example, *AllowAccessfromMyDemoRepo*.json).

1. Using the JSON file you just created, at the terminal (Linux, macOS, or Unix) or command line (Windows), run the **aws lambda add-permissions** command to add a permission to the resource policy associated with your Lambda function:

   ```
   aws lambda add-permission --cli-input-json file://AllowAccessfromMyDemoRepo.json
   ```

   This command returns the JSON of the policy statement you just added, similar to the following:

   ```
   {
       "Statement": "{\"Condition\":{\"StringEquals\":{\"AWS:SourceAccount\":\"111122223333\"},\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:codecommit:us-east-1:111122223333:MyDemoRepo\"}},\"Action\":[\"lambda:InvokeFunction\"],\"Resource\":\"arn:aws:lambda:us-east-1:111122223333:function:MyCodeCommitFunction\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"codecommit.amazonaws.com\"},\"Sid\":\"1\"}"
   }
   ```

   For more information about resource policies for Lambda functions, see [AddPermission](https://docs.aws.amazon.com/lambda/latest/dg/API_AddPermission.html) and [The Pull/Push Event Models](https://docs.aws.amazon.com/lambda/latest/dg/intro-invocation-modes.html) in the *AWS Lambda User Guide*.

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the **Dashboard** navigation pane, choose **Roles**, and in the list of roles, select *lambda\$1basic\$1execution*.

1. On the summary page for the role, choose the **Permissions** tab, and in **Inline Policies**, choose **Create Role Policy**.

1. On the **Set Permissions** page, choose **Policy Generator**, and then choose **Select**.

1. On the **Edit Permissions** page, do the following:
   + In **Effect**, choose **Allow**.
   + In **AWS Service**, choose **AWS CodeCommit**.
   + In **Actions**, select **GetRepository**.
   + In **Amazon Resource Name (ARN)**, enter the ARN for the repository (for example, `arn:aws:codecommit:us-east-1:111122223333:MyDemoRepo`).

   Choose **Add Statement**, and then choose **Next Step**.

1. On the **Review Policy** page, choose **Apply Policy**. 

   Your policy statement should look similar to the following example:

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "Stmt11111111",
               "Effect": "Allow",
               "Action": [
                   "codecommit:GetRepository"
               ],
               "Resource": [
                   "arn:aws:codecommit:us-east-1:111122223333:MyDemoRepo"
               ]
           }
       ]
   }
   ```

------

## Create a trigger for the Lambda function in a CodeCommit repository (console)
<a name="how-to-notify-lam-console"></a>

After you have created the Lambda function, you can create a trigger in CodeCommit that runs the function in response to the repository events you specify.

**Note**  
Before you can successfully test or run the trigger for the example, you must configure the policies that allow CodeCommit to invoke the function and the Lambda function to get information about the repository. For more information, see [To allow CodeCommit to run a Lambda function](#how-to-notify-lambda-create-function-perm).

**To create a trigger for a Lambda function**

1. Open the CodeCommit console at [https://console.aws.amazon.com/codesuite/codecommit/home](https://console.aws.amazon.com/codesuite/codecommit/home).

1. In **Repositories**, choose the repository where you want to create triggers for repository events.

1. In the navigation pane for the repository, choose **Settings**, and then choose **Triggers**.

1. Choose **Create trigger**.

1. In **Create trigger**, do the following:

    
   + In **Trigger name**, enter a name for the trigger (for example, *MyLambdaFunctionTrigger*).
   + In **Events**, choose the repository events that trigger the Lambda function. 

     If you choose **All repository events**, you cannot choose any other events. If you want to choose a subset of events, clear **All repository events**, and then choose the events you want from the list. For example, if you want the trigger to run only when a user creates a tag or a branch in the CodeCommit repository, remove **All repository events**, and then choose **Create branch or tag**.
   + If you want the trigger to apply to all branches of the repository, in **Branches**, leave the selection blank, because this default option applies the trigger to all branches automatically. If you want this trigger to apply to specific branches only, choose up to 10 branch names from the list of repository branches.
   + In **Choose the service to use**, choose **AWS Lambda**.
   + In **Lambda function**, choose the function name from the list, or enter the ARN for the function.
   + (Optional) In **Custom data**, enter information you want included in the Lambda function (for example, the name of the IRC channel used by developers to discuss development in the repository). This field is a string. It cannot be used to pass any dynamic parameters.

1. (Optional) Choose **Test trigger**. This option attempts to invoke the function with sample data about your repository, including the most recent commit ID for the repository. (If no commit history exists, sample values consisting of zeroes are generated instead.) This helps you confirm that you have correctly configured access between CodeCommit and the Lambda function.

1. Choose **Create trigger** to finish creating the trigger.

1. To verify the functionality of the trigger, make and push a commit to the repository where you configured the trigger. You should see a response from the Lambda function on the **Monitoring** tab for that function in the Lambda console. 

## Create a trigger to a Lambda function for a CodeCommit repository (AWS CLI)
<a name="how-to-notify-lam-cli"></a>

You can also use the command line to create a trigger for a Lambda function in response to CodeCommit repository events, such as when someone pushes a commit to your repository. 

**To create a trigger for an Lambda function**

1. Open a plain-text editor and create a JSON file that specifies:
   + The Lambda function name.
   + The repository and branches you want to monitor with this trigger. (If you do not specify any branches, the trigger applies to all branches in the repository.)
   + The events that activate this trigger.

    Save the file. 

   For example, if you want to create a trigger for a repository named *MyDemoRepo* that publishes all repository events to a Lambda function named *MyCodeCommitFunction* for two branches, *main* and *preprod*:

   ```
   {
       "repositoryName": "MyDemoRepo",
       "triggers": [
           {
               "name": "MyLambdaFunctionTrigger",
               "destinationArn": "arn:aws:lambda:us-east-1:111122223333:function:MyCodeCommitFunction",
               "customData": "",
               "branches": [
                   "main", "preprod"
               ],
               "events": [
                   "all"
               ]
           }
       ]
   }
   ```

   There must be a trigger block in the JSON for each trigger for a repository. To create more than one trigger for a repository, include additional blocks in the JSON. Remember that all triggers created in this file are for the specified repository. You cannot create triggers for multiple repositories in a single JSON file. For example, if you wanted to create two triggers for a repository, you can create a JSON file with two trigger blocks. In the following example, no branches are specified in the second trigger block, so that trigger applies to all branches:

    

   ```
   {
       "repositoryName": "MyDemoRepo",
       "triggers": [
           {
               "name": "MyLambdaFunctionTrigger",
               "destinationArn": "arn:aws:lambda:us-east-1:111122223333:function:MyCodeCommitFunction",
               "customData": "",
               "branches": [
                   "main", "preprod"
               ],
               "events": [
                   "all"
               ]
           },
           {
               "name": "MyOtherLambdaFunctionTrigger",
               "destinationArn": "arn:aws:lambda:us-east-1:111122223333:function:MyOtherCodeCommitFunction",
               "customData": "",
               "branches": [],
               "events": [
                   "updateReference", "deleteReference"
               ]
           }
       ]
   }
   ```

   You can create triggers for events you specify, such as when a commit is pushed to a repository. Event types include:
   + `all` for all events in the specified repository and branches.
   + `updateReference` for when commits are pushed to the specified repository and branches.
   + `createReference` for when a new branch or tag is created in the specified repository.
   + `deleteReference` for when a branch or tag is deleted in the specified repository.
**Note**  
You can use more than one event type in a trigger. However, if you specify `all`, you cannot specify other events. 

   To see the full list of valid event types, at the terminal or command prompt, enter **aws codecommit put-repository-triggers help**. 

   In addition, you can include a string in `customData` (for example, an IRC channel name developers use when discussing development in this repository). This field is a string. It cannot be used to pass any dynamic parameters. This string is appended as an attribute to the CodeCommit JSON returned in response to the trigger.

1. (Optional) At a terminal or command prompt, run the **test-repository-triggers** command. For example, the following is used to test that the JSON file named *trigger.json* is valid and that CodeCommit can trigger the Lambda function. This test uses sample data to trigger the function if no real data is available.

   ```
   aws codecommit test-repository-triggers --cli-input-json file://trigger.json
   ```

   If successful, this command returns information similar to the following:

   ```
   {
       "successfulExecutions": [
           "MyLambdaFunctionTrigger"
       ],
       "failedExecutions": []
   }
   ```

1. At a terminal or command prompt, run the **put-repository-triggers** command to create the trigger in CodeCommit. For example, to use a JSON file named *trigger.json* to create the trigger:

   `aws codecommit put-repository-triggers --cli-input-json file://trigger.json`

   This command returns a configuration ID, similar to the following:

   ```
   {
       "configurationId": "0123456-I-AM-AN-EXAMPLE"
   }
   ```

1. To view the configuration of the trigger, run the **get-repository-triggers** command, specifying the name of the repository:

   `aws codecommit get-repository-triggers --repository-name MyDemoRepo`

   This command returns the structure of all triggers configured for the repository, similar to the following:

   ```
   {
       "configurationId": "0123456-I-AM-AN-EXAMPLE",
       "triggers": [
           {
               "events": [
                   "all"
               ],
               "destinationArn": "arn:aws:lambda:us-east-1:111122223333:MyCodeCommitFunction",
               "branches": [
                   "main",
                   "preprod"
               ],
               "name": "MyLambdaFunctionTrigger",
               "customData": "Project ID 12345"
           }
       ]
   }
   ```

1. To test the functionality of the trigger, make and push a commit to the repository where you configured the trigger. You should see a response from the Lambda function on the **Monitoring** tab for that function in the Lambda console. 

# Edit triggers for an AWS CodeCommit repository
<a name="how-to-notify-edit"></a>

You can edit the triggers that have been created for a CodeCommit repository. You can change the events and branches for the trigger, the action taken in response to the event, and other settings. 

**Topics**
+ [Edit a trigger for a repository (console)](#how-to-notify-edit-console)
+ [Edit a trigger for a repository (AWS CLI)](#how-to-notify-edit-cli)

## Edit a trigger for a repository (console)
<a name="how-to-notify-edit-console"></a>

1. Open the CodeCommit console at [https://console.aws.amazon.com/codesuite/codecommit/home](https://console.aws.amazon.com/codesuite/codecommit/home).

1. In **Repositories**, choose the repository where you want to edit a trigger for repository events.

1. In the navigation pane for the repository, choose **Settings**, and then choose **Triggers**.

1. From the list of triggers for the repository, choose the trigger you want to edit, and then choose **Edit**. 

1. Make the changes you want to the trigger, and then choose **Save**.

## Edit a trigger for a repository (AWS CLI)
<a name="how-to-notify-edit-cli"></a>

1. At a terminal (Linux, macOS, or Unix) or command prompt (Windows), run the **get-repository-triggers** command to create a JSON file with the structure of all of the triggers configured for your repository. For example, to create a JSON file named *MyTriggers.json* with the structure of all of the triggers configured for a repository named *MyDemoRepo*:

   ```
   aws codecommit get-repository-triggers --repository-name MyDemoRepo >MyTriggers.json
   ```

   This command returns nothing, but a file named *MyTriggers.json* is created in the directory where you ran the command.

1. Edit the JSON file in a plain-text editor and make changes to the trigger block of the trigger you want to edit. Replace the `configurationId` pair with a `repositoryName` pair. Save the file.

   For example, if you want to edit a trigger named *MyFirstTrigger* in the repository named *MyDemoRepo* so that it applies to all branches, replace `configurationId` with `repositoryName`, and remove the specified `main` and `preprod` branches in *red italic text*. By default, if no branches are specified, the trigger applies to all branches in the repository:

   ```
   {
       "repositoryName": "MyDemoRepo", 
       "triggers": [
           {
               "destinationArn": "arn:aws:sns:us-east-2:111122223333:MyCodeCommitTopic", 
               "branches": [
                   "main", 
                   "preprod"
               ], 
               "name": "MyFirstTrigger", 
               "customData": "", 
               "events": [
                   "all"
               ]
           }  
       ]
   }
   ```

1. At the terminal or command line, run the **put-repository-triggers** command. This updates all triggers for the repository, including the changes you made to the *MyFirstTrigger* trigger:

   ```
   aws codecommit put-repository-triggers --repository-name MyDemoRepo file://MyTriggers.json
   ```

   This command returns a configuration ID, similar to the following:

   ```
   {
       "configurationId": "0123456-I-AM-AN-EXAMPLE"
   }
   ```

# Test triggers for an AWS CodeCommit repository
<a name="how-to-notify-test"></a>

You can test the triggers that have been created for a CodeCommit repository. Testing involves running the trigger with sample data from your repository, including the most recent commit ID. If no commit history exists for the repository, sample values consisting of zeroes are generated instead. Testing triggers helps you confirm you have correctly configured access between CodeCommit and the target of the trigger, whether that is an AWS Lambda function or an Amazon Simple Notification Service notification. 

**Topics**
+ [Test a trigger for a repository (console)](#how-to-notify-test-console)
+ [Test a trigger for a repository (AWS CLI)](#how-to-notify-test-cli)

## Test a trigger for a repository (console)
<a name="how-to-notify-test-console"></a>

1. Open the CodeCommit console at [https://console.aws.amazon.com/codesuite/codecommit/home](https://console.aws.amazon.com/codesuite/codecommit/home).

1. In **Repositories**, choose the repository where you want to test a trigger for repository events.

1. In the navigation pane for the repository, choose **Settings**, and then choose **Triggers**.

1. Choose the trigger you want to test, and then choose **Test trigger**. You should see a success or failure message. If successful, you should also see a corresponding action response from the Lambda function or the Amazon SNS topic.

## Test a trigger for a repository (AWS CLI)
<a name="how-to-notify-test-cli"></a>

1. At a terminal (Linux, macOS, or Unix) or command prompt (Windows), run the **get-repository-triggers** command to create a JSON file with the structure of all of the triggers configured for your repository. For example, to create a JSON file named *TestTrigger.json* with the structure of all of the triggers configured for a repository named MyDemoRepo:

   ```
   aws codecommit get-repository-triggers --repository-name MyDemoRepo >TestTrigger.json
   ```

   This command creates a file named *TestTriggers.json* in the directory where you ran the command.

1. Edit the JSON file in a plain-text editor and make the changes to the trigger statement. Replace the `configurationId` pair with a `repositoryName` pair. Save the file.

   For example, if you want to test a trigger named *MyFirstTrigger* in the repository named *MyDemoRepo* so that it applies to all branches, replace the `configurationId` with `repositoryName` and then save a file that looks similar to the following as *TestTrigger.json*:

   ```
   {
       "repositoryName": "MyDemoRepo", 
       "triggers": [
           {
               "destinationArn": "arn:aws:sns:us-east-2:111122223333:MyCodeCommitTopic", 
               "branches": [
                   "main", 
                   "preprod"
               ], 
               "name": "MyFirstTrigger", 
               "customData": "", 
               "events": [
                   "all"
               ]
           }  
       ]
   }
   ```

1. At the terminal or command line, run the **test-repository-triggers** command. This updates all triggers for the repository, including the changes you made to the *MyFirstTrigger* trigger:

   ```
   aws codecommit test-repository-triggers --cli-input-json file://TestTrigger.json
   ```

   This command returns a response similar to the following:

   ```
   {
       "successfulExecutions": [
           "MyFirstTrigger"
       ],
       "failedExecutions": []
   }
   ```

# Delete triggers from an AWS CodeCommit repository
<a name="how-to-notify-delete"></a>

You might want to delete triggers if they are no longer being used. You cannot undo the deletion of a trigger, but you can create one again.

**Note**  
If you configured one or more triggers for your repository, deleting the repository does not delete the Amazon SNS topics or Lambda functions you configured as the targets of those triggers. Be sure to delete those resources, too, if they are no longer needed.

**Topics**
+ [Delete a trigger from a repository (console)](#how-to-notify-delete-console)
+ [Delete a trigger from a repository (AWS CLI)](#how-to-notify-delete-cli)

## Delete a trigger from a repository (console)
<a name="how-to-notify-delete-console"></a>

1. Open the CodeCommit console at [https://console.aws.amazon.com/codesuite/codecommit/home](https://console.aws.amazon.com/codesuite/codecommit/home).

1. In **Repositories**, choose the repository where you want to delete triggers for repository events.

1. In the navigation pane for the repository, choose **Settings**. In **Settings**, choose **Triggers**.

1. Choose the trigger you want to delete from the list of triggers, and then choose **Delete**.

1. In the dialog box, type **delete** to confirm.

## Delete a trigger from a repository (AWS CLI)
<a name="how-to-notify-delete-cli"></a>

1. At a terminal (Linux, macOS, or Unix) or command prompt (Windows), run the **get-repository-triggers** command to create a JSON file with the structure of all of the triggers configured for your repository. For example, to create a JSON file named *MyTriggers.json* with the structure of all of the triggers configured for a repository named MyDemoRepo:

   ```
   aws codecommit get-repository-triggers --repository-name MyDemoRepo >MyTriggers.json
   ```

   This command creates a file named *MyTriggers.json* in the directory where you ran the command.

1. Edit the JSON file in a plain-text editor and remove the trigger block for the trigger you want to delete. Replace the `configurationId` pair with a `repositoryName` pair. Save the file.

   For example, if you want to remove a trigger named *MyFirstTrigger* from the repository named *MyDemoRepo*, you would replace `configurationId` with `repositoryName`, and remove the statement in *red italic text*:

   ```
   {
       "repositoryName": "MyDemoRepo", 
       "triggers": [
           {
               "destinationArn": "arn:aws:sns:us-east-2:111122223333:MyCodeCommitTopic", 
               "branches": [
                   "main", 
                   "preprod"
               ], 
               "name": "MyFirstTrigger", 
               "customData": "", 
               "events": [
                   "all"
               ]
           }, 
           {
               "destinationArn": "arn:aws:lambda:us-east-2:111122223333:function:MyCodeCommitJSFunction", 
               "branches": [], 
               "name": "MyLambdaTrigger", 
               "events": [
                   "all"
               ]
           }  
       ]
   }
   ```

1. At the terminal or command line, run the **put-repository-triggers** command. This updates the triggers for the repository and deletes the *MyFirstTrigger* trigger:

   ```
   aws codecommit put-repository-triggers --repository-name MyDemoRepo file://MyTriggers.json
   ```

   This command returns a configuration ID, similar to the following:

   ```
   {
       "configurationId": "0123456-I-AM-AN-EXAMPLE"
   }
   ```
**Note**  
To delete all triggers for a repository named *MyDemoRepo*, your JSON file would look similar to this:  

   ```
   {
       "repositoryName": "MyDemoRepo",
       "triggers": []
   }
   ```