

# Monitoring deployments in CodeDeploy
<a name="monitoring"></a>

Monitoring is an important part of maintaining the reliability, availability, and performance of CodeDeploy and your AWS solutions. You should collect monitoring data from all of the parts of your AWS solution so that you can more easily debug a multi-point failure if one occurs. Before you start monitoring CodeDeploy, however, you should create a monitoring plan that includes answers to the following questions:
+ What are your monitoring goals?
+ What resources will you monitor?
+ How often will you monitor these resources?
+ What monitoring tools will you use?
+ Who will perform the monitoring tasks?
+ Who should be notified when something goes wrong?

The next step is to establish a baseline for normal CodeDeploy performance in your environment, by measuring performance at various times and under different load conditions. As you monitor CodeDeploy, store historical monitoring data so that you can compare it with current performance data, identify normal performance patterns and performance anomalies, and devise methods to address issues.

For example, if you're using CodeDeploy, you can monitor the status of deployments and target instances. When deployments or instances fail, you might need to reconfigure an application specification file, reinstall or update the CodeDeploy agent, update settings in an application or deployment group, or make changes to instance settings or an AppSpec file.

To establish a baseline, you should, at a minimum, monitor the following items:
+ Deployment events and status
+ Instance events and status

## Automated monitoring tools
<a name="monitoring_automated_tools"></a>

AWS provides various tools that you can use to monitor CodeDeploy. You can configure some of these tools to do the monitoring for you, while some of the tools require manual intervention. We recommend that you automate monitoring tasks as much as possible.

You can use the following automated monitoring tools to watch CodeDeploy and report when something is wrong:
+ **Amazon CloudWatch Alarms** – Watch a single metric over a time period that you specify, and perform one or more actions based on the value of the metric relative to a given threshold over a number of time periods. The action is a notification sent to an Amazon Simple Notification Service (Amazon SNS) topic or Amazon EC2 Auto Scaling policy. CloudWatch alarms do not invoke actions simply because they are in a particular state; the state must have changed and been maintained for a specified number of periods. For more information, see [Monitoring deployments with Amazon CloudWatch tools](monitoring-cloudwatch.md).

  For information about updating your service role to work with CloudWatch alarm monitoring, see [Grant CloudWatch permissions to a CodeDeploy service role](monitoring-create-alarms-grant-permissions.md). For information about adding CloudWatch alarm monitoring to your CodeDeploy operations, see [Create an application with CodeDeploy](applications-create.md), [Create a deployment group with CodeDeploy](deployment-groups-create.md), or [Change deployment group settings with CodeDeploy](deployment-groups-edit.md).

  
+ **Amazon CloudWatch Logs** – Monitor, store, and access your log files from AWS CloudTrail or other sources. For more information, see [Monitoring Log Files](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/WhatIsCloudWatchLogs.html) in the *Amazon CloudWatch User Guide*.

  For information about using the CloudWatch console to view CodeDeploy logs, see [View CodeDeploy logs in CloudWatch Logs console](https://aws.amazon.com/blogs/devops/view-aws-codedeploy-logs-in-amazon-cloudwatch-console/).
+ **Amazon CloudWatch Events** – Match events and route them to one or more target functions or streams to make changes, capture state information, and take corrective action. For more information, see [What is Amazon CloudWatch Events](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/WhatIsCloudWatchEvents.html) in the *Amazon CloudWatch User Guide*.

  For information about using CloudWatch Events in your CodeDeploy operations, see [Monitoring deployments with Amazon CloudWatch Events](monitoring-cloudwatch-events.md).
+ **AWS CloudTrail Log Monitoring** – Share log files between accounts, monitor CloudTrail log files in real time by sending them to CloudWatch Logs, write log processing applications in Java, and validate that your log files have not changed after delivery by CloudTrail. For more information, see [Working with CloudTrail Log Files](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-working-with-log-files.html) in the *AWS CloudTrail User Guide*. 

  For information about using CloudTrail with CodeDeploy, see [Monitoring deployments with AWS CloudTrail](monitoring-cloudtrail.md).
+ **Amazon Simple Notification Service** — Configure event-driven triggers to receive SMS or email notifications about deployment and instance events, such as success or failure. For more information, see [Create a topic](https://docs.aws.amazon.com/sns/latest/dg/CreateTopic.html) and [What is Amazon Simple Notification Service](https://docs.aws.amazon.com/sns/latest/dg/welcome.html).

  For information about setting up Amazon SNS notifications for CodeDeploy, see [Monitoring deployments with Amazon SNS event notifications](monitoring-sns-event-notifications.md).

## Manual monitoring tools
<a name="monitoring_manual_tools"></a>

Another important part of monitoring CodeDeploy involves manually monitoring those items that the CloudWatch alarms don't cover. The CodeDeploy, CloudWatch, and other AWS console dashboards provide an at-a-glance view of the state of your AWS environment. We recommend that you also check the log files on CodeDeploy deployments.
+ CodeDeploy console shows:
  + The status of deployments
  + The date and time of each last attempted and last successful deployment of a revision
  + The number of instances that succeeded, failed, were skipped, or are in progress in a deployment
  + The status of on-premises instances
  + The date and time when on-premises instances were registered or deregistered
+ CloudWatch home page shows:
  + Current alarms and status
  + Graphs of alarms and resources
  + Service health status

  In addition, you can use CloudWatch to do the following: 
  + Create [customized dashboards](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CloudWatch_Dashboards.html) to monitor the services you care about
  + Graph metric data to troubleshoot issues and discover trends
  + Search and browse all your AWS resource metrics
  + Create and edit alarms to be notified of problems

**Topics**
+ [Monitoring Deployments with Amazon CloudWatch Tools](monitoring-cloudwatch.md)
+ [Monitoring Deployments](monitoring-cloudtrail.md)
+ [Monitoring Deployments with Amazon SNS Event Notifications](monitoring-sns-event-notifications.md)

# Monitoring deployments with Amazon CloudWatch tools
<a name="monitoring-cloudwatch"></a>

You can monitor CodeDeploy deployments using the following CloudWatch tools: Amazon CloudWatch Events, CloudWatch alarms, and Amazon CloudWatch Logs. 

Reviewing the logs created by the CodeDeploy agent and deployments can help you troubleshoot the causes of deployment failures. As an alternative to reviewing CodeDeploy logs on one instance at a time, you can use CloudWatch Logs to monitor all logs in a central location.

For information about using CloudWatch alarms and CloudWatch Events to monitor your CodeDeploy deployments, see the following topics. 

**Topics**
+ [Monitoring deployments with CloudWatch alarms in CodeDeploy](monitoring-create-alarms.md)
+ [Monitoring deployments with Amazon CloudWatch Events](monitoring-cloudwatch-events.md)

# Monitoring deployments with CloudWatch alarms in CodeDeploy
<a name="monitoring-create-alarms"></a>

You can create a CloudWatch alarm for an instance or Amazon EC2 Auto Scaling group you are using in your CodeDeploy operations. An alarm watches a single metric over a time period you specify and performs one or more actions based on the value of the metric relative to a given threshold over a number of time periods. CloudWatch alarms invoke actions when their state changes (for example, from `OK` to `ALARM`).

Using native CloudWatch alarm functionality, you can specify any of the actions supported by CloudWatch when an instance you are using in a deployment fails, such as sending an Amazon SNS notification or stopping, terminating, rebooting, or recovering an instance. For your CodeDeploy operations, you can configure a deployment group to stop a deployment whenever any CloudWatch alarm you associate with the deployment group is activated. 

You can associate up to ten CloudWatch alarms with a CodeDeploy deployment group. If any of the specified alarms are activated, the deployment stops, and the status is updated to Stopped. To use this option, you must grant CloudWatch permissions to your CodeDeploy service role.

For information about setting up CloudWatch alarms in the CloudWatch console, see [Creating Amazon CloudWatch alarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/AlarmThatSendsEmail.html) in the *Amazon CloudWatch User Guide*.

For information about associating a CloudWatch alarm with a deployment group in CodeDeploy, see [Create a deployment group with CodeDeploy](deployment-groups-create.md) and [Change deployment group settings with CodeDeploy](deployment-groups-edit.md).

**Topics**
+ [Grant CloudWatch permissions to a CodeDeploy service role](monitoring-create-alarms-grant-permissions.md)

# Grant CloudWatch permissions to a CodeDeploy service role
<a name="monitoring-create-alarms-grant-permissions"></a>

Before you can use CloudWatch alarm monitoring with your deployments, the service role you use in your CodeDeploy operations must be granted permission to access the CloudWatch resources. 

**To grant CloudWatch permissions to a service role**

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 IAM console, in the navigation pane, choose **Roles**.

1. Choose the name of the service role you use in your AWS CodeDeploy operations.

1. On the **Permissions** tab, in the **Inline Policies** area, choose **Create Role Policy**.

   –or–

   If the **Create Role Policy** button is not available, expand the **Inline Policies** area, and then choose **click here**.

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

1. On the **Review Policy** page, in the **Policy Name** field, type a name to identify this policy, such as `CWAlarms`.

1. Paste the following into the **Policy Document** field: 

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "cloudwatch:DescribeAlarms",
               "Resource": "*"
           }
       ]
   }
   ```

------

1. Choose **Apply Policy**.

# Monitoring deployments with Amazon CloudWatch Events
<a name="monitoring-cloudwatch-events"></a>

You can use Amazon CloudWatch Events to detect and react to changes in the state of an instance or a deployment (an "event") in your CodeDeploy operations. Then, based on rules you create, CloudWatch Events will invoke one or more target actions when a deployment or instance enters the state you specify in a rule. Depending on the type of state change, you might want to send notifications, capture state information, take corrective action, initiate events, or take other actions. You can select the following types of targets when using CloudWatch Events as part of your CodeDeploy operations:
+ AWS Lambda functions
+  Kinesis streams
+ Amazon SQS queues
+ Built-in targets (`EC2 CreateSnapshot API call`, `EC2 RebootInstances API call`, `EC2 StopInstances API call` , and `EC2 TerminateInstances API call`)
+ Amazon SNS topics

The following are some use cases:
+ Use a Lambda function to pass a notification to a Slack channel whenever deployments fail.
+ Push data about deployments or instances to a Kinesis stream to support comprehensive, real-time status monitoring.
+ Use CloudWatch alarm actions to automatically stop, terminate, reboot, or recover Amazon EC2 instances when a deployment or instance event you specify occurs.

The remainder of this topic describes the basic procedure for creating a CloudWatch Events rule for CodeDeploy. Before you create event rules for use in your CodeDeploy operations, however, you should do the following:
+ Complete the CloudWatch Events prerequisites. For information, see [Amazon CloudWatch Events Prerequisites](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CWE_Prerequisites.html).
+ Familiarize yourself with events, rules, and targets in CloudWatch Events. For more information, see [What is Amazon CloudWatch Events?](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) and [New CloudWatch Events – Track and respond to changes to your AWS resources](https://aws.amazon.com/blogs/aws/new-cloudwatch-events-track-and-respond-to-changes-to-your-aws-resources/).
+ Create the target or targets you will use in your event rules. 

**To create a CloudWatch Events rule for CodeDeploy:**

1. Open the CloudWatch console at [https://console.aws.amazon.com/cloudwatch/](https://console.aws.amazon.com/cloudwatch/).

1. In the navigation pane, choose **Events**.

1. Choose **Create rule**, and then under **Event selector**, choose **AWS CodeDeploy**.

1. Specify a detail type:
   + To make a rule that applies to all state changes of both instances and deployments, choose **Any detail type**, and then skip to step 6.
   + To make a rule that applies to instances only, choose **Specific detail type**, and then choose **CodeDeploy Instance State-change Notification**.
   + To make a rule that applies to deployments only, choose **Specific detail type**, and then choose **CodeDeploy Deployment State-change Notification**.

1. Specify the state changes the rule applies to:
   + To make a rule that applies to all state changes, choose **Any state**.
   + To make a rule that applies to some state changes only, choose **Specific state(s)**, and then choose one or more status values from the list. The following table lists the status values you can choose:  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codedeploy/latest/userguide/monitoring-cloudwatch-events.html)

1. Specify which CodeDeploy applications the rule applies to:
   + To make a rule that applies to all applications, choose **Any application**, and then skip to step 8.
   + To make a rule that applies to one application only, choose **Specific application**, and then choose the name of the application from the list.

1. Specify which deployment groups the rule applies to:
   + To make a rule that applies to all deployment groups associated with the selected application, choose **Any deployment group**.
   + To make a rule that applies to only one of the deployment groups associated with the selected application, choose **Specific deployment group(s)**, and then choose the name of the deployment group from the list.

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

1. In the **Targets** area, choose **Add target\$1**.

1. In the **Select target type** list, choose the type of target you have prepared to use with this rule, and then configure any additional options required by that type. 

1. Choose **Configure details**.

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

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

# Monitoring deployments with AWS CloudTrail
<a name="monitoring-cloudtrail"></a>

CodeDeploy is integrated with CloudTrail, a service that captures API calls made by or on behalf of CodeDeploy in your AWS account and delivers the log files to an Amazon S3 bucket you specify. CloudTrail captures API calls from the CodeDeploy console, from CodeDeploy commands through the AWS CLI, or from the CodeDeploy APIs directly. Using the information collected by CloudTrail, you can determine which request was made to CodeDeploy, the source IP address from which the request was made, who made the request, when it was made, and so on. To learn more about CloudTrail, including how to configure and enable it, see [AWS CloudTrail User Guide](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/).

## CodeDeploy information in CloudTrail
<a name="service-name-info-in-cloudtrail"></a>

When CloudTrail logging is enabled in your AWS account, API calls made to CodeDeploy actions are tracked in log files. CodeDeploy records are written together with other AWS service records in a log file. CloudTrail determines when to create and write to a new file based on a time period and file size.

All of the CodeDeploy actions are logged and documented in the [AWS CodeDeploy Command Line Reference](https://docs.aws.amazon.com/cli/latest/reference/deploy/index.html) and the [AWS CodeDeploy API Reference](https://docs.aws.amazon.com/codedeploy/latest/APIReference/). For example, calls to create deployments, delete applications, and register application revisions generate entries in CloudTrail log files. 

Every log entry contains information about who generated the request. The user identity information in the log helps you determine whether the request was made with root or user credentials, with temporary security credentials for a role or federated user, or by another AWS service. For more information, see the **userIdentity** field in the [CloudTrail event reference](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/event_reference_top_level.html).

You can store your log files in your bucket for as long as you want, but you can also define Amazon S3 lifecycle rules to archive or delete log files automatically. By default, Amazon S3 server-side encryption (SSE) is used to encrypt your log files.

You can have CloudTrail publish Amazon SNS notifications when new log files are delivered. For more information, see [Configuring Amazon SNS notifications for CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/getting_notifications_top_level.html).

You can also aggregate CodeDeploy log files from multiple AWS regions and multiple AWS accounts into a single Amazon S3 bucket. For more information, see [Receiving CloudTrail log files from multiple regions](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/aggregating_logs_top_level.html).

## Understanding CodeDeploy log file entries
<a name="understanding-service-name-entries"></a>

CloudTrail log files can contain one or more log entries where each entry is made up of multiple JSON-formatted events. A log entry represents a single request from any source and includes information about the requested action, any parameters, the date and time of the action, and so on. The log entries are not guaranteed to be in any particular order. That is, they are not an ordered stack trace of the public API calls.

The following example shows a CloudTrail log entry that demonstrates the CodeDeploy create deployment group action:

```
{
	"Records": [{
		"eventVersion": "1.02",
		"userIdentity": {
			"type": "AssumedRole",
			"principalId": "AKIAI44QH8DHBEXAMPLE:203.0.113.11",
			"arn": "arn:aws:sts::123456789012:assumed-role/example-role/203.0.113.11",
			"accountId": "123456789012",
			"accessKeyId": "AKIAIOSFODNN7EXAMPLE",
			"sessionContext": {
				"attributes": {
					"mfaAuthenticated": "false",
					"creationDate": "2014-11-27T03:57:36Z"
				},
				"sessionIssuer": {
					"type": "Role",
					"principalId": "AKIAI44QH8DHBEXAMPLE",
					"arn": "arn:aws:iam::123456789012:role/example-role",
					"accountId": "123456789012",
					"userName": "example-role"
				}
			}
		},
		"eventTime": "2014-11-27T03:57:36Z",
		"eventSource": "codedeploy.amazonaws.com",
		"eventName": "CreateDeploymentGroup",
		"awsRegion": "us-west-2",
		"sourceIPAddress": "203.0.113.11",
		"userAgent": "example-user-agent-string",
		"requestParameters": {
			"applicationName": "ExampleApplication",
			"serviceRoleArn": "arn:aws:iam::123456789012:role/example-instance-group-role",
			"deploymentGroupName": "ExampleDeploymentGroup",
			"ec2TagFilters": [{
                "value": "CodeDeployDemo",
				"type": "KEY_AND_VALUE",
				"key": "Name"
            }],
            "deploymentConfigName": "CodeDeployDefault.HalfAtATime"
		},
		"responseElements": {
			"deploymentGroupId": "7d64e680-e6f4-4c07-b10a-9e117EXAMPLE"
		},
		"requestID": "86168559-75e9-11e4-8cf8-75d18EXAMPLE",
		"eventID": "832b82d5-d474-44e8-a51d-093ccEXAMPLE",
		"eventType": "AwsApiCall",
		"recipientAccountId": "123456789012"
	},
    ... additional entries ...
    ]
}
```

# Monitoring deployments with Amazon SNS event notifications
<a name="monitoring-sns-event-notifications"></a>

You can add triggers to a CodeDeploy deployment group to receive notifications about events related to deployments or instances in that deployment group. These notifications are sent to recipients who are subscribed to an Amazon SNS topic you have made part of the trigger's action. 

You can receive notifications for CodeDeploy events in SMS messages or email messages. You can also use the JSON data that is created when a specified event occurs in other ways, such as sending messages to Amazon SQS queues or invoking a function in AWS Lambda. For a look at the structure of the JSON data provided for deployment and instance triggers, see [JSON data formats for CodeDeploy triggers](monitoring-sns-event-notifications-json-format.md).

You might choose to use triggers to receive notifications if:
+ You are a developer who needs to know when a deployment fails or stops so you can troubleshoot it.
+ You are a system administrator who needs to know how many instances fail in order to monitor the health of your Amazon EC2 fleet.
+ You are a manager who wants an at-a-glance count of deployment and instance events, which you can get through filtering rules that route different types of notifications into folders in your desktop email client. 

You can create up to 10 triggers for each CodeDeploy deployment group, for any of the following event types.


| Deployment events | Instance events | 
| --- | --- | 
|  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codedeploy/latest/userguide/monitoring-sns-event-notifications.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codedeploy/latest/userguide/monitoring-sns-event-notifications.html)  | 
| ¹Applies to blue/green deployments only. Indicates that the latest application revision has been installed on instances in a replacement environment and traffic from the original environment can now be rerouted behind a load balancer. For more information see [Working with deployments in CodeDeploy](deployments.md). | 

**Topics**
+ [Grant Amazon SNS permissions to a service role](monitoring-sns-event-notifications-permisssions.md)
+ [Create a trigger for a CodeDeploy event](monitoring-sns-event-notifications-create-trigger.md)
+ [Edit a trigger in a deployment group](monitoring-sns-event-notifications-edit-trigger.md)
+ [Delete a trigger from a deployment group](monitoring-sns-event-notifications-delete-trigger.md)
+ [JSON data formats for triggers](monitoring-sns-event-notifications-json-format.md)

# Grant Amazon SNS permissions to a CodeDeploy service role
<a name="monitoring-sns-event-notifications-permisssions"></a>

Before your triggers can generate notifications, the service role you use in your CodeDeploy operations must be granted permission to access the Amazon SNS resources. 

**To grant Amazon SNS permissions to a service role**

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 IAM console, in the navigation pane, choose **Roles**.

1. Choose the name of the service role you use in your AWS CodeDeploy operations.

1. On the **Permissions** tab, in the **Inline Policies** area, choose **Create Role Policy**.

   –or–

   If the **Create Role Policy** button is not available, expand the **Inline Policies** area, and then choose **click here**.

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

1. On the **Review Policy** page, in the **Policy Name** field, enter a name to identify this policy, such as `SNSPublish`.

1. Paste the following into the **Policy Document** field: 

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "sns:Publish",
               "Resource": "*"
           }
       ]
   }
   ```

------

1. Choose **Apply Policy**.

# Create a trigger for a CodeDeploy event
<a name="monitoring-sns-event-notifications-create-trigger"></a>

You can create a trigger that publishes an Amazon Simple Notification Service (Amazon SNS) topic for a AWS CodeDeploy deployment or instance event. Then, when that event occurs, all subscribers to the associated topic receive notifications through the endpoint specified in the topic, such as an SMS message or email message. Amazon SNS offers multiple methods for subscribing to topics.

Before you create a trigger, you must set up the Amazon SNS topic for the trigger to point to. For information, see [Create a topic](https://docs.aws.amazon.com/sns/latest/dg/CreateTopic.html). When you create a topic, we recommend you give it a name that identifies its purpose, in formats such as `Topic-group-us-west-3-deploy-fail` or `Topic-group-project-2-instance-stop`. 

You must also grant Amazon SNS permissions to a CodeDeploy service role before notifications can be sent for your trigger. For information, see [Grant Amazon SNS permissions to a CodeDeploy service role](monitoring-sns-event-notifications-permisssions.md).

After you have created the topic, you can add subscribers. For information about creating, managing, and subscribing to topics, see [What is Amazon Simple Notification Service](https://docs.aws.amazon.com/sns/latest/dg/welcome.html).



## Create a trigger to send notifications for CodeDeploy events (console)
<a name="monitoring-sns-event-notifications-create-trigger-console"></a>

You can use the CodeDeploy console to create triggers for a CodeDeploy event. At the end of the setup process, a test notification message is sent to ensure that both permissions and trigger details are set up correctly.

**To create a trigger for a CodeDeploy event**

1. In the AWS Management Console, open the AWS CodeDeploy console.

1. Sign in to the AWS Management Console and open the CodeDeploy console at [https://console.aws.amazon.com/codedeploy](https://console.aws.amazon.com/codedeploy).
**Note**  
Sign in with the same user that you set up in [Getting started with CodeDeploy](getting-started-codedeploy.md).

1. In the navigation pane, expand **Deploy**, then choose **Applications**.

1. On the **Applications** page, choose the name of the application associated with the deployment group where you want to add a trigger.

1. On the **Application details** page, choose the deployment group where you want to add a trigger.

1.  Choose **Edit**. 

1.  Expand **Advanced - optional**. 

1.  In the **Triggers** area, choose **Create trigger**. 

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

   1. In **Trigger name**, enter a name for the trigger that makes it easy to identify its purpose. We recommend formats such as `Trigger-group-us-west-3-deploy-fail` or `Trigger-group-eu-central-instance-stop`.

   1. In **Events**, choose the event type or types to trigger the Amazon SNS topic to send notifications. 

   1. In **Amazon SNS topics**, choose the name of topic you created for sending notifications for this trigger.

   1.  Choose **Create trigger**. CodeDeploy sends a test notification to confirm you have correctly configured access between CodeDeploy and the Amazon SNS topic. Depending on the endpoint type you selected for the topic, and if you are subscribed to the topic, you receive confirmation in an SMS message or email message. 

1.  Choose **Save changes**. 

## Create a trigger to send notifications for CodeDeploy events (CLI)
<a name="monitoring-sns-event-notifications-create-trigger-cli"></a>

You can use the CLI to include triggers when you create a deployment group, or you can add triggers to an existing deployment group.

### To create a trigger to send notifications for a new deployment group
<a name="monitoring-sns-event-notifications-create-trigger-cli-new"></a>

Create a JSON file to configure the deployment group, and then run the [create-deployment-group](https://docs.aws.amazon.com/cli/latest/reference/deploy/create-deployment-group.html) command using the `--cli-input-json` option. 

The simplest way to create the JSON file is to use the `--generate-cli-skeleton` option to get a copy of the JSON format, and then provide the required values in a plain-text editor.

1. Run the following command, and then copy the results into a plain-text editor.

   ```
   aws deploy create-deployment-group --generate-cli-skeleton
   ```

1. Add the name of an existing CodeDeploy application to the output:

   ```
   {
       "applicationName": "TestApp-us-east-2",
       "deploymentGroupName": "",
       "deploymentConfigName": "",
       "ec2TagFilters": [
           {
               "Key": "",
               "Value": "",
               "Type": ""
           }
       ],
       "onPremisesInstanceTagFilters": [
           {
               "Key": "",
               "Value": "",
               "Type": ""
           }
       ],
       "autoScalingGroups": [
           ""
       ],
       "serviceRoleArn": "",
       "triggerConfigurations": [
           {
               "triggerName": "",
               "triggerTargetArn": "",
               "triggerEvents": [
                   ""
               ]
           }
       ]
   }
   ```

1. Provide values for the parameters you want to configure.

   When you use the [create-deployment-group](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_CreateDeploymentGroup.html) command, you must provide, at a minimum, values for the following parameters:
   + `applicationName`: The name of an application already created in your account. 
   + `deploymentGroupName`: A name for the deployment group you are creating.
   + `serviceRoleArn`: The ARN of an existing service role set up for CodeDeploy in your account. For information, see [Step 2: Create a service role for CodeDeploy](getting-started-create-service-role.md).

   In the `triggerConfigurations` section, provide values for the following parameters: 
   + `triggerName`: The name you want to give the trigger so you can easily identify it. We recommend formats such as `Trigger-group-us-west-3-deploy-fail` or `Trigger-group-eu-central-instance-stop`.
   + `triggerTargetArn`: The ARN of the Amazon SNS topic you created to associate with your trigger, in this format: `arn:aws:sns:us-east-2:444455556666:NewTestTopic`.
   + `triggerEvents`: The type of event or events for which you want to trigger notifications. You can specify one or more event types, separating multiple event type names with commas (for example, `"triggerEvents":["DeploymentSuccess","DeploymentFailure","InstanceFailure"]`). When you add more than one event type, notifications for all those types are sent to the topic you specified, rather than to a different topic for each one. You can choose from the following event types:
     + DeploymentStart
     + DeploymentSuccess
     + DeploymentFailure
     + DeploymentStop
     + DeploymentRollback
     + DeploymentReady (Applies only to replacement instances in a blue/green deployment)
     + InstanceStart
     + InstanceSuccess
     + InstanceFailure
     + InstanceReady (Applies only to replacement instances in a blue/green deployment)

   The following configuration example creates a deployment group named `dep-group-ghi-789-2` for an application named `TestApp-us-east-2` and a trigger that prompts the sending of notifications whenever a deployment starts, succeeds, or fails:

   ```
   {
       "applicationName": "TestApp-us-east-2",
       "deploymentConfigName": "CodeDeployDefault.OneAtATime",
       "deploymentGroupName": "dep-group-ghi-789-2",
       "ec2TagFilters": [
           {
               "Key": "Name",
               "Value": "Project-ABC",
               "Type": "KEY_AND_VALUE"
           }
       ],
       "serviceRoleArn": "arn:aws:iam::444455556666:role/AnyCompany-service-role",
       "triggerConfigurations": [
           {
               "triggerName": "Trigger-group-us-east-2",
               "triggerTargetArn": "arn:aws:sns:us-east-2:444455556666:us-east-deployments",
               "triggerEvents": [
                   "DeploymentStart",
                   "DeploymentSuccess",
                   "DeploymentFailure"
               ]
           }
       ]
   }
   ```

1. Save your updates as a JSON file, and then call that file using the `--cli-input-json` option when you run the **create-deployment-group** command:
**Important**  
Be sure to include `file://` before the file name. It is required in this command.

   ```
   aws deploy create-deployment-group --cli-input-json file://filename.json
   ```

   At the end of the creation process, you receive a test notification message that indicates both permissions and trigger details are set up correctly.

### To create a trigger to send notifications for an existing deployment group
<a name="monitoring-sns-event-notifications-create-trigger-cli-existing"></a>

To use the AWS CLI to add triggers for CodeDeploy events to an existing deployment group, create a JSON file to update the deployment group, and then run the [update-deployment-group](https://docs.aws.amazon.com/cli/latest/reference/deploy/create-deployment-group.html) command using the `--cli-input-json` option. 

The simplest way to create the JSON file is to run the **get-deployment-group** command to get a copy of the deployment group's configuration, in JSON format, and then update the parameter values in a plain-text editor.

1.  Run the following command, and then copy the results into a plain-text editor.

   ```
   aws deploy get-deployment-group --application-name application --deployment-group-name deployment-group
   ```

1. Delete the following from the output:
   + At the beginning of the output, delete `{ "deploymentGroupInfo":`.
   + At the end of the output, delete `}`. 
   + Delete the row containing `deploymentGroupId`.
   + Delete the row containing `deploymentGroupName`.

   The contents of your text file should now look similar to the following:

   ```
   {
       "applicationName": "TestApp-us-east-2",
       "deploymentConfigName": "CodeDeployDefault.OneAtATime",
       "autoScalingGroups": [],
       "ec2TagFilters": [
           {
               "Type": "KEY_AND_VALUE",
               "Value": "Project-ABC",
               "Key": "Name"
           }
       ],
       "triggerConfigurations": [],
       "serviceRoleArn": "arn:aws:iam::444455556666:role/AnyCompany-service-role",
       "onPremisesInstanceTagFilters": []
   }
   ```

1. In the `triggerConfigurations` section, add data for the `triggerEvents`, `triggerTargetArn`, and `triggerName` parameters. For information about trigger configuration parameters, see [TriggerConfig](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_TriggerConfig.html).

   The contents of your text file should now look similar to the following. This code prompts notifications to be sent whenever a deployment starts, succeeds, or fails. 

   ```
   {
       "applicationName": "TestApp-us-east-2",
       "deploymentConfigName": "CodeDeployDefault.OneAtATime",
       "autoScalingGroups": [],
       "ec2TagFilters": [
           {
               "Type": "KEY_AND_VALUE",
               "Value": "Project-ABC",
               "Key": "Name"
           }
       ],
       "triggerConfigurations": [
           {
               "triggerEvents": [
                   "DeploymentStart",
                   "DeploymentSuccess",
                   "DeploymentFailure"
               ],
               "triggerTargetArn": "arn:aws:sns:us-east-2:444455556666:us-east-deployments",
               "triggerName": "Trigger-group-us-east-2"
           }
       ],
       "serviceRoleArn": "arn:aws:iam::444455556666:role/AnyCompany-service-role",
       "onPremisesInstanceTagFilters": []
   }
   ```

1. Save your updates as a JSON file, and then run the [update-deployment-group](https://docs.aws.amazon.com/cli/latest/reference/deploy/create-deployment-group.html) command using the `--cli-input-json` option. Be sure to include the `--current-deployment-group-name` option and substitute the name of your JSON file for *filename*: 
**Important**  
Be sure to include `file://` before the file name. It is required in this command.

   ```
   aws deploy update-deployment-group --current-deployment-group-name deployment-group-name --cli-input-json file://filename.json
   ```

   At the end of the creation process, you receive a test notification message that indicates both permissions and trigger details are set up correctly.

# Edit a trigger in a CodeDeploy deployment group
<a name="monitoring-sns-event-notifications-edit-trigger"></a>

If your notification requirements change, you can modify your trigger rather than create a new one.

## Modify a CodeDeploy trigger (CLI)
<a name="monitoring-sns-event-notifications-edit-trigger-cli"></a>

 To use the AWS CLI to change trigger details for CodeDeploy events when you update a deployment group, create a JSON file to define changes to the deployment group's properties, and then run the [update-deployment-group](https://docs.aws.amazon.com/cli/latest/reference/deploy/update-deployment-group.html) command with the `--cli-input-json` option. 

The simplest way to create the JSON file is to run the **get-deployment-group** command to get the current deployment group details in JSON format, and then edit the required values in a plain-text editor.

1. Run the following command, substituting the names of your application and deployment group for *application* and *deployment-group*:

   ```
   aws deploy get-deployment-group --application-name application --deployment-group-name deployment-group
   ```

1. Copy the results of the command into a plain-text editor and then delete the following:
   + At the beginning of the output, delete `{ "deploymentGroupInfo":`. 
   + At the end of the output, delete `}`. 
   + Delete the row containing `deploymentGroupId`.
   + Delete the row containing `deploymentGroupName`.

   The contents of your text file should now look similar to the following:

   ```
   {
       "applicationName": "TestApp-us-east-2",
       "deploymentConfigName": "CodeDeployDefault.OneAtATime",
       "autoScalingGroups": [],
       "ec2TagFilters": [
           {
               "Type": "KEY_AND_VALUE",
               "Value": "East-1-Instances",
               "Key": "Name"
           }
       ],
       "triggerConfigurations": [
           {
               "triggerEvents": [
                   "DeploymentStart",
                   "DeploymentSuccess",
                   "DeploymentFailure",
                   "DeploymentStop"
               ],
               "triggerTargetArn": "arn:aws:sns:us-east-2:111222333444:Trigger-group-us-east-2",
               "triggerName": "Trigger-group-us-east-2"
           }
       ],
       "serviceRoleArn": "arn:aws:iam::444455556666:role/AnyCompany-service-role",
       "onPremisesInstanceTagFilters": []
   }
   ```

1. Change any parameters, as necessary. For information about trigger configuration parameters, see [TriggerConfig](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_TriggerConfig.html).

1. Save your updates as a JSON file, and then run the [update-deployment-group](https://docs.aws.amazon.com/cli/latest/reference/deploy/update-deployment-group.html) command using the `--cli-input-json` option. Be sure to include the `--current-deployment-group-name` option and substitute the name of your JSON file for *filename*: 
**Important**  
Be sure to include `file://` before the file name. It is required in this command.

   ```
   aws deploy update-deployment-group --current-deployment-group-name deployment-group-name --cli-input-json file://filename.json
   ```

At the end of the creation process, you receive a test notification message that indicates both permissions and trigger details are set up correctly.

# Delete a trigger from a CodeDeploy deployment group
<a name="monitoring-sns-event-notifications-delete-trigger"></a>

Because there is a limit of 10 triggers per deployment group, you might want to delete triggers if they are no longer being used. You cannot undo the deletion of a trigger, but you can re-create one.

## Delete a trigger from a deployment group (console)
<a name="monitoring-sns-event-notifications-delete-trigger-console"></a>

1. Sign in to the AWS Management Console and open the CodeDeploy console at [https://console.aws.amazon.com/codedeploy](https://console.aws.amazon.com/codedeploy).
**Note**  
Sign in with the same user that you set up in [Getting started with CodeDeploy](getting-started-codedeploy.md).

1. In the navigation pane, expand **Deploy**, then choose **Applications**.

1. On the **Applications** page, choose the name of the application associated with the deployment group where you want to delete a trigger.

1. On the **Application details** page, choose the deployment group where you want to delete a trigger.

1.  Choose **Edit**. 

1.  Expand **Advanced - optional**. 

1. In the **Triggers** area, choose the trigger you want to delete, then choose **Delete trigger**. 

1.  Choose **Save changes**. 

## Delete a trigger from a deployment group (CLI)
<a name="monitoring-sns-event-notifications-delete-trigger-cli"></a>

To use the CLI to delete a trigger, call the [update-deployment-group](https://docs.aws.amazon.com/cli/latest/reference/deploy/update-deployment-group.html) command, with empty trigger configuration parameters, specifying:
+ The name of the application associated with the deployment group. To view a list of application names, call the [list-applications](https://docs.aws.amazon.com/cli/latest/reference/deploy/list-applications.html) command.
+ The name of the deployment group associated with the application. To view a list of deployment group names, call the [list-deployment-groups](https://docs.aws.amazon.com/cli/latest/reference/deploy/list-deployment-groups.html) command.

For example:

```
aws deploy update-deployment-group --application-name application-name --current-deployment-group-name deployment-group-name --trigger-configurations
```

# JSON data formats for CodeDeploy triggers
<a name="monitoring-sns-event-notifications-json-format"></a>

You can use the JSON output that is created when a trigger for a deployment or instance is activated in a custom notification workflow, such as sending messages to Amazon SQS queues or invoking a function in AWS Lambda. 

**Note**  
This guide does not address how to configure notifications using JSON. For information about using Amazon SNS to send messages to Amazon SQS queues, see [Sending Amazon SNS messages to Amazon SQS queues](https://docs.aws.amazon.com/sns/latest/dg/SendMessageToSQS.html). For information about using Amazon SNS to invoke a Lambda function, see [Invoking Lambda functions using Amazon SNS notifications](https://docs.aws.amazon.com/sns/latest/dg/sns-lambda.html).

The following examples show the structure of the JSON output available with CodeDeploy triggers.

**Sample JSON Output for Instance-Based Triggers**

```
{
    "region": "us-east-2",
    "accountId": "111222333444",
    "eventTriggerName": "trigger-group-us-east-instance-succeeded",
    "deploymentId": "d-75I7MBT7C",
    "instanceId": "arn:aws:ec2:us-east-2:444455556666:instance/i-496589f7",
    "lastUpdatedAt": "1446744207.564",
    "instanceStatus": "Succeeded",
    "lifecycleEvents": [
        {
            "LifecycleEvent": "ApplicationStop",
            "LifecycleEventStatus": "Succeeded",
            "StartTime": "1446744188.595",
            "EndTime": "1446744188.711"
        },
        {
            "LifecycleEvent": "BeforeInstall",
            "LifecycleEventStatus": "Succeeded",
            "StartTime": "1446744189.827",
            "EndTime": "1446744190.402"
        }
//More lifecycle events might be listed here
    ]
}
```

**Sample JSON Output for Deployment-Based Triggers**

```
{
    "region": "us-west-1",
    "accountId": "111222333444",
    "eventTriggerName": "Trigger-group-us-west-3-deploy-failed",
    "applicationName": "ProductionApp-us-west-3",
    "deploymentId": "d-75I7MBT7C",
    "deploymentGroupName": "dep-group-def-456",
    "createTime": "1446744188.595",
    "completeTime": "1446744190.402",
    "deploymentOverview": {
        "Failed": "10",
        "InProgress": "0",
        "Pending": "0",
        "Skipped": "0",
        "Succeeded": "0"
    },
    "status": "Failed",
    "errorInformation": {
        "ErrorCode": "IAM_ROLE_MISSING",
        "ErrorMessage": "IAM Role is missing for deployment group: dep-group-def-456"
    }
}
```