Amazon CloudWatch Events User Guide Cloud Watch
User Manual:
Open the PDF directly: View PDF .
Page Count: 80
Download | |
Open PDF In Browser | View PDF |
Amazon CloudWatch Events User Guide Amazon CloudWatch Events User Guide Amazon CloudWatch Events User Guide Amazon CloudWatch Events: User Guide Copyright © 2016 Amazon Web Services, Inc. and/or its affiliates. All rights reserved. Amazon's trademarks and trade dress may not be used in connection with any product or service that is not Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may or may not be affiliated with, connected to, or sponsored by Amazon. Amazon CloudWatch Events User Guide Table of Contents What is Amazon CloudWatch Events? ............................................................................................. 1 Components ......................................................................................................................... 1 Prerequisites ........................................................................................................................ 2 Regions and Endpoints .......................................................................................................... 2 Limits .................................................................................................................................. 2 Related AWS Services .......................................................................................................... 3 Resources ........................................................................................................................... 4 Getting Set Up ............................................................................................................................. 5 Sign Up for Amazon Web Services (AWS) ................................................................................ 5 Sign in to the Amazon CloudWatch Console ............................................................................. 5 Set Up the Command Line Interface ........................................................................................ 6 Getting Started ............................................................................................................................. 7 Scenario 1: Log the State of an Amazon EC2 Instance ............................................................... 7 Step 1: Create an AWS Lambda function ......................................................................... 7 Step 2: Create an Amazon CloudWatch Events Rule .......................................................... 8 Step 3: Test Your Amazon CloudWatch Events Rule .......................................................... 9 Scenario 2: Take Scheduled EBS Snapshots ............................................................................ 9 Step 1: Create an Amazon CloudWatch Events Rule .......................................................... 9 Step 2: Test Your Amazon CloudWatch Events Rule ........................................................ 10 Scenario 3: Log an AWS API Call ......................................................................................... 10 Step 1: Create an AWS Lambda function ........................................................................ 10 Step 2: Create an Amazon CloudWatch Events Rule ........................................................ 11 Step 3: Test Your Amazon CloudWatch Events Rule by Stopping an Instance ....................... 11 Scenario 4: Log the State of an Auto Scaling Group ................................................................. 12 Step 1: Create an AWS Lambda function ........................................................................ 12 Step 2: Create an Amazon CloudWatch Events Rule ........................................................ 12 Step 3: Test Your Amazon CloudWatch Events Rule with an Auto Scaling Group ................... 13 Scenario 5: Relay Events to an Amazon Kinesis Stream ........................................................... 13 Step 1: Create an Amazon Kinesis Stream ..................................................................... 14 Step 2: Create an Amazon CloudWatch Events Rule ........................................................ 14 Step 3: Test Your Amazon CloudWatch Events Rule by Stopping an Instance ....................... 15 Step 4: Get the Record to Verify that the Event is Relayed ................................................ 15 Scenario 6: Run an AWS Lambda Function on a Schedule ........................................................ 16 Step 1: Create an AWS Lambda function ........................................................................ 17 Step 2: Create an Amazon CloudWatch Events Rule ........................................................ 17 Step 3: Verify Your Amazon CloudWatch Events Rule ...................................................... 18 Schedule Expression Syntax for Rules ........................................................................................... 19 Cron Expressions ................................................................................................................ 19 Rate Expressions ................................................................................................................ 21 Events and Event Patterns ........................................................................................................... 22 Event Patterns .................................................................................................................... 23 Adding Events with PutEvents ....................................................................................................... 25 Handling Failures When Using PutEvents ............................................................................... 25 Sending Events Using the AWS CLI ...................................................................................... 27 Calculating PutEvents Event Entry Sizes ................................................................................ 27 Event Types ............................................................................................................................... 29 Amazon EC2 Events ........................................................................................................... 29 Amazon EC2 Simple Systems Manager Events ....................................................................... 30 Auto Scaling Events ............................................................................................................ 30 AWS API Call Events .......................................................................................................... 34 AWS CodeDeploy Events ..................................................................................................... 36 AWS Console Sign-in Events ................................................................................................ 37 Scheduled Events ............................................................................................................... 38 Authentication and Access Control ................................................................................................. 39 Authentication ..................................................................................................................... 39 iv Amazon CloudWatch Events User Guide Access Control ................................................................................................................... 40 Overview of Managing Access .............................................................................................. 41 Resources and Operations ........................................................................................... 41 Understanding Resource Ownership .............................................................................. 42 Managing Access to Resources .................................................................................... 42 Specifying Policy Elements: Actions, Effects, and Principals ............................................... 44 Specifying Conditions in a Policy ................................................................................... 44 Using Identity-Based Policies (IAM Policies) ............................................................................ 44 Permissions Required to Use the CloudWatch Console ..................................................... 45 AWS Managed (Predefined) Policies for CloudWatch Events .............................................. 46 Customer Managed Policy Examples ............................................................................. 47 Using Resource-Based Policies ............................................................................................. 50 AWS Lambda Permissions ........................................................................................... 50 Amazon SNS Permissions ............................................................................................ 51 Amazon SQS Permissions ............................................................................................ 52 CloudWatch Events Permissions Reference ............................................................................ 53 Using Conditions ................................................................................................................. 55 Example 1: Limit Access to a Specific Source ................................................................. 57 Example 2: Define Multiple Sources That Can Be Used in an Event Pattern Individually .......... 58 Example 3: Define a Source and a DetailType That Can Be Used in an Event Pattern ............. 59 Example 4: Ensure That the Source is Defined in the Event Pattern .................................... 60 Example 5: Define a List of Allowed Sources in an Event Pattern With Multiple Sources .......... 61 Example 6: Ensure That AWS CloudTrail Events for API Calls From a Certain PrincipalId Are Consumed .................................................................................................................. 62 Logging API Calls ....................................................................................................................... 64 CloudWatch Events Information in CloudTrail .......................................................................... 64 Understanding Log File Entries ............................................................................................. 65 Troubleshooting .......................................................................................................................... 67 My rule was triggered but my Lambda function was not invoked ................................................. 67 I have just created/modified a rule but it did not match a test event ............................................. 68 My rule did not self-trigger at the time specified in the ScheduleExpression ................................... 69 My rule did not trigger at the time that I expected .................................................................... 69 My rule matches IAM API calls but my rule was not triggered ..................................................... 69 My rule is not working because the IAM role associated with the rule is ignored when the rule is triggered ............................................................................................................................ 70 I created a rule with an EventPattern that is supposed to match a resource, but I don't see any events that match the rule .................................................................................................... 70 My event's delivery to the target experienced a delay ............................................................... 70 My rule was triggered more than once in response two identical events. What guarantee does CloudWatch Events offer for triggering rules or delivering events to the targets? ............................ 70 My rule is being triggered but I don't see any messages published into my Amazon SNS topic .......... 71 My Amazon SNS topic still has permissions for CloudWatch Events even after I deleted the rule associated with the Amazon SNS topic .................................................................................. 72 Which IAM condition keys can I use with CloudWatch Events .................................................... 72 How can I tell when CloudWatch Events rules are broken ......................................................... 72 Document History ........................................................................................................................ 74 AWS Glossary ............................................................................................................................ 75 v Amazon CloudWatch Events User Guide Components What is Amazon CloudWatch Events? Amazon CloudWatch Events delivers a near real-time stream of system events that describe changes in Amazon Web Services (AWS) resources to AWS Lambda functions, Amazon SNS topics, Amazon SQS queues, streams in Amazon Kinesis Streams, or built-in targets. Using simple rules that you can quickly set up, you can match events and route them to one or more target functions or streams. CloudWatch Events becomes aware of operational changes as they occur. CloudWatch Events responds to these operational changes and takes corrective action as necessary, by sending messages to respond to the environment, activating functions, making changes, and capturing state information. CloudWatch Events Components The three main components of CloudWatch Events are events, rules, and targets: • Events—are generated in four ways. First, they are emitted by AWS when resources change state. For example, an event is generated when the state of an Amazon EC2 instance changes from pending to running or when Auto Scaling launches or terminates instances in your Auto Scaling group. Second, events are emitted by AWS CloudTrail when you make a read/write API call, or sign in to the AWS Management Console. Third, your own code can generate application-level events and publish them to CloudWatch Events for processing. Fourth, they can be issued on a scheduled basis, with options for periodic or cron-style scheduling. • Rules—match incoming events and route them to one or more targets for processing. Rules are not processed in any particular order. This allows different parts of a single organization to independently look for and process events that are of interest. • Targets—are specified in rules and receive matching events. Targets include AWS Lambda functions, Amazon SNS topics, Amazon SQS queues, streams in Amazon Kinesis Streams, or builtin targets (CloudWatch alarm actions). A single rule can specify multiple targets, all of which are processed in parallel. Each event is passed to each target in JSON form. A rule can customize the JSON that flows to the target, by passing only certain part of an event to the target, or overwriting the matched event with a constant. Some target types might not be available in every region. For more information about the endpoints that represent each region, see Regions and Endpoints in the Amazon Web Services General Reference. Topics • Amazon CloudWatch Events Prerequisites (p. 2) • Regions and Endpoints (p. 2) 1 Amazon CloudWatch Events User Guide Prerequisites • CloudWatch Events Limits (p. 2) • Related AWS Services (p. 3) • Amazon CloudWatch Events Resources (p. 4) Amazon CloudWatch Events Prerequisites Amazon CloudWatch Events has the following prerequisites: • User accounts—Although you can use your root account, we recommend that you use an AWS Identity and Access Management (IAM) account. If you're using an IAM account, you must have "events:*" and "iam:PassRole" permissions: { "Version": "2012-10-17", "Statement": [ { "Action": [ "events:*", "iam:PassRole" ], "Effect": "Allow", "Resource": "*" } ] } • AWS CloudTrail logging—If you want to log AWS API calls in CloudWatch Events, you must turn on AWS CloudTrail. For more information, see Turning on CloudTrail in Additional Accounts in the AWS CloudTrail User Guide. • AWS Security Token Service (AWS STS)—Regional endpoints must be enabled (the default) in order to use Amazon CloudWatch Events. For more information, see Activating and Deactivating AWS STS in an AWS Region in the IAM User Guide. Regions and Endpoints You create rules and targets in a specific AWS region. You send your CloudWatch Events requests to a region-specific endpoint. For a list of supported AWS regions, see Regions and Endpoints in the Amazon Web Services General Reference. CloudWatch Events Limits CloudWatch Events has the following limits: Resource Default Limit API requests Up to 5 requests per second for all CloudWatch Events API operations except PutEvents. PutEvents is limited to 10 requests per second. Event pattern 2048 characters maximum. Invocations 20/second (after 20 invocations, the invocations are throttled; that is, they still happen but they are delayed). 2 Amazon CloudWatch Events User Guide Related AWS Services Resource Default Limit If the invocation of a target fails due to a problem with the target service, account throttling, etc., new attempts are made for up to 24 hours for a specific invocation. ListRuleNamesByTarget Up to 100 results per page for requests. ListRules Up to 100 results per page for requests. ListTargetsByRule Up to 100 results/page for requests. PutEvents 10 entries/request and 10 requests/second. Each request can be up to 256 KB in size. PutTargets 10 entries/request. RemoveTargets 10 entries/request. Rules 50/account. You can request a limit increase. For instructions, see AWS Service Limits. Before requesting a limit increase, examine your rules. You may have multiple rules each matching to very specific events. Consider broadening their scope by using fewer identifiers in your Events and Event Patterns (p. 22). In addition, a rule can invoke several targets each time it matches an event. Consider adding more targets to your rules. Targets 5/rule. Related AWS Services The following services are used in conjunction with CloudWatch Events: • AWS CloudTrail is a web service that enables you to monitor the calls made to the CloudWatch Events API for your account, including calls made by the AWS Management Console, command line interface (CLI), and other services. When CloudTrail logging is turned on, CloudWatch Events will write log files into the Amazon S3 bucket that you specified when you configured CloudTrail. Each log file can contain one or more records, depending on how many actions must be performed to satisfy a request. For more information about AWS CloudTrail, see What is AWS CloudTrail? in the AWS CloudTrail User Guide. For an example of the type of data that CloudWatch writes into CloudTrail log files, see Logging Amazon CloudWatch Events API Calls in AWS CloudTrail (p. 64). • AWS Identity and Access Management (IAM) is a web service that helps you securely control access to AWS resources for your users. Use IAM to control who can use your AWS resources (authentication) and what resources they can use in which ways (authorization). For more information, see What is IAM? in the IAM User Guide. • Amazon Kinesis Streams is a web service you can use for rapid and continuous data intake and aggregation. The type of data used includes IT infrastructure log data, application logs, social media, market data feeds, and web clickstream data. Because the response time for the data intake and processing is in real time, processing is typically lightweight. For more information, see What is Amazon Kinesis Streams? in the Amazon Kinesis Streams Developer Guide. • AWS Lambda is a web service you can use to build applications that respond quickly to new information. Upload your application code as Lambda functions and Lambda runs your code on highavailability compute infrastructure and performs all the administration of the compute resources, 3 Amazon CloudWatch Events User Guide Resources including server and operating system maintenance, capacity provisioning and automatic scaling, code and security patch deployment, and code monitoring and logging. All you need to do is supply your code in one of the languages that Lambda supports. For more information, see What is AWS Lambda? in the AWS Lambda Developer Guide. Amazon CloudWatch Events Resources The following table lists related resources that you'll find useful as you work with Amazon CloudWatch. Resource Description Amazon CloudWatch FAQs The FAQ covers the top questions developers have asked about this product. Release notes The release notes give a high-level overview of the current release. They specifically note any new features, corrections, and known issues. AWS Developer Resource Center A central starting point to find documentation, code samples, release notes, and other information to help you build innovative applications with AWS. AWS Management Console The console allows you to perform most of the functions of Amazon CloudWatch Events and various other AWS products without programming. Amazon CloudWatch Discussion Forums Community-based forum for developers to discuss technical questions related to Amazon CloudWatch Events. AWS Support The hub for creating and managing your AWS Support cases. Also includes links to other helpful resources, such as forums, technical FAQs, service health status, and AWS Trusted Advisor. Amazon CloudWatch product information The primary web page for information about Amazon CloudWatch Events. Contact Us A central contact point for inquiries concerning AWS billing, account, events, abuse, etc. 4 Amazon CloudWatch Events User Guide Sign Up for Amazon Web Services (AWS) Getting Set Up To use Amazon CloudWatch Events you need an AWS account. Your AWS account allows you to use services (e.g., Amazon EC2) to generate events that you can view in the CloudWatch console, a pointand-click web-based interface. In addition, you need to install and configure the AWS command line interface (CLI). Topics • Sign Up for Amazon Web Services (AWS) (p. 5) • Sign in to the Amazon CloudWatch Console (p. 5) • Set Up the Command Line Interface (p. 6) Sign Up for Amazon Web Services (AWS) When you create an AWS account, we automatically sign up your account for all AWS services. You pay only for the services that you use. If you have an AWS account already, skip to the next step. If you don't have an AWS account, use the following procedure to create one. To sign up for an AWS account 1. Open http://aws.amazon.com/, and then choose Create an AWS Account. 2. Follow the online instructions. Part of the sign-up procedure involves receiving a phone call and entering a PIN using the phone keypad. Sign in to the Amazon CloudWatch Console To sign in to the Amazon CloudWatch console 1. Sign in to the AWS Management Console and open the CloudWatch console at https:// console.aws.amazon.com/cloudwatch/. 5 Amazon CloudWatch Events User Guide Set Up the Command Line Interface 2. If necessary, change the region. From the navigation bar, select the region that meets your needs. For more information, see Regions and Endpoints in the Amazon Web Services General Reference. 3. In the navigation pane, choose Events. Set Up the Command Line Interface You can use the AWS CLI with CloudWatch Events. The AWS CLI, which is a unified tool for managing multiple AWS services. Before you can use the CLI, however, you have to install and configure it. For information about how to install and configure the AWS CLI, see Getting Set Up with the AWS Command Line Interface in the AWS Command Line Interface User Guide. 6 Amazon CloudWatch Events User Guide Scenario 1: Log the State of an Amazon EC2 Instance Getting Started with Amazon CloudWatch Events You can set up simple rules that match events and route them to one or more AWS Lambda functions, Amazon SNS topics, Amazon SQS queues, streams in Amazon Kinesis Streams, or built-in targets. This section walks you through scenarios that can get you started using CloudWatch Events. Note Some target types might not be available in every region. For more information about the endpoints that represent each region, see Regions and Endpoints in the Amazon Web Services General Reference. Topics • Scenario 1: Log the State of an Amazon EC2 Instance (p. 7) • Scenario 2: Take Scheduled EBS Snapshots (p. 9) • Scenario 3: Log an AWS API Call (p. 10) • Scenario 4: Log the State of an Auto Scaling Group (p. 12) • Scenario 5: Relay Events to an Amazon Kinesis Stream (p. 13) • Scenario 6: Run an AWS Lambda Function on a Schedule Using the AWS CLI (p. 16) Scenario 1: Log the State of an Amazon EC2 Instance You can use a simple AWS Lambda function that logs the changes in state of an Amazon EC2 instance. You can choose to create a rule that runs whenever there is a state transition, or on a transition to one or more states that are of interest. In this scenario, you log the launch of any new Amazon EC2 instance. Step 1: Create an AWS Lambda function To create an AWS Lambda function 1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/. 7 Amazon CloudWatch Events User Guide Step 2: Create an Amazon CloudWatch Events Rule 2. Choose Create a Lambda function, and then on the Select blueprint screen, choose helloworld. 3. On the Configure function screen, in the Name field, enter SomethingHappened. 4. In the Lambda function code section, edit the sample code to match the following example: console.log('Loading function'); exports.handler = function(event, context, callback) { console.log('SomethingHappened()'); console.log('Here is the event:', JSON.stringify(event, null, 2)); callback(null, "Ready"); }; 5. Under Lambda function handler and role, in the Role field, if you have a lambda_basic_execution_rule, select it. Otherwise, create a new basic execution role. 6. Choose Next, and then on the Review screen, choose Edit to make any changes. If you're satisfied with the function, choose Create function. Step 2: Create an Amazon CloudWatch Events Rule To create a CloudWatch Events rule 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Events. 3. Choose Create rule, and then under Event selector, choose EC2 instance state-change notification. 4. Choose Specific state(s), and then Running from the list. 5. Do one of the following: • To make the rule respond to any of your instances in the region, choose Any instance. • To make the rule respond to a specific instance, choose Specific instance(s) and then in the text box, enter the instance ID. 6. Under Targets, choose Add target. In the Select target type list, choose AWS Lambda function. 7. In the Function list, select the SomethingHappened function that you created in "Step 1: Create an AWS Lambda Function." 8. Choose Configure input, and then choose one of the following options: • Matched event—Sends all of the data fields in the event to CloudWatch Logs. • Part of the matched event—Sends only the specified data field of the event to CloudWatch Logs. You specify the part of the event using a string formatted $.first_parameter.second_parameter. For example, to send just the Amazon EC2 instance ID, type $.detail.state in the field. • Constant—Sends a JSON-formatted text string that you specify to CloudWatch Logs. For example, to send a text string for the event, type {"Name":"MyInstance"}. The constant must be valid JSON. 9. Choose Configure details. On the Configure rule details screen, in the Name field, type a name for the rule. 10. In the Description field, enter a brief description for your rule, for example, Log when an EC2 instance is ready to accept traffic. 8 Amazon CloudWatch Events User Guide Step 3: Test Your Amazon CloudWatch Events Rule 11. If you're satisfied with the rule, choose Create rule. Step 3: Test Your Amazon CloudWatch Events Rule You can test your rule by launching an Amazon EC2 instance using the Amazon EC2 console. After waiting a few minutes for the instance to launch and to initialize, check your AWS Lambda metrics in the Amazon CloudWatch console to verify that your function was invoked. To test your CloudWatch Events rule using the console 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. Launch an Amazon EC2 instance. For more information about how to launch an instance, see Launch Your Instance in the Amazon EC2 User Guide for Linux Instances. 3. To view your AWS Lambda metrics, open the CloudWatch console https:// console.aws.amazon.com/cloudwatch/. 4. In the navigation pane, under Metrics, choose Lambda to view the metrics generated by your Lambda function. 5. To view the output from your function, in the navigation pane, choose Logs, and then in the Log Groups list, select the /aws/lambda log group that contains the data. 6. Under Log Streams, select a log stream to view the data about the instance you launched. Scenario 2: Take Scheduled EBS Snapshots You can run CloudWatch Events rules according to a schedule. In this scenario, you create a snapshot of an existing Amazon Elastic Block Store (Amazon EBS) volume on a schedule. You can choose a fixed rate to create a snapshot every few minutes or use a cron expression to specify that the snapshot is made at a specific time of day. For more information about working with Amazon EBS snapshots, see Amazon EBS Snapshots in the Amazon EC2 User Guide for Linux Instances. Step 1: Create an Amazon CloudWatch Events Rule To create a CloudWatch Events rule 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Events. 3. Choose Create rule, and then under Event selector, choose Schedule. 4. Do one of the following: • To create a snapshot in time intervals, choose Fixed rate of, enter the number of minutes (for example, 5) in the field, and then choose minutes from the list. • To create a snapshot at a specific time of day, choose Cron expression, and enter a cron expression (for example, 0/5 * * * ? *) in the field. For more information about using cron expressions, see Schedule Expression Syntax for Rules (p. 19). 5. Under Targets, choose Add target. 6. In the Select target type list, choose Built-in-target, and in the Action list, choose Create a snapshot of an EBS volume. 9 Amazon CloudWatch Events User Guide Step 2: Test Your Amazon CloudWatch Events Rule 7. In the Volume ID drop-down list, enter the ID of the EBS volume that you want to create a snapshot of. 8. Choose Configure details. On the Configure rule details screen, in the Name field, type a name for the rule. 9. In the Description field, enter a brief description for your rule, for example, Create EBS snapshot. 10. If you're satisfied with the rule, choose Create rule. Step 2: Test Your Amazon CloudWatch Events Rule You can test your rule by viewing the Amazon EC2 console after the Amazon EBS snapshot has been taken. To test your CloudWatch Events rule 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. In the navigation pane, under Elastic Block Store, choose Snapshots. 3. In the list of snapshots, verify that your snapshot appears. Scenario 3: Log an AWS API Call You can use a simple AWS Lambda function that logs each AWS API call. For example, you can create a rule to log any operation within Amazon EC2, or you can limit this rule to log only a specific API call. In this scenario, you log every time an Amazon EC2 instance is stopped. Step 1: Create an AWS Lambda function To create an AWS Lambda function 1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/. 2. Choose Create a Lambda function, and then on the Select blueprint screen, choose helloworld. 3. On the Configure function screen, in the Name field, enter LogIncomingEvent. 4. In the Lambda function code section, edit the sample code to match the following example: console.log('Loading function'); exports.handler = function(event, context) { console.log('LogIncomingEvent()'); console.log('Here is the event:', JSON.stringify(event, null, 2)); context.succeed('Ready'); }; 5. Under Lambda function handler and role, in the Role field, if you have a lambda_basic_execution_rule, select it. Otherwise, create a new basic execution role. 6. Choose Next, and then on the Review screen, choose Edit to make any changes. If you're satisfied with the rule, choose Create function. 10 Amazon CloudWatch Events User Guide Step 2: Create an Amazon CloudWatch Events Rule Step 2: Create an Amazon CloudWatch Events Rule To create a CloudWatch Events rule 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Events. 3. Choose Create rule, and then under Event selector, choose AWS API call. 4. In the Service name list, choose EC2. 5. Choose the Specific operation radio button, and then in the Specific operation field, choose StopInstances from the list. 6. Under Targets, choose Add target. In the Select target type list, choose Lambda function. 7. In the Function list, select the EC2InstanceStopped function that you created in "Step 1: Create an AWS Lambda Function." 8. Choose Configure input, and then choose one of the following options: 9. a. Matched event—Sends all of the data fields in the event to CloudWatch Logs. b. Part of the matched event—Sends only the specified data field of the event to CloudWatch Logs. You specify the part of the event using a string formatted $.first_parameter.second_parameter. For example, to send just detail part of the event, type $.detail. c. Constant—Sends a JSON-formatted text string that you specify to CloudWatch Logs. For example, to send a text string for the event, type {"Name":"MyInstance"}. The constant must be valid JSON. Choose Configure details. On the Configure rule details screen, in the Name field, type a name for the rule. 10. In the Description field, enter a brief description for your rule, for example, Log when an EC2 StopInstances API call is made. 11. If you're satisfied with the rule, choose Create rule. Step 3: Test Your Amazon CloudWatch Events Rule by Stopping an Instance You can test your rule by stopping an Amazon EC2 instance using the Amazon EC2 console. After waiting a few minutes for the instance to stop, check your AWS Lambda metrics in the CloudWatch console to verify that your function was invoked. To test your CloudWatch Events rule by stopping an instance 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. Launch an Amazon EC2 instance. For more information about how to launch an instance, see Launch Your Instance in the Amazon EC2 User Guide for Linux Instances. 3. Stop an Amazon EC2 instance. For more information, see Stop and Start Your Instance in the Amazon EC2 User Guide for Linux Instances. 4. To view your CloudWatch Events metrics, open the CloudWatch console https:// console.aws.amazon.com/cloudwatch/. 5. In the navigation pane, under Metrics, choose Events, and then choose ec2-start-stopinvocations to view the number of invocations on the graph. You should see one data point on the graph from the instance you just stopped. 11 Amazon CloudWatch Events User Guide Scenario 4: Log the State of an Auto Scaling Group 6. To view the output from your function, in the navigation pane, choose Logs, and then in the Log Groups list, select the /aws/lambda log group that contains the data. 7. Under Log Streams, select a log stream to view the data about the instance you launched. Scenario 4: Log the State of an Auto Scaling Group You can run an AWS Lambda function that logs whenever an Auto Scaling group launches or terminates an Amazon EC2 instance and whether the launch or terminate action was successful. For additional CloudWatch Events scenarios using Auto Scaling events, see Getting CloudWatch Events When Your Auto Scaling Group Scales in the Auto Scaling User Guide. Step 1: Create an AWS Lambda function To create an AWS Lambda function 1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/. 2. Choose Create a Lambda function, and then on the Select blueprint screen, choose helloworld. 3. On the Configure function screen, in the Name field, enter AutoScalingLaunchTerminate. 4. In the Lambda function code section, edit the sample code to match the following example: console.log('Loading function'); exports.handler = function(event, context) { console.log('AutoScalingLaunchTerminate()'); console.log('Here is the event:', JSON.stringify(event, null, 2)); context.succeed('Ready'); }; 5. Under Lambda function handler and role, in the Role field, if you have a lambda_basic_execution_rule, select it. Otherwise, create a new basic execution role. 6. Choose Next, and then on the Review screen, choose Edit to make any changes. If you're satisfied with the rule, choose Create function. Step 2: Create an Amazon CloudWatch Events Rule To create a CloudWatch Events rule 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Events. 3. Choose Create rule, and then under Event selector, choose Auto Scaling. 4. Choose Any instance event to capture all successful and unsuccessful launch and terminate actions. 5. Do one of the following: 12 Amazon CloudWatch Events User Guide Step 3: Test Your Amazon CloudWatch Events Rule with an Auto Scaling Group 6. 7. 8. • To make the rule respond to any of your Auto Scaling groups in the region, choose Any group name. • To make the rule respond to a specific Auto Scaling group, choose Specific group name(s) and then in the text box, enter an Auto Scaling group name. Under Targets, choose Add target. In the Select target type list, choose Lambda function. In the Function list, select the AutoScalingLaunchTerminate function that you created in "Step 1: Create an AWS Lambda Function." Choose Configure input, and then choose one of the following options: • Matched event—Sends all of the data fields in the event to CloudWatch Logs. • Part of the matched event—Sends only the specified data field of the event to CloudWatch Logs. You specify the part of the event using a string formatted $.first_parameter.second_parameter. For example, to send just the detail part of the event, type $.detail. • Constant—Sends a JSON-formatted text string that you specify to CloudWatch Logs. For example, to send a text string for the event, type {"Name":"MyInstance"}. The constant must be valid JSON. 9. Choose Configure details. On the Configure rule details screen, in the Name field, type a name for the rule. 10. In the Description field, enter a brief description for your rule, for example, Log whenever an Auto Scaling group launches or terminates. 11. If you're satisfied with the rule, choose Create rule. Step 3: Test Your Amazon CloudWatch Events Rule with an Auto Scaling Group You can test your rule by launching or terminating an Auto Scaling group using the Amazon EC2 console. After waiting a few minutes for the action to be logged, check your AWS Lambda in the CloudWatch console to verify that your Lambda function was invoked. To test your CloudWatch Events rule with an Auto Scaling group 1. 2. 3. 4. 5. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. For more information about how to launch an instance, see Launch Your Instance in the Amazon EC2 User Guide for Linux Instances. Create an Auto Scaling group and let it launch an Amazon EC2 instance for you. For more information about Auto Scaling groups, see Launch Your Instance in the Auto Scaling User Guide. In the navigation pane, under Metrics, choose Lambda to view the metrics generated by your Lambda function. To view the output from your function, in the navigation pane, choose Logs, and then in the Log Groups list, select the /aws/lambda log group that contains the data. Under Log Streams, select a log stream to view the data about the Auto Scaling group that you launched or terminated. Scenario 5: Relay Events to an Amazon Kinesis Stream In this scenario, you relay AWS API call events in CloudWatch Events to an Amazon Kinesis stream. 13 Amazon CloudWatch Events User Guide Step 1: Create an Amazon Kinesis Stream Step 1: Create an Amazon Kinesis Stream To create an Amazon Kinesis stream 1. Create a stream named "test". At a command prompt, type: aws kinesis create-stream --stream-name test --shard-count 1 2. Check the progress of the stream's creation. At a command prompt, type: aws kinesis describe-stream --stream-name test Wait until you see ACTIVE in the stream status, like the one in the following example: { "StreamDescription": { "StreamStatus": "ACTIVE", "StreamName": "test", "StreamARN": "arn:aws:kinesis:us-east-1:123456789012:stream/test", "Shards": [ { "ShardId": "shardId-000000000000", "HashKeyRange": { "EndingHashKey": "170141183460469231731687303715884105727", "StartingHashKey": "0" }, "SequenceNumberRange": { "StartingSequenceNumber": "49546986683135544286507457935754639466300920667981217794" } } ] } } Step 2: Create an Amazon CloudWatch Events Rule To create a CloudWatch Events rule 1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. 2. In the navigation pane, choose Events. 3. Choose Create rule, and then under Event selector, choose AWS API call. 4. In the Service name list, choose EC2. 5. Choose the Specific operation radio button, and then in the Specific operation field, choose StopInstances from the list. 6. Under Targets, choose Add target. In the Select target type list, choose Kinesis stream. 7. In the Stream list, select the test stream that you created in "Step 1: Create an Amazon Kinesis Stream." 8. Choose Configure input, and then choose one of the following options: 14 Amazon CloudWatch Events User Guide Step 3: Test Your Amazon CloudWatch Events Rule by Stopping an Instance 9. a. Matched event—Sends all of the data fields in the event to CloudWatch Logs. b. Part of the matched event—Sends only the specified data field of the event to CloudWatch Logs. You specify the part of the event using a string formatted $.first_parameter.second_parameter. For example, to send just detail part of the event, type $.detail. c. Constant—Sends a JSON-formatted text string that you specify to CloudWatch Logs. For example, to send a text string for the event, type {"Name":"MyInstance"}. The constant must be valid JSON. Choose Configure details. On the Configure rule details screen, in the Name field, type a name for the rule. 10. In the Description field, enter a brief description for your rule, for example, Relay the event to an Amazon Kinesis stream when an EC2 StopInstances API call is made. 11. If you're satisfied with the rule, choose Create rule. Step 3: Test Your Amazon CloudWatch Events Rule by Stopping an Instance You can test your rule by stopping an Amazon EC2 instance using the Amazon EC2 console. After waiting a few minutes for the instance to stop, check your AWS Lambda metrics in the CloudWatch console to verify that your function was invoked. To test your CloudWatch Events rule by stopping an instance 1. Open the Amazon EC2 console at https://console.aws.amazon.com/ec2/. 2. Launch an Amazon EC2 instance. For more information about how to launch an instance, see Launch Your Instance in the Amazon EC2 User Guide for Linux Instances. 3. Stop an Amazon EC2 instance. For more information, see Stop and Start Your Instance in the Amazon EC2 User Guide for Linux Instances. 4. To view your CloudWatch Events metrics, open the CloudWatch console https:// console.aws.amazon.com/cloudwatch/. 5. In the navigation pane, under Metrics, choose Events, and then choose ec2-start-stopinvocations to view the number of invocations on the graph. You should see one data point on the graph from the instance you just stopped. Step 4: Get the Record to Verify that the Event is Relayed To get the record to verify that the event was relayed 1. Get an iterator to start reading from your Amazon Kinesis stream, At a command prompt, type: aws kinesis get-shard-iterator --shard-id shardId-000000000000 --sharditerator-type TRIM_HORIZON --stream-name test If the command is successful, you should see output similar to the following example: { "ShardIterator": "AAAAAAAAAAHSywljv0zEgPX4NyKdZ5wryMzP9yALs8NeKbUjp1IxtZs1Sp 15 Amazon CloudWatch Events User Guide Scenario 6: Run an AWS Lambda Function on a Schedule +KEd9I6AJ9ZG4lNR1EMi+9Md/nHvtLyxpfhEzYvkTZ4D9DQVz/ mBYWRO6OTZRKnW9gd+efGN2aHFdkH1rJl4BL9Wyrk +ghYG22D2T1Da2EyNSH1+LAbK33gQweTJADBdyMwlo5r6PqcP2dzhg=" } 2. Type the following command (use the shard iterator you obtained as the output of the previous command): aws kinesis get-records --shard-iterator AAAAAAAAAAHSywljv0zEgPX4NyKdZ5wryMzP9yALs8NeKbUjp1IxtZs1Sp +KEd9I6AJ9ZG4lNR1EMi+9Md/nHvtLyxpfhEzYvkTZ4D9DQVz/ mBYWRO6OTZRKnW9gd+efGN2aHFdkH1rJl4BL9Wyrk +ghYG22D2T1Da2EyNSH1+LAbK33gQweTJADBdyMwlo5r6PqcP2dzhg= If the get-records command is successful, it will request records from your stream for the shard that you specified when you obtained the shard iterator, as in the following example: { "Records":[ { "Data":"", "PartitionKey":"123”, "ApproximateArrivalTimestamp": 1.441215410867E9, "SequenceNumber":"49544985256907370027570885864065577703022652638596431874" } ], "MillisBehindLatest":24000, "NextShardIterator":"AAAAAAAAAAEDOW3ugseWPE4503kqN1yN1UaodY8unE0sYslMUmC6lX9hlig5+t4RtZ tALfiI4QGjunVgJvQsjxjh2aLyxaAaPr +LaoENQ7eVs4EdYXgKyThTZGPcca2fVXYJWL3yafv9dsDwsYVedI66dbMZFC8rPMWc797zxQkv4pSKvPOZvrUIud } Note The GetRecords API is a request, which means you may receive zero or more records, even if there are records in your stream. Any records returned may not represent all the records currently in your stream. If you don't receive the data you're looking for, keep calling get-records until you see an output with empty records. Records in Amazon Kinesis are Base64 encoded. However, the streams support in the AWS CLI does not provide Base64 decoding. If you use a Base64 decoder to manually decode the data, you will see that it is the event relayed to the stream in JSON form. Scenario 6: Run an AWS Lambda Function on a Schedule Using the AWS CLI You can set up a rule to run an AWS Lambda function on a schedule. This scenario uses the AWS CLI to create the rule. Note CloudWatch Events does not provide second-level precision in schedule expressions. The finest resolution using a cron expression is a minute. Due to the distributed nature of the CloudWatch Events and the target services, the delay between the time the scheduled rule is triggered and the time the target service honors the execution of the target resource might 16 Amazon CloudWatch Events User Guide Step 1: Create an AWS Lambda function be several seconds. Your scheduled rule will be triggered within that minute but not on the precise 0th second. Step 1: Create an AWS Lambda function To create an AWS Lambda function 1. Open the AWS Lambda console at https://console.aws.amazon.com/lambda/. 2. Choose Create a Lambda function, and then on the Select blueprint screen, choose helloworld. 3. On the Configure function screen, in the Name field, enter SomethingHappened. 4. In the Lambda function code section, edit the sample code to match the following example: console.log('Loading function'); exports.handler = function(event, context) { console.log('SomethingHappened()'); console.log('Here is the event:', JSON.stringify(event, null, 2)); context.succeed('Ready'); }; 5. Under Lambda function handler and role, in the Role field, if you have a lambda_basic_execution_rule, select it. Otherwise, create a new basic execution role. 6. Choose Next, and then on the Review screen, choose Edit to make any changes. If you're satisfied with the function, choose Create function. Step 2: Create an Amazon CloudWatch Events Rule To create a CloudWatch Events rule 1. At a command prompt, type the following to trust events.amazonaws.com: aws lambda add-permission \ --function-name SomethingHappened \ --statement-id MyId \ --action 'lambda:InvokeFunction' \ --principal events.amazonaws.com \ --source-arn arn:aws:events:us-east-1:123456789012:rule/MyScheduledRule Note If you're using a specific Lambda alias or version, you must add the --qualifier parameter in the aws lambda add-permission command. aws lambda add-permission \ --function-name SomethingHappened \ --statement-id MyId \ --action 'lambda:InvokeFunction' \ --principal events.amazonaws.com \ --source-arn arn:aws:events:useast-1:123456789012:rule/MyScheduledRule --qualifier alias or version 17 Amazon CloudWatch Events User Guide Step 3: Verify Your Amazon CloudWatch Events Rule 2. At a command prompt, type the following to create a rule that self-triggers on a schedule: aws events put-rule \ --name MyScheduledRule \ --schedule-expression 'rate(5 minutes)' When the above rule self-triggers it will generate an event (that looks like the following), which can be used as an input to the targets of this rule: { "id": "53dc4d37-cffa-4f76-80c9-8b7d4a4d2eaa", "detail-type": "Scheduled Event", "source": "aws.events", "account": "123456789012", "time": "2015-10-08T16:53:06Z", "region": "us-east-1", "resources": ["arn:aws:events:useast-1:123456789012:rule/MyScheduledRule"], "detail": {} } 3. Run the following command to add the AWS Lambda function you created in Step 1 to this rule so that it is run every 5 minutes: aws events put-targets \ --rule MyScheduledRule \ --targets '{"Id" : "1", "Arn": "arn:aws:lambda:useast-1:123456789012:function:SomethingHappened"}' Step 3: Verify Your Amazon CloudWatch Events Rule You can verify your rule by checking your AWS Lambda metrics in the Amazon CloudWatch console. To verify your CloudWatch Events rule using the console 1. 2. 3. 4. To view your AWS Lambda metrics, open the CloudWatch console https:// console.aws.amazon.com/cloudwatch/. In the navigation pane, under Metrics, choose Lambda to view the metrics generated by your Lambda function. To view the output from your function, in the navigation pane, choose Logs, and then in the Log Groups list, select the /aws/lambda log group that contains the data. Under Log Streams, select a log stream to view the data about the instance you launched. 18 Amazon CloudWatch Events User Guide Cron Expressions Schedule Expression Syntax for Rules You can create rules that self-trigger on schedule in CloudWatch Events using cron or rate expressions. All scheduled events use UTC time zone and the minimum precision for schedules is 1 minute. Note CloudWatch Events does not provide second-level precision in schedule expressions. The finest resolution using a cron expression is a minute. Due to the distributed nature of the CloudWatch Events and the target services, the delay between the time the scheduled rule is triggered and the time the target service honors the execution of the target resource might be several seconds. Your scheduled rule will be triggered within that minute but not on the precise 0th second. CloudWatch Events supports the following formats: • cron( ) • rate( ) Cron Expressions Cron expressions have six required fields. Fields are separated by white space. For more information about cron expressions, see CRON expression at the Wikipedia Website. Field Values Wildcards Minutes 0-59 ,-*/ Hours 0-23 ,-*/ Day-of-month 1-31 ,-*?/LW Month 1-12 or JAN-DEC ,-*/ Day-of-week 1-7 or SUN-SAT ,-*?/L Year 1970-2199 ,-*/ 19 Amazon CloudWatch Events User Guide Cron Expressions Note You cannot specify a value in the Day-of-month and in the Day-of-week fields in the same cron expression. If you specify a value in one of the fields, you must use a ? (question mark) in the other. Wildcards: The , (comma) wildcard includes additional values. In the Month field, JAN,FEB,MAR would include January, February, and March. The - (dash) wildcard specifies ranges. In the Day field, 1-15 would include days 1 through 15 of the specified month. The * (asterisk) wildcard includes all values in the field. In the Hours field, * would include every hour. The / (forward slash) wildcard specifies increments. In the Minutes field, you could enter 1/10 to specify every tenth minute, starting from the first minute of the hour (for example, the 11th, 21st, and 31st minute, and so on). The ? (question mark) wildcard specifies one or another. In the Day-of-month field you could enter 7 and if you didn't care what day of the week the 7th was, you could enter ? in the Day-of-week field. The L wildcard in the Day-of-month or Day-of-week fields specifies the last day of the month or week. The W wildcard in the Day-of-month field specifies a weekday. In the Day-of-month field, 3W specifies the day closest to the third weekday of the month. You can use the following sample cron strings when creating a rule with schedule. Note Cron expressions that lead to rates faster than 1 minute are not supported. Support for specifying both a day-of-week and a day-of-month value is not complete (you must currently use the '?' character in one of these fields). Minutes Hours Day of month Month Day of week Year Meaning 0 10 * * ? * Run at 10:00 am (UTC) every day 15 12 * * ? * Run at 12:15 pm (UTC) every day 0 18 ? * MON-FRI * Run at 6:00 pm (UTC) every Monday through Friday 0 8 1 * ? * Run at 8:00 am (UTC) every 1st day of the month 0/15 * * * ? * Run every 15 minutes 20 Amazon CloudWatch Events User Guide Rate Expressions Minutes Hours Day of month Month Day of week Year Meaning 0/10 * ? * MON-FRI * Run every 10 minutes Monday through Friday 0/5 8-17 ? * MON-FRI * Run every 5 minutes Monday through Friday between 8:00 am and 5:55 pm (UTC) The following examples show how to use cron expressions with the AWS CLI. aws events put-rule --schedule-expression 'cron(0 12 * * ? *)' --name MyRule1 aws events put-rule --schedule-expression 'cron(15 10 ? * 6L 2002-2005)' -name MyRule2 Rate Expressions Rate expressions have the following two required fields. Fields are separated by white space. Field Values Value positive number Unit minute(s) OR hour(s) OR day(s) Note If the value is equal to 1, then the unit must be singular. Similarly, for values greater than 1, the unit must be plural. For example, rate(1 hours) and rate(5 hour) are not valid, but rate(1 hour) and rate(5 hours) are valid. The following examples show how to use rate expressions with the AWS CLI. aws events put-rule --schedule-expression rate(5 minutes)' --name MyRule3 aws events put-rule --schedule-expression rate(1 hour)' --name MyRule4 aws events put-rule --schedule-expression rate(1 day)' --name MyRule5 21 Amazon CloudWatch Events User Guide Events and Event Patterns Events in Amazon CloudWatch Events are represented as JSON objects. For more information about JSON objects, see RFC 7159. The following is an example event: { "version": "0", "id": "6a7e8feb-b491-4cf7-a9f1-bf3703467718", "detail-type": "EC2 Instance State-change Notification", "source": "aws.ec2", "account": "111122223333", "time": "2015-12-22T18:43:48Z", "region": "us-east-1", "resources": [ "arn:aws:ec2:us-east-1:123456789012:instance/i-12345678" ], "detail": { "instance-id": "i-12345678", "state": "terminated" } } It is important to remember the following details about an event: • They all have the same top-level fields – the ones appearing in the example above – which are never absent. • The contents of the detail top-level field will be different depending on which service generated the event and what the event is. • The combination of the top-level source field and detail-type fields serve to identify the fields and values found in the detail field. Each event field is described below. version By default, this is set to 0 (zero) in all events. id A unique value is generated for every event. This can be helpful in tracing events as they move through rules to targets, and are processed. 22 Amazon CloudWatch Events User Guide Event Patterns detail-type Identifies, in combination with the source field, the fields and values that will appear in the detail field. source Identifies the service that sourced the event. All events sourced from within AWS will begin with "aws." Customer-generated events can have any value here as long as it doesn't begin with "aws." We recommend the use of java package-name style reverse domain-name strings. account The 12-digit number identifying an AWS account. time The event timestamp, which can be specified by the service originating the event. If the event spans a time interval, the service might choose to report the start time, so this value can be noticeably before the time the event is actually received. region Identifies the AWS region where the event originated. resources This JSON array contains ARNs that identify resources that are involved in the event. Inclusion of these ARNs is at the discretion of the service. For example, Amazon EC2 instance state-changes include Amazon EC2 instance ARNs, Auto Scaling events include ARNs for both instances and Auto Scaling groups, but API calls with AWS CloudTrail do not include resource ARNs. detail A JSON object, whose content is at the discretion of the service originating the event. The detail content in the example above is very simple, just two fields. AWS API call events have detail objects with around 50 fields nested several levels deep. Event Patterns Rules use event patterns to select events and route them to targets. A pattern either matches an event or it doesn't. Event patterns are represented as JSON objects with a structure that is similar to that of events, for example: { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ], "detail": { "state": [ "running" ] } } It is important to remember the following things about event pattern matching: • For a pattern to match an event, the event must contain all the field names listed in the pattern. The field names must appear in the event with the same nesting structure. • Other fields of the event not mentioned in the pattern are ignored; effectively, there is a "*": "*" wildcard for fields not mentioned. • The value of each field in the pattern is an array containing one or more values, and the pattern matches if any of the values in the array match the value in the event. • If the value in the event is an array, then the pattern matches if the intersection of the pattern array and the event array is non-empty. • The matching is exact (character-by-character), without case-folding or any other string normalization. • The values being matched follow JSON rules: Strings enclosed in quotes, numbers, and the unquoted keywords true, false, and null. 23 Amazon CloudWatch Events User Guide Event Patterns • Number matching is at the string representation level. For example, 300, 300.0, and 3.0e2 are not considered equal. The following event patterns would match the event above. { "resources": [ "arn:aws:ec2:us-east-1:123456789012:instance/i-12345678", "arn:aws:ec2:us-east-1:123456789012:instance/i-abcdefgh" ] } { "detail": { "state": [ "terminated" ] } } These event patterns would not match the event above: { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ], "detail": { "state": [ "pending" ] } } { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ], "resources": [ "arn:aws:ec2:us-east-1::image/ami-12345678" ] } 24 Amazon CloudWatch Events User Guide Handling Failures When Using PutEvents Adding Events with PutEvents The PutEvents action sends multiple events to CloudWatch Events in a single request. Each PutEvents request can support a limited number of entries. For more information, see CloudWatch Events Limits (p. 2). The PutEvents operation attempts to process all entries in the natural order of the request. Each event has a unique id that is assigned by CloudWatch Events after you call PutEvents. The following example Java code sends two identical events to CloudWatch Events: PutEventsRequestEntry requestEntry = new PutEventsRequestEntry() .withTime(new Date()) .withSource("com.mycompany.myapp") .withDetailType("myDetailType") .withResources("resource1", "resource2") .withDetail("{ \"key1\": \"value1\", \"key2\": \"value2\" }"); PutEventsRequest request = new PutEventsRequest() .withEntries(requestEntry, requestEntry); PutEventsResult result = awsEventsClient.putEvents(request); for (PutEventsResultEntry resultEntry : result.getEntries()) { if (resultEntry.getEventId() != null) { System.out.println("Event Id: " + resultEntry.getEventId()); } else { System.out.println("Injection failed with Error Code: " + resultEntry.getErrorCode()); } } The PutEvents result includes an array of response entries. Each entry in the response array directly correlates with an entry in the request array using natural ordering, from the top to the bottom of the request and response. The response Entries array always includes the same number of entries as the request array. Handling Failures When Using PutEvents By default, failure of individual entries within a request does not stop the processing of subsequent entries in the request. This means that a response Entries array includes both successfully and 25 Amazon CloudWatch Events User Guide Handling Failures When Using PutEvents unsuccessfully processed entries. You must detect unsuccessfully processed entries and include them in a subsequent call. Successful result entries include Id value, and unsuccessful result entries include ErrorCode and ErrorMessage values. The ErrorCode parameter reflects the type of error. ErrorMessage provides more detailed information about the error. The example below has three result entries for a PutEvents request. The second entry has failed and is reflected in the response. Example: PutEvents Response Syntax { "FailedEntryCount": 1, "Entries": [ { "EventId": "11710aed-b79e-4468-a20b-bb3c0c3b4860" }, { "ErrorCode": "InternalFailure", "ErrorMessage": "Internal Service Failure" }, "EventId": "d804d26a-88db-4b66-9eaf-9a11c708ae82" } ] } Entries that were unsuccessfully processed can be included in subsequent PutEvents requests. First, check the FailedRecordCount parameter in the PutEventsResult to confirm if there are failed records in the request. If so, each Entry that has an ErrorCode that is not null should be added to a subsequent request. For an example of this type of handler, refer to the following code. Example: PutEvents failure handler PutEventsRequestEntry requestEntry = new PutEventsRequestEntry() .withTime(new Date()) .withSource("com.mycompany.myapp") .withDetailType("myDetailType") .withResources("resource1", "resource2") .withDetail("{ \"key1\": \"value1\", \"key2\": \"value2\" }"); List putEventsRequestEntryList = new ArrayList<>(); for (int i = 0; i < 3; i++) { putEventsRequestEntryList.add(requestEntry); } PutEventsRequest putEventsRequest = new PutEventsRequest(); putEventsRequest.withEntries(putEventsRequestEntryList); PutEventsResult putEventsResult = awsEventsClient.putEvents(putEventsRequest); while (putEventsResult.getFailedEntryCount() > 0) { final List failedEntriesList = new ArrayList<>(); final List PutEventsResultEntryList = putEventsResult.getEntries(); for (int i = 0; i < PutEventsResultEntryList.size(); i++) { final PutEventsRequestEntry putEventsRequestEntry = putEventsRequestEntryList.get(i); final PutEventsResultEntry putEventsResultEntry = PutEventsResultEntryList.get(i); if (putEventsResultEntry.getErrorCode() != null) { 26 Amazon CloudWatch Events User Guide Sending Events Using the AWS CLI failedEntriesList.add(putEventsRequestEntry); } } putEventsRequestEntryList = failedEntriesList; putEventsRequest.setEntries(putEventsRequestEntryList); putEventsResult = awsEventsClient.putEvents(putEventsRequest); } Sending Events Using the AWS CLI You can use the AWS CLI to send custom events. The following example puts one custom event into CloudWatch Events: aws events put-events \ --entries '[{"Time": "2016-01-14T01:02:03Z", "Source": "com.mycompany.myapp", "Resources": ["resource1", "resource2"], "DetailType": "myDetailType", "Detail": "{ \"key1\": \"value1\", \"key2\": \"value2\" }"}]' You can also create a file for example, entries.json like the following: [ { "Time": "2016-01-14T01:02:03Z", "Source": "com.mycompany.myapp", "Resources": [ "resource1", "resource2" ], "DetailType": "myDetailType", "Detail": "{ \"key1\": \"value1\", \"key2\": \"value2\" }" } ] You can use the AWS CLI to read the entries from this file and send events. At a command prompt, type: aws events put-events --entries file://entries.json Calculating PutEvents Event Entry Sizes You can inject custom events into CloudWatch Events using the PutEvents action. You can inject multiple events using the PutEvents action as long as the total entry size is less than 256KB. You can calculate the event entry size beforehand by following the steps below. You can then batch multiple even entries into one request for efficiency. Note The size limit is imposed on the entry. Even if the entry is less than the size limit, it does not mean that the event in CloudWatch Events will also be less than this size. On the contrary, the event size will always be larger than the entry size due to the necessary characters and keys of the JSON representation of the event. For more information, see Events and Event Patterns (p. 22). 27 Amazon CloudWatch Events User Guide Calculating PutEvents Event Entry Sizes The PutEventsRequestEntry size is calculated as follows: • If the Time parameter is specified, it is measured as 14 bytes. • The Source and DetailType parameters are measured as the number of bytes for their UTF-8 encoded forms. • If the Detail parameter is specified, it is measured as the number of bytes for its UTF-8 encoded form. • If the Resources parameter is specified, each entry is measured as the number of bytes for their UTF-8 encoded forms. The following example Java code calculates the size of a given PutEventsRequestEntry object: int getSize(PutEventsRequestEntry entry) { int size = 0; if (entry.getTime() != null) { size += 14; } size += entry.getSource().getBytes(StandardCharsets.UTF_8).length; size += entry.getDetailType().getBytes(StandardCharsets.UTF_8).length; if (entry.getDetail() != null) { size += entry.getDetail().getBytes(StandardCharsets.UTF_8).length; } if (entry.getResources() != null) { for (String resource : entry.getResources()) { if (resource != null) { size += resource.getBytes(StandardCharsets.UTF_8).length; } } } return size; } 28 Amazon CloudWatch Events User Guide Amazon EC2 Events Event Types for CloudWatch Events Amazon CloudWatch Events supports the following events: Event Types • Amazon EC2 Events (p. 29) • Amazon EC2 Simple Systems Manager Events (p. 30) • Auto Scaling Events (p. 30) • AWS API Call Events (p. 34) • AWS CodeDeploy Events (p. 36) • AWS Console Sign-in Events (p. 37) • Scheduled Events (p. 38) Amazon EC2 Events The following is an example of an EC2 instance state change notification event, with an Amazon EC2 instance in the pending state: { "id": "7bf73129-1428-4cd3-a780-95db273d1602", "detail-type": "EC2 Instance State-change Notification", "source": "aws.ec2", "account": "123456789012", "time": "2015-11-11T21:29:54Z", "region": "us-east-1", "resources": [ "arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111" ], "detail": { "instance-id": "i-abcd1111", "state": "pending" } } 29 Amazon CloudWatch Events User Guide Amazon EC2 Simple Systems Manager Events Amazon EC2 Simple Systems Manager Events The following are examples of Amazon EC2 Simple Systems Manager (SSM) events. For more information, see Log Command Execution Status Changes for Run Command in the Amazon EC2 User Guide for Linux Instances. EC2 Command Status-change Notification { "version": "0", "id": "51c0891d-0e34-45b1-83d6-95db273d1602", "detail-type": "EC2 Command Status-change Notification", "source": "aws.ssm", "account": "123456789012", "time": "2016-07-10T21:51:32Z", "region": "us-east-1", "resources": ["arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"], "detail": { "command-id": "e8d3c0e4-71f7-4491-898f-c9b35bee5f3b", "document-name": "AWS-RunPowerShellScript", "expire-after": "2016-07-14T22:01:30.049Z", "parameters": { "executionTimeout": ["3600"], "commands": ["date"] }, "requested-date-time": "2016-07-10T21:51:30.049Z", "status": "Success" } } EC2 Command Invocation Status-change Notification { "version": "0", "id": "4780e1b8-f56b-4de5-95f2-95db273d1602", "detail-type": "EC2 Command Invocation Status-change Notification", "source": "aws.ssm", "account": "123456789012", "time": "2016-07-10T21:51:32Z", "region": "us-east-1", "resources": ["arn:aws:ec2:us-east-1:123456789012:instance/i-abcd1111"], "detail": { "command-id": "e8d3c0e4-71f7-4491-898f-c9b35bee5f3b", "document-name": "AWS-RunPowerShellScript", "instance-id": "i-9bb89e2b", "requested-date-time": "2016-07-10T21:51:30.049Z", "status": "Success" } } Auto Scaling Events The following are examples of the Auto Scaling events. Amazon EC2 Instance-launch Lifecycle Action 30 Amazon CloudWatch Events User Guide Auto Scaling Events { "version": "0", "id": "6a7e8feb-b491-4cf7-a9f1-bf3703467718", "detail-type": "EC2 Instance-launch Lifecycle Action", "source": "aws.autoscaling", "account": "123456789012", "time": "2015-12-22T18:43:48Z", "region": "us-east-1", "resources": [ "arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:59fcbb81bd02-485d-80ce-563ef5b237bf:autoScalingGroupName/sampleASG" ], "detail": { "LifecycleActionToken": "c613620e-07e2-4ed2-a9e2-ef8258911ade", "AutoScalingGroupName": "sampleASG", "LifecycleHookName": "SampleLifecycleHook-12345", "EC2InstanceId": "i-12345678", "LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING" } } Amazon EC2 Instance Launch Successful { "id": "3e3c153a-8339-4e30-8c35-687ebef853fe", "detail-type": "EC2 Instance Launch Successful", "source": "aws.autoscaling", "account": "123456789012", "time": "2015-11-11T21:31:47Z", "region": "us-east-1", "resources": [ "arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:eb56d16bbbf0-401d-b893-d5978ed4a025:autoScalingGroupName/ASGLaunchSuccess", "arn:aws:ec2:us-east-1:123456789012:instance/i-b188560f" ], "detail": { "StatusCode": "InProgress", "AutoScalingGroupName": "ASGLaunchSuccess", "ActivityId": "9cabb81f-42de-417d-8aa7-ce16bf026590", "Details": { "Availability Zone": "us-east-1b", "Subnet ID": "subnet-95bfcebe" }, "RequestId": "9cabb81f-42de-417d-8aa7-ce16bf026590", "EndTime": "2015-11-11T21:31:47.208Z", "EC2InstanceId": "i-b188560f", "StartTime": "2015-11-11T21:31:13.671Z", "Cause": "At 2015-11-11T21:31:10Z a user request created an Auto Scaling group changing the desired capacity from 0 to 1. At 2015-11-11T21:31:11Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 1." } } Amazon EC2 Instance Launch Unsuccessful { 31 Amazon CloudWatch Events User Guide Auto Scaling Events "id": "1681ab87-4a09-459f-95a2-7fa09403c4b7", "detail-type": "EC2 Instance Launch Unsuccessful", "source": "aws.autoscaling", "account": "123456789012", "time": "2015-11-11T21:42:36Z", "region": "us-east-1", "resources": [ "arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:528ffce5ef9f-4c1d-8d18-5d005b4a438c:autoScalingGroupName/brokenASG", "arn:aws:ec2:us-east-1:123456789012:instance/" ], "detail": { "StatusCode": "Failed", "AutoScalingGroupName": "brokenASG", "ActivityId": "06076c51-4874-487d-b15b-7895a713ab55", "Details": { "Availability Zone": "us-east-1e", "Subnet ID": "subnet-16c5df2c" }, "RequestId": "06076c51-4874-487d-b15b-7895a713ab55", "EndTime": "2015-11-11T21:42:36.000Z", "EC2InstanceId": "", "StartTime": "2015-11-11T21:42:36.698Z", "Cause": "At 2015-11-11T21:42:09Z a user request update of Auto Scaling group constraints to min: 0, max: 10, desired: 2 changing the desired capacity from 0 to 2. At 2015-11-11T21:42:35Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 2." } } Amazon EC2 Instance-terminate Lifecycle Action { "version": "0", "id": "468fe059-f4b7-445f-bb22-2a271b94974d", "detail-type": "EC2 Instance-terminate Lifecycle Action", "source": "aws.autoscaling", "account": "123456789012", "time": "2015-12-22T18:43:48Z", "region": "us-east-1", "resources": [ "arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:59fcbb81bd02-485d-80ce-563ef5b237bf:autoScalingGroupName/sampleASG" ], "detail": { "LifecycleActionToken": "630aa23f-48eb-45e7-aba6-799ea6093a0f", "AutoScalingGroupName": "sampleASG", "LifecycleHookName": "SampleLifecycleHook-6789", "EC2InstanceId": "i-12345678", "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING" } } Amazon EC2 Instance Terminate Successful { "id": "156d01c9-a6c3-4d7e-b883-5758266b95af", 32 Amazon CloudWatch Events User Guide Auto Scaling Events "detail-type": "EC2 Instance Terminate Successful", "source": "aws.autoscaling", "account": "123456789012", "time": "2015-11-11T21:36:57Z", "region": "us-east-1", "resources": [ "arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:eb56d16bbbf0-401d-b893-d5978ed4a025:autoScalingGroupName/ASGTerminate", "arn:aws:ec2:us-east-1:123456789012:instance/i-b188560f" ], "detail": { "StatusCode": "InProgress", "AutoScalingGroupName": "ASGTerminate", "ActivityId": "56472e79-538a-4ba7-b3cc-768d889194b0", "Details": { "Availability Zone": "us-east-1b", "Subnet ID": "subnet-95bfcebe" }, "RequestId": "56472e79-538a-4ba7-b3cc-768d889194b0", "EndTime": "2015-11-11T21:36:57.498Z", "EC2InstanceId": "i-b188560f", "StartTime": "2015-11-11T21:36:12.649Z", "Cause": "At 2015-11-11T21:36:03Z a user request update of Auto Scaling group constraints to min: 0, max: 1, desired: 0 changing the desired capacity from 1 to 0. At 2015-11-11T21:36:12Z an instance was taken out of service in response to a difference between desired and actual capacity, shrinking the capacity from 1 to 0. At 2015-11-11T21:36:12Z instance ib188560f was selected for termination." } } Amazon EC2 Instance Terminate Unsuccessful { "id": "5e3df53a-0239-4e31-7d15-087ebef903ce", "detail-type": "EC2 Instance Terminate Unsuccessful", "source": "aws.autoscaling", "account": "123456789012", "time": "2015-12-01T23:34:57Z", "region": "us-east-1", "resources": [ "arn:aws:autoscaling:useast-1:123456789012:autoScalingGroup:cf5ebd9c-8e2a-4197abe2-2fb94e8d1f87:autoScalingGroupName/ASGTermFail", "arn:aws:ec2:us-east-1:123456789012:instance/i-b188560f" ], "detail": { "StatusCode": "InProgress", "Description": "Terminating EC2 instance: i-b188560f", "AutoScalingGroupName": "ASGTermFail", "ActivityId": "c1a8f6ce-82e8-4517-96ba-67d1999ceee4", "Details": { "Availability Zone": "us-east-1e", "Subnet ID": "subnet-915643ba" }, "RequestId": "c1a8f6ce-82e8-4517-96ba-67d1999ceee4", "StatusMessage": "", "EndTime": "2015-12-01T23:34:57.721Z", 33 Amazon CloudWatch Events User Guide AWS API Call Events "EC2InstanceId": "i-b188560f", "StartTime": "2015-12-01T23:33:48.489Z", "Cause": "At 2015-12-01T23:33:41Z a user request explicitly set group desired capacity changing the desired capacity from 2 to 0. At 2015-12-01T23:33:47Z an instance was taken out of service in response to a difference between desired and actual capacity, shrinking the capacity from 2 to 0. At 2015-12-01T23:33:47Z instance i-0867b4292c0cff474 was selected for termination. At 2015-12-01T23:33:48Z instance i-b188560f was selected for termination." } } AWS API Call Events The following is an example of an AWS API call event to Amazon S3 to create a bucket: { "version": "0", "id": "36eb8523-97d0-4518-b33d-ee3579ff19f0", "detail-type": "AWS API Call via CloudTrail", "source": "aws.s3", "account": "123456789012", "time": "2016-02-20T01:09:13Z", "region": "us-east-1", "resources": [], "detail": { "eventVersion": "1.03", "userIdentity": { "type": "Root", "principalId": "123456789012", "arn": "arn:aws:iam::123456789012:root", "accountId": "123456789012", "sessionContext": { "attributes": { "mfaAuthenticated": "false", "creationDate": "2016-02-20T01:05:59Z" } } }, "eventTime": "2016-02-20T01:09:13Z", "eventSource": "s3.amazonaws.com", "eventName": "CreateBucket", "awsRegion": "us-east-1", "sourceIPAddress": "100.100.100.100", "userAgent": "[S3Console/0.4]", "requestParameters": { "bucketName": "bucket-test-iad" }, "responseElements": null, "requestID": "9D767BCC3B4E7487", "eventID": "24ba271e-d595-4e66-a7fd-9c16cbf8abae", "eventType": "AwsApiCall" } } 34 Amazon CloudWatch Events User Guide AWS API Call Events Only the read/write events from the following services are supported. Read-only APIs, such as those that begin with List, Get, or Describe aren't supported. In addition, AWS API call events that are larger than 256KB in size are not supported. • Auto Scaling • AWS Certificate Manager • AWS CloudFormation • Amazon CloudFront • AWS CloudHSM • Amazon CloudSearch • AWS CloudTrail • Amazon CloudWatch • Amazon CloudWatch Events • Amazon CloudWatch Logs • AWS CodeDeploy • AWS CodePipeline • Amazon Cognito Identity • Amazon Cognito Sync • AWS Config • AWS Data Pipeline • AWS Device Farm • AWS Direct Connect • AWS Directory Service • AWS Database Migration Service • Amazon DynamoDB • Amazon EC2 Container Registry • Amazon EC2 Container Service • Amazon EC2 Simple Systems Manager • Amazon ElastiCache • AWS Elastic Beanstalk • Amazon Elastic Compute Cloud • Amazon Elastic File System • Elastic Load Balancing • Amazon EMR • Amazon Elastic Transcoder • Amazon Elasticsearch Service • Amazon GameLift • Amazon Glacier • AWS Identity and Access Management (supported in the US East (N. Virginia) Region only) • Amazon Inspector • AWS IoT • AWS Key Management Service • Amazon Kinesis • Amazon Kinesis Firehose • AWS Lambda • Amazon Machine Learning • AWS OpsWorks 35 Amazon CloudWatch Events User Guide AWS CodeDeploy Events • Amazon Redshift • Amazon Relational Database Service • Amazon Route 53 • AWS Security Token Service • Amazon Simple Email Service • Amazon Simple Notification Service • Amazon Simple Queue Service • Amazon Simple Storage Service • Amazon Simple Workflow Service • AWS Storage Gateway • AWS Support • AWS WAF • Amazon WorkDocs • Amazon WorkSpaces AWS CodeDeploy Events The following are examples of the AWS CodeDeploy events. For more information, see Monitoring Deployments with CloudWatch Events in the AWS CodeDeploy User Guide. AWS CodeDeploy Deployment State-change Notification { "account": "123456789012", "region": "us-east-1", "detail-type": "CodeDeploy Deployment State-change Notification", "source": "aws.codedeploy", "version": "0", "time": "2016-06-30T22:06:31Z", "id": "c071bfbf-83c4-49ca-a6ff-3df053957145", "resources": [ "arn:aws:codedeploy:us-east-1:123456789012:application:myApplication", "arn:aws:codedeploy:us-east-1:123456789012:deploymentgroup:myApplication/ myDeploymentGroup" ], "detail": { "instanceGroupId": "9fd2fbef-2157-40d8-91e7-6845af69e2d2", "region": "us-east-1", "application": "myApplication", "deploymentId": "d-123456789", "state": "SUCCESS", "deploymentGroup": "myDeploymentGroup" } } AWS CodeDeploy Instance State-change Notification { "account": "123456789012", "region": "us-east-1", "detail-type": "CodeDeploy Instance State-change Notification", "source": "aws.codedeploy", 36 Amazon CloudWatch Events User Guide AWS Console Sign-in Events "version": "0", "time": "2016-06-30T23:18:50Z", "id": "fb1d3015-c091-4bf9-95e2-d98521ab2ecb", "resources": [ "arn:aws:ec2:us-east-1:123456789012:instance/i-0000000aaaaaaaaaa", "arn:aws:codedeploy:us-east-1:123456789012:deploymentgroup:myApplication/ myDeploymentGroup", "arn:aws:codedeploy:us-east-1:123456789012:application:myApplication" ], "detail": { "instanceId": "i-0000000aaaaaaaaaa", "region": "us-east-1", "state": "SUCCESS", "application": "myApplication", "deploymentId": "d-123456789", "instanceGroupId": "8cd3bfa8-9e72-4cbe-a1e5-da4efc7efd49", "deploymentGroup": "myDeploymentGroup" } } AWS Console Sign-in Events AWS console sign-in events are supported only in the US East (N. Virginia) Region. The following is an example of an AWS console sign-in event: { "id": "6f87d04b-9f74-4f04-a780-7acf4b0a9b38", "detail-type": "AWS Console Sign In via CloudTrail", "source": "aws.signin", "account": "123456789012", "time": "2016-01-05T18:21:27Z", "region": "us-east-1", "resources": [], "detail": { "eventVersion": "1.02", "userIdentity": { "type": "Root", "principalId": "123456789012", "arn": "arn:aws:iam::123456789012:root", "accountId": "123456789012" }, "eventTime": "2016-01-05T18:21:27Z", "eventSource": "signin.amazonaws.com", "eventName": "ConsoleLogin", "awsRegion": "us-east-1", "sourceIPAddress": "0.0.0.0", "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36", "requestParameters": null, "responseElements": { "ConsoleLogin": "Success" }, "additionalEventData": { "LoginTo": "https://console.aws.amazon.com/console/home? state=hashArgs%23&isauthcode=true", "MobileVersion": "No", 37 Amazon CloudWatch Events User Guide Scheduled Events "MFAUsed": "No" }, "eventID": "324731c0-64b3-4421-b552-dfc3c27df4f6", "eventType": "AwsConsoleSignIn" } } Scheduled Events The following is an example of a scheduled event: { "id": "53dc4d37-cffa-4f76-80c9-8b7d4a4d2eaa", "detail-type": "Scheduled Event", "source": "aws.events", "account": "123456789012", "time": "2015-10-08T16:53:06Z", "region": "us-east-1", "resources": [ "arn:aws:events:us-east-1:123456789012:rule/ MyScheduledRule" ], "detail": {} } 38 Amazon CloudWatch Events User Guide Authentication Authentication and Access Control for Amazon CloudWatch Events Access to Amazon CloudWatch Events requires credentials that AWS can use to authenticate your requests. Those credentials must have permissions to access AWS resources, such as retrieving event data from other AWS resources. The following sections provide details on how you can use AWS Identity and Access Management (IAM) and CloudWatch Events to help secure your resources by controlling who can access them: • Authentication (p. 39) • Access Control (p. 40) Authentication You can access AWS as any of the following types of identities: • AWS account root user – When you sign up for AWS, you provide an email address and password that is associated with your AWS account. These are your root credentials and they provide complete access to all of your AWS resources. Important For security reasons, we recommend that you use the root credentials only to create an administrator user, which is an IAM user with full permissions to your AWS account. Then, you can use this administrator user to create other IAM users and roles with limited permissions. For more information, see IAM Best Practices and Creating an Admin User and Group in the IAM User Guide. • IAM user – An IAM user is simply an identity within your AWS account that has specific custom permissions (for example, permissions to send event data to a target in CloudWatch Events). You can use an IAM user name and password to sign in to secure AWS webpages like the AWS Management Console, AWS Discussion Forums, or the AWS Support Center. 39 Amazon CloudWatch Events User Guide Access Control In addition to a user name and password, you can also generate access keys for each user. You can use these keys when you access AWS services programmatically, either through one of the several SDKs or by using the AWS Command Line Interface (AWS CLI). The SDK and CLI tools use the access keys to cryptographically sign your request. If you don’t use the AWS tools, you must sign the request yourself. CloudWatch Events supports Signature Version 4, a protocol for authenticating inbound API requests. For more information about authenticating requests, see Signature Version 4 Signing Process in the AWS General Reference. • IAM role – An IAM role is another IAM identity you can create in your account that has specific permissions. It is similar to an IAM user, but it is not associated with a specific person. An IAM role enables you to obtain temporary access keys that can be used to access AWS services and resources. IAM roles with temporary credentials are useful in the following situations: • Federated user access – Instead of creating an IAM user, you can use preexisting user identities from AWS Directory Service, your enterprise user directory, or a web identity provider. These are known as federated users. AWS assigns a role to a federated user when access is requested through an identity provider. For more information about federated users, see Federated Users and Roles in the IAM User Guide. • Cross-account access – You can use an IAM role in your account to grant another AWS account permissions to access your account’s resources. For an example, see Tutorial: Delegate Access Across AWS Accounts Using IAM Roles in the IAM User Guide. • AWS service access – You can use an IAM role in your account to grant an AWS service permissions to access your account’s resources. For example, you can create a role that allows Amazon Redshift to access an Amazon S3 bucket on your behalf and then load data stored in the bucket into an Amazon Redshift cluster. For more information, see Creating a Role to Delegate Permissions to an AWS Service in the IAM User Guide. • Applications running on Amazon EC2 – Instead of storing access keys within the EC2 instance for use by applications running on the instance and making AWS API requests, you can use an IAM role to manage temporary credentials for these applications. To assign an AWS role to an EC2 instance and make it available to all of its applications, you can create an instance profile that is attached to the instance. An instance profile contains the role and enables programs running on the EC2 instance to get temporary credentials. For more information, see Using Roles for Applications on Amazon EC2 in the IAM User Guide. Access Control You can have valid credentials to authenticate your requests, but unless you have permissions you cannot create or access CloudWatch Events resources. For example, you must have permissions to invoke AWS Lambda, Amazon Simple Notification Service (Amazon SNS), and Amazon Simple Queue Service (Amazon SQS) targets associated with your CloudWatch Events rules. The following sections describe how to manage permissions for CloudWatch Events. We recommend that you read the overview first. • Overview of Managing Access Permissions to Your CloudWatch Events Resources (p. 41) • Using Identity-Based Policies (IAM Policies) for CloudWatch Events (p. 44) 40 Amazon CloudWatch Events User Guide Overview of Managing Access • Using Resource-Based Policies for CloudWatch Events (p. 50) • CloudWatch Events Permissions Reference (p. 53) Overview of Managing Access Permissions to Your CloudWatch Events Resources Every AWS resource is owned by an AWS account, and permissions to create or access a resource are governed by permissions policies. An account administrator can attach permissions policies to IAM identities (that is, users, groups, and roles), and some services (such as AWS Lambda) also support attaching permissions policies to resources. Note An account administrator (or administrator user) is a user with administrator privileges. For more information, see IAM Best Practices in the IAM User Guide. When granting permissions, you decide who is getting the permissions, the resources they get permissions for, and the specific actions that you want to allow on those resources. Topics • CloudWatch Events Resources and Operations (p. 41) • Understanding Resource Ownership (p. 42) • Managing Access to Resources (p. 42) • Specifying Policy Elements: Actions, Effects, and Principals (p. 44) • Specifying Conditions in a Policy (p. 44) CloudWatch Events Resources and Operations In CloudWatch Events, the primary resource is a rule. CloudWatch Events supports other resources that can be used with the primary resource, such as events. These are referred to as subresources. These resources and subresources have unique Amazon Resource Names (ARNs) associated with them. For more information about ARNs, see Amazon Resource Names (ARN) and AWS Service Namespaces in the Amazon Web Services General Reference. Resource Type ARN Format Rule arn:aws:events:region:account:rule/rule-name All CloudWatch Events resources arn:aws:events:* All CloudWatch Events resources owned by the specified account in the specified region arn:aws:events:region:account:* Note Most services in AWS treat a colon (:) or a forward slash (/) as the same character in ARNs. However, CloudWatch Events uses an exact match in event patterns and rules. Be sure to use the correct ARN characters when creating event patterns so that they match the ARN syntax in the event you want to match. For example, you can indicate a specific rule (myRule) in your statement using its ARN as follows: 41 Amazon CloudWatch Events User Guide Understanding Resource Ownership "Resource": "arn:aws:events:us-east-1:123456789012:rule/myRule" You can also specify all rules that belong to a specific account by using the asterisk (*) wildcard as follows: "Resource": "arn:aws:events:us-east-1:123456789012:rule/*" To specify all resources, or if a specific API action does not support ARNs, use the asterisk (*) wildcard in the Resource element as follows: "Resource": "*" Some CloudWatch Events API actions accept multiple resources (e.g., PutTargets). To specify multiple resources in a single statement, separate their ARNs with commas, as follows: "Resource": ["arn1", "arn2"] CloudWatch Events provides a set of operations to work with the CloudWatch Events resources. For a list of available operations, see CloudWatch Events Permissions Reference (p. 53). Understanding Resource Ownership The AWS account owns the resources that are created in the account, regardless of who created the resources. Specifically, the resource owner is the AWS account of the principal entity (that is, the root account, an IAM user, or an IAM role) that authenticates the resource creation request. The following examples illustrate how this works: • If you use the root account credentials of your AWS account to create a rule, your AWS account is the owner of the CloudWatch Events resource. • If you create an IAM user in your AWS account and grant permissions to create CloudWatch Events resources to that user, the user can create CloudWatch Events resources. However, your AWS account, to which the user belongs, owns the CloudWatch Events resources. • If you create an IAM role in your AWS account with permissions to create CloudWatch Events resources, anyone who can assume the role can create CloudWatch Events resources. Your AWS account, to which the role belongs, owns the CloudWatch Events resources. Managing Access to Resources A permissions policy describes who has access to what. The following section explains the available options for creating permissions policies. Note This section discusses using IAM in the context of CloudWatch Events. It doesn't provide detailed information about the IAM service. For complete IAM documentation, see What Is IAM? in the IAM User Guide. For information about IAM policy syntax and descriptions, see AWS IAM Policy Reference in the IAM User Guide. Policies attached to an IAM identity are referred to as identity-based policies (IAM polices) and policies attached to a resource are referred to as resource-based policies. CloudWatch Events supports both identity-based (IAM policies) and resource-based policies. Topics • Identity-Based Policies (IAM Policies) (p. 43) 42 Amazon CloudWatch Events User Guide Managing Access to Resources • Resource-Based Policies (p. 43) Identity-Based Policies (IAM Policies) You can attach policies to IAM identities. For example, you can do the following: • Attach a permissions policy to a user or a group in your account – To grant a user permissions to view rules in the CloudWatch console, you can attach a permissions policy to a user or group that the user belongs to. • Attach a permissions policy to a role (grant cross-account permissions) – You can attach an identity-based permissions policy to an IAM role to grant cross-account permissions. For example, the administrator in Account A can create a role to grant cross-account permissions to another AWS account (for example, Account B) or an AWS service as follows: 1. Account A administrator creates an IAM role and attaches a permissions policy to the role that grants permissions on resources in Account A. 2. Account A administrator attaches a trust policy to the role identifying Account B as the principal who can assume the role. 3. Account B administrator can then delegate permissions to assume the role to any users in Account B. Doing this allows users in Account B to create or access resources in Account A. The principal in the trust policy an also be an AWS service principal if you want to grant an AWS service permissions to assume the role. For more information about using IAM to delegate permissions, see Access Management in the IAM User Guide. The following policy allows CloudWatch Events to relay events to the streams in Amazon Kinesis streams in your account. { "Version": "2012-10-17", "Statement": [ { "Sid": "CloudWatchEventsInvocationAccess", "Effect": "Allow", "Action": [ "kinesis:PutRecord" ], "Resource": "*" } ] } You can create specific IAM policies to restrict the calls and resources that users in your account have access to, and then attach those policies to IAM users. For more information about how to create IAM roles and to explore example IAM policy statements for CloudWatch Events, see Overview of Managing Access Permissions to Your CloudWatch Events Resources (p. 41). Resource-Based Policies When a rule is triggered in CloudWatch Events, all the targets associated with the rule are invoked. Invocation means invoking the AWS Lambda functions, publishing to the Amazon SNS topics, and relaying the event to the Amazon Kinesis streams. In order to be able to make API calls against the resources you own, CloudWatch Events needs the appropriate permissions. For Lambda, Amazon SNS, and Amazon SQS resources, CloudWatch Events relies on resource-based policies. For Amazon Kinesis streams, CloudWatch Events relies on IAM roles. 43 Amazon CloudWatch Events User Guide Specifying Policy Elements: Actions, Effects, and Principals For more information about how to create IAM roles and to explore example resource-based policy statements for CloudWatch Events, see Using Resource-Based Policies for CloudWatch Events (p. 50). Specifying Policy Elements: Actions, Effects, and Principals For each CloudWatch Events resource, the service defines a set of API operations. To grant permissions for these API operations, CloudWatch Events defines a set of actions that you can specify in a policy. Some API operations can require permissions for more than one action in order to perform the API operation. For more information about resources and API operations, see CloudWatch Events Resources and Operations (p. 41) and CloudWatch Events Permissions Reference (p. 53). The following are the basic policy elements: • Resource – You use an Amazon Resource Name (ARN) to identify the resource that the policy applies to. For more information, see CloudWatch Events Resources and Operations (p. 41). • Action – You use action keywords to identify resource operations that you want to allow or deny. For example, the events:Describe permission allows the user permissions to perform the Describe operation. • Effect – You specify the effect, either allow or deny, when the user requests the specific action. If you don't explicitly grant access to (allow) a resource, access is implicitly denied. You can also explicitly deny access to a resource, which you might do to make sure that a user cannot access it, even if a different policy grants access. • Principal – In identity-based policies (IAM policies), the user that the policy is attached to is the implicit principal. For resource-based policies, you specify the user, account, service, or other entity that you want to receive permissions (applies to resource-based policies only). To learn more about IAM policy syntax and descriptions, see AWS IAM Policy Reference in the IAM User Guide. For a table showing all of the CloudWatch Events API actions and the resources that they apply to, see CloudWatch Events Permissions Reference (p. 53). Specifying Conditions in a Policy When you grant permissions, you can use the access policy language to specify the conditions when a policy should take effect. For example, you might want a policy to be applied only after a specific date. For more information about specifying conditions in a policy language, see Condition in the IAM User Guide. To express conditions, you use predefined condition keys. There are AWS-wide condition keys and CloudWatch Events–specific keys that you can use as appropriate. For a complete list of AWS-wide keys, see Available Keys for Conditions in the IAM User Guide. For a complete list of CloudWatch Events–specific keys, see Using IAM Policy Conditions for Fine-Grained Access Control (p. 55). Using Identity-Based Policies (IAM Policies) for CloudWatch Events This topic provides examples of identity-based policies in which an account administrator can attach permissions policies to IAM identities (that is, users, groups, and roles). 44 Amazon CloudWatch Events User Guide Permissions Required to Use the CloudWatch Console The following shows an example of a permissions policy that allows a user to put event data into Amazon Kinesis. { "Version": "2012-10-17", "Statement": [ { "Sid": "CloudWatchEventsInvocationAccess", "Effect": "Allow", "Action": [ "kinesis:PutRecord" ], "Resource": "*" } ] } The sections in this topic cover the following: Topics • Permissions Required to Use the CloudWatch Console (p. 45) • AWS Managed (Predefined) Policies for CloudWatch Events (p. 46) • Customer Managed Policy Examples (p. 47) Permissions Required to Use the CloudWatch Console For a user to work with CloudWatch Events in the CloudWatch console, that user must have a minimum set of permissions that allows the user to describe other AWS resources for their AWS account. In order to use CloudWatch Events in the CloudWatch console, you must have permissions from the following services: • Automation • Auto Scaling • CloudTrail • CloudWatch • CloudWatch Events • IAM • Amazon Kinesis • Lambda • Amazon SNS • Amazon SWF If you create an IAM policy that is more restrictive than the minimum required permissions, the console won't function as intended for users with that IAM policy. To ensure that those users can still use the CloudWatch console, also attach the CloudWatchEventsReadOnlyAccess managed policy to the user, as described in AWS Managed (Predefined) Policies for CloudWatch Events (p. 46). You don't need to allow minimum console permissions for users that are making calls only to the AWS CLI or the CloudWatch API. The full set of permissions required to work with the CloudWatch console are listed below: 45 Amazon CloudWatch Events User Guide AWS Managed (Predefined) Policies for CloudWatch Events • automation:CreateAction • automation:DescribeAction • automation:UpdateAction • autoscaling:DescribeAutoScalingGroups • cloudtrail:DescribeTrails • ec2:DescribeInstances • ec2:DescribeVolumes • events:DeleteRule • events:DescribeRule • events:DisableRule • events:EnableRule • events:ListRuleNamesByTarget • events:ListRules • events:ListTargetsByRule • events:PutEvents • events:PutRule • events:PutTargets • events:RemoveTargets • events:TestEventPattern • iam:ListRoles • kinesis:ListStreams • lambda:AddPermission • lambda:ListFunctions • lambda:RemovePermission • sns:GetTopicAttributes • sns:ListTopics • sns:SetTopicAttributes • swf:DescribeAction • swf:ReferenceAction • swf:RegisterAction • swf:RegisterDomain • swf:UpdateAction AWS Managed (Predefined) Policies for CloudWatch Events AWS addresses many common use cases by providing standalone IAM policies that are created and administered by AWS. Managed policies grant necessary permissions for common use cases so you can avoid having to investigate what permissions are needed. For more information, see AWS Managed Policies in the IAM User Guide. The following AWS managed policies, which you can attach to users in your account, are specific to CloudWatch Events: • CloudWatchEventsFullAccess – Grants full access to CloudWatch Events. • CloudWatchEventsInvocationAccess – Allows CloudWatch Events to relay events to the streams in Amazon Kinesis Streams in your account. • CloudWatchEventsReadOnlyAccess – Grants read-only access to CloudWatch Events. 46 Amazon CloudWatch Events User Guide Customer Managed Policy Examples • CloudWatchEventsBuiltInTargetExecutionAccess – Allows built-in targets in CloudWatch Events to perform Amazon EC2 actions on your behalf. IAM Roles for Sending Events In order for CloudWatch Events to relay events to your Amazon Kinesis stream targets, you must create an IAM role. To create an IAM role for sending CloudWatch Events 1. Open the Identity and Access Management (IAM) console at https://console.aws.amazon.com/ iam/. 2. Follow the steps in Creating a Role to Delegate Permissions to an AWS Service in the IAM User Guide to create an IAM role. As you follow the steps to create a role, do the following: • In Role Name, use a name that is unique within your AWS account (for example, CloudWatchEventsSending). • In Select Role Type, choose AWS Service Roles, and then choose Amazon CloudWatch Events. This grants CloudWatch Events permissions to assume the role. • In Attach Policy, choose CloudWatchEventsInvocationAccess. You can also create your own custom IAM policies to allow permissions for CloudWatch Events actions and resources. You can attach these custom policies to the IAM users or groups that require those permissions. For more information about IAM policies, see Overview of IAM Policies in the IAM User Guide. For more information about managing and creating custom IAM policies, see Managing IAM Policies in the IAM User Guide. Customer Managed Policy Examples In this section, you can find example user policies that grant permissions for various CloudWatch Events actions. These policies work when you are using the CloudWatch Events API, AWS SDKs, or the AWS CLI. Note All examples use the US West (Oregon) Region (us-west-2) and contain fictitious account IDs. You can use the following sample IAM policies listed to limit the CloudWatch Events access for your IAM users and roles. Examples • Example 1: CloudWatchEventsBuiltInTargetExecutionAccess (p. 47) • • • • Example 2: CloudWatchEventsInvocationAccess (p. 48) Example 3: CloudWatchEventsConsoleAccess (p. 48) Example 4: CloudWatchEventsFullAccess (p. 49) Example 5: CloudWatchEventsReadOnlyAccess (p. 49) Example 1: CloudWatchEventsBuiltInTargetExecutionAccess The following policy allows built-in targets in CloudWatch Events to perform Amazon EC2 actions on your behalf. { 47 Amazon CloudWatch Events User Guide Customer Managed Policy Examples "Version": "2012-10-17", "Statement": [ { "Sid": "CloudWatchEventsBuiltInTargetExecutionAccess", "Effect": "Allow", "Action": [ "ec2:Describe*", "ec2:RebootInstances", "ec2:StopInstances", "ec2:TerminateInstances", "ec2:CreateSnapshot" ], "Resource": "*" } ] } Example 2: CloudWatchEventsInvocationAccess The following policy allows CloudWatch Events to relay events to the streams in Amazon Kinesis streams in your account. { "Version": "2012-10-17", "Statement": [ { "Sid": "CloudWatchEventsInvocationAccess", "Effect": "Allow", "Action": [ "kinesis:PutRecord" ], "Resource": "*" } ] } Example 3: CloudWatchEventsConsoleAccess The following policy ensures that IAM users can use the CloudWatch Events console. { "Version": "2012-10-17", "Statement": [ { "Sid": "CloudWatchEventsConsoleAccess", "Effect": "Allow", "Action": [ "automation:CreateAction", "automation:DescribeAction", "automation:UpdateAction", "autoscaling:DescribeAutoScalingGroups", "cloudtrail:DescribeTrails", "ec2:DescribeInstances", "ec2:DescribeVolumes", "events:*", "iam:ListRoles", 48 Amazon CloudWatch Events User Guide Customer Managed Policy Examples "kinesis:ListStreams", "lambda:AddPermission", "lambda:ListFunctions", "lambda:RemovePermission", "sns:GetTopicAttributes", "sns:ListTopics", "sns:SetTopicAttributes", "swf:DescribeAction", "swf:ReferenceAction", "swf:RegisterAction", "swf:RegisterDomain", "swf:UpdateAction" ], "Resource": "*" }, { "Sid": "IAMPassRoleForCloudWatchEvents", "Effect": "Allow", "Action": "iam:PassRole", "Resource": [ "arn:aws:iam::*:role/AWS_Events_Invoke_Targets", "arn:aws:iam::*:role/AWS_Events_Actions_Execution" ] } ] } Example 4: CloudWatchEventsFullAccess The following policy allows performing actions against CloudWatch Events through the AWS CLI and SDK. { "Version": "2012-10-17", "Statement": [ { "Sid": "CloudWatchEventsFullAccess", "Effect": "Allow", "Action": "events:*", "Resource": "*" }, { "Sid": "IAMPassRoleForCloudWatchEvents", "Effect": "Allow", "Action": "iam:PassRole", "Resource": "arn:aws:iam::*:role/AWS_Events_Invoke_Targets" } ] } Example 5: CloudWatchEventsReadOnlyAccess The following policy provides read-only access to CloudWatch Events. { "Version": "2012-10-17", "Statement": [ 49 Amazon CloudWatch Events User Guide Using Resource-Based Policies { "Sid": "CloudWatchEventsReadOnlyAccess", "Effect": "Allow", "Action": [ "events:Describe*", "events:List*", "events:TestEventPattern" ], "Resource": "*" } ] } Using Resource-Based Policies for CloudWatch Events When a rule is triggered in CloudWatch Events, all the targets associated with the rule are invoked. Invocation means invoking the AWS Lambda functions, publishing to the Amazon SNS topics, and relaying the event to the Amazon Kinesis streams. In order to be able to make API calls against the resources you own, CloudWatch Events needs the appropriate permissions. For Lambda, Amazon SNS, and Amazon SQS resources, CloudWatch Events relies on resource-based policies. For Amazon Kinesis streams, CloudWatch Events relies on IAM roles. You can use the following permissions to invoke the targets associated with your CloudWatch Events rules. The procedures below use the AWS CLI to add permissions to your targets. For information about how to install and configure the AWS CLI, see Getting Set Up with the AWS Command Line Interface in the AWS Command Line Interface User Guide. Topics • AWS Lambda Permissions (p. 50) • Amazon SNS Permissions (p. 51) • Amazon SQS Permissions (p. 52) AWS Lambda Permissions To invoke your AWS Lambda function using a CloudWatch Events rule, add the following permission to the policy of your Lambda function. { "Effect": "Allow", "Action": "lambda:InvokeFunction", "Resource": "arn:aws:lambda:region:account-id:function:function-name", "Principal": { "Service": "events.amazonaws.com" }, "Condition": { "ArnLike": { "AWS:SourceArn": "arn:aws:events:region:account-id:rule/rule-name" } }, "Sid": "TrustCWEToInvokeMyLambdaFunction" } 50 Amazon CloudWatch Events User Guide Amazon SNS Permissions To add permissions that enable CloudWatch Events to invoke Lambda functions • At a command prompt, enter the following command: aws lambda add-permission --statement-id "TrustCWEToInvokeMyLambdaFunction" \ --action "lambda:InvokeFunction" \ --principal "events.amazonaws.com" \ --function-name "arn:aws:lambda:region:account-id:function:function-name" \ --source-arn "arn:aws:events:region:account-id:rule/rule-name" For more information about setting permissions that enable CloudWatch Events to invoke Lambda functions, see AddPermission and Using Lambda with Scheduled Events in the AWS Lambda Developer Guide. Amazon SNS Permissions To allow CloudWatch Events to publish an Amazon SNS topic, use the aws sns get-topicattributes and the aws sns set-topic-attributes commands. To add permissions that enable CloudWatch Events to publish SNS topics 1. First, list SNS topic attributes. At a command prompt, type the following: aws sns get-topic-attributes --topic-arn "arn:aws:sns:region:accountid:topic-name" The command returns all attributes of the SNS topic. The following example shows the result of a newly-created SNS topic. { "Attributes": { "SubscriptionsConfirmed": "0", "DisplayName": "", "SubscriptionsDeleted": "0", "EffectiveDeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy \":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3, \"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0, \"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}", "Owner": "account-id", "Policy": "{\"Version\":\"2012-10-17\",\"Id\": \"__default_policy_ID\",\"Statement\":[{\"Sid\":\"__default_statement_ID \",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\": [\"SNS:GetTopicAttributes\",\"SNS:SetTopicAttributes\",\"SNS:AddPermission \",\"SNS:RemovePermission\",\"SNS:DeleteTopic\",\"SNS:Subscribe\", \"SNS:ListSubscriptionsByTopic\",\"SNS:Publish\",\"SNS:Receive\"], \"Resource\":\"arn:aws:sns:region:account-id:topic-name\",\"Condition\": {\"StringEquals\":{\"AWS:SourceOwner\":\"account-id\"}}}]}", "TopicArn": "arn:aws:sns:region:account-id:topic-name", "SubscriptionsPending": "0" } } 2. Next, convert the following statement to a string and add it to the "Statement" collection inside the "Policy" attribute. 51 Amazon CloudWatch Events User Guide Amazon SQS Permissions { "Sid": "TrustCWEToPublishEventsToMyTopic", "Effect": "Allow", "Principal": { "Service": "events.amazonaws.com" }, "Action": "sns:Publish", "Resource": "arn:aws:sns:region:account-id:topic-name" } After you convert the statement to a string, it should look like the following: {\"Sid\":\"TrustCWEToPublishEventsToMyTopic\",\"Effect\":\"Allow \",\"Principal\":{\"Service\":\"events.amazonaws.com\"},\"Action\": \"sns:Publish\",\"Resource\":\"arn:aws:sns:region:account-id:topic-name\"} 3. After you've added the statement string to the statement collection, use the aws sns settopic-attributes command to set the new policy. aws sns set-topic-attributes --topic-arn "arn:aws:sns:region:accountid:topic-name" \ --attribute-name Policy \ --attribute-value "{\"Version\":\"2012-10-17\",\"Id\": \"__default_policy_ID\",\"Statement\":[{\"Sid\":\"__default_statement_ID \",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\": [\"SNS:GetTopicAttributes\",\"SNS:SetTopicAttributes\",\"SNS:AddPermission \",\"SNS:RemovePermission\",\"SNS:DeleteTopic\",\"SNS:Subscribe\", \"SNS:ListSubscriptionsByTopic\",\"SNS:Publish\",\"SNS:Receive\"], \"Resource\":\"arn:aws:sns:region:account-id:topic-name\",\"Condition \":{\"StringEquals\":{\"AWS:SourceOwner\":\"account-id\"}}}, {\"Sid\": \"TrustCWEToPublishEventsToMyTopic\",\"Effect\":\"Allow\",\"Principal \":{\"Service\":\"events.amazonaws.com\"},\"Action\":\"sns:Publish\", \"Resource\":\"arn:aws:sns:region:account-id:topic-name\"}]}" For more information, see the SetTopicAttributes action in the Amazon Simple Notification Service API Reference. Amazon SQS Permissions To allow a CloudWatch Events rule to invoke an Amazon SQS queue, use the aws sqs get-queueattributes and the aws sqs set-queue-attributes commands. To add permissions that enable CloudWatch Events rules to invoke an SQS queue 1. First, list SQS queue attributes. At a command prompt, type the following: aws sqs get-queue-attributes \ --queue-url https://sqs.region.amazonaws.com/account-id/queue-name \ --attribute-names Policy For a newly-created SQS queue, its policy is empty by default. In addition to adding a statement, you also need to create a policy that contains this statement. 2. The following statement enables CloudWatch Events to send messages to an SQS queue: 52 Amazon CloudWatch Events User Guide CloudWatch Events Permissions Reference { "Sid": "TrustCWEToSendEventsToMyQueue", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:region:account-id:queue-name", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:events:region:account-id:rule/rule-name" } } } 3. Next, convert the statement above into a string. After you convert the policy to a string, it should look like the following: {\"Sid\": \"TrustCWEToSendEventsToMyQueue\", \"Effect\": \"Allow\", \"Principal\": {\"AWS\": \"*\"}, \"Action\": \"sqs:SendMessage\", \"Resource\": \"arn:aws:sqs:region:account-id:queue-name\", \"Condition \": {\"ArnEquals\": {\"aws:SourceArn\": \"arn:aws:events:region:accountid:rule/rule-name\"}} 4. Create a file called set-queue-attributes.json with the following content: { "Policy": "{\"Version\":\"2012-10-17\",\"Id\": \"arn:aws:sqs:region:account-id:queue-name/SQSDefaultPolicy\",\"Statement \":[{\"Sid\": \"TrustCWEToSendEventsToMyQueue\", \"Effect\": \"Allow \", \"Principal\": {\"AWS\": \"*\"}, \"Action\": \"sqs:SendMessage\", \"Resource\": \"arn:aws:sqs:region:account-id:queue-name\", \"Condition \": {\"ArnEquals\": {\"aws:SourceArn\": \"arn:aws:events:region:accountid:rule/rule-name\"}}}]}" } 5. Set the policy attribute using the set-queue-attributes.json file as the input. At a command prompt, type: aws sqs set-queue-attributes \ --queue-url https://sqs.region.amazonaws.com/account-id/queue-name \ --attributes file://set-queue-attributes.json If the SQS queue already has a policy, you need to copy the original policy and combine it with a new statement in the set-queue-attributes.json file and run the above command to update the policy. For more information, see Amazon SQS Policy Examples in the Amazon Simple Queue Service Developer Guide. CloudWatch Events Permissions Reference When you are setting up Access Control (p. 40) and writing permissions policies that you can attach to an IAM identity (identity-based policies), you can use the following table as a reference. The table 53 Amazon CloudWatch Events User Guide CloudWatch Events Permissions Reference lists each CloudWatch Events API operation and the corresponding actions for which you can grant permissions to perform the action. You specify the actions in the policy's Action field, and you specify a wildcard character (*) as the resource value in the policy's Resource field. You can use AWS-wide condition keys in your CloudWatch Events policies to express conditions. For a complete list of AWS-wide keys, see Available Keys in the IAM User Guide. Note To specify an action, use the events: prefix followed by the API operation name. For example: events:PutRule, events:EnableRule, or events:* (for all CloudWatch Events actions). To specify multiple actions in a single statement, separate them with commas as follows: "Action": ["events:action1", "events:action2"] You can also specify multiple actions using wildcards. For example, you can specify all actions whose name begins with the word "Put" as follows: "Action": "events:Put*" To specify all CloudWatch Events API actions, use the * wildcard as follows: "Action": "events:*" The actions you can specify in an IAM policy for use with CloudWatch Events are listed below. CloudWatch Events API Operations and Required Permissions for Actions CloudWatch Events API Operations Required Permissions (API Actions) DeleteRule events:DeleteRule Required to delete a rule. DescribeRule events:DescribeRule Required to list the details about a rule. DisableRule events:DisableRule Required to disable a rule. EnableRule events:EnableRule Required to enable a rule. ListRuleNamesByTarget events:ListRuleNamesByTarget Required to list rules associated with a target. ListRules events:ListRules Required to list all rules in your account. ListTargetsByRule events:ListTargetsByRule Required to list all targets associated with a rule. 54 Amazon CloudWatch Events User Guide Using Conditions CloudWatch Events API Operations Required Permissions (API Actions) PutEvents events:PutEvents Required to add custom events that can be matched to rules. PutRule events:PutRule Required to create or update a rule. PutTargets events:PutTargets Required to add targets to a rule. RemoveTargets events:RemoveTargets Required to remove a target from a rule. TestEventPattern events:TestEventPattern Required to test an event pattern against a given event. Using IAM Policy Conditions for Fine-Grained Access Control When you grant permissions, you can use the access policy language to specify the conditions when a policy should take effect. In a policy statement, you can optionally specify conditions that control when it is in effect. Each condition contains one or more key-value pairs. Condition keys are not casesensitive. For example, you might want a policy to be applied only after a specific date. If you specify multiple conditions, or multiple keys in a single condition, they are evaluated using a logical AND operation. If you specify a single condition with multiple values for one key, they are evaluated using a logical OR operation. For permission to be granted, all conditions must be met. You can also use placeholders when you specify conditions. For more information, see Policy Variables in the IAM User Guide. For more information about specifying conditions in an access policy language, see Condition in the IAM User Guide. By default, IAM users and roles can't access the events in your account. To consume events, a user must be authorized for the PutRule API action. If you allow an IAM user or role for the events:PutRule action in their policy, then they will be able to create a rule that matches certain events. You must add a target to a rule, otherwise, a rule without a target does nothing except publish a CloudWatch metric when it matches an incoming event. Your IAM user or role must have permissions for the events:PutTargets action. It is possible to limit access to the events by scoping the authorization to specific sources and types of events (using the events:source and events:detail-type condition keys). You can provide a condition in the policy statement of the IAM user or role that allows them to create a rule that only matches a specific set of sources and detail types. For a list showing all of condition key values and the CloudWatch Events actions and resources that they apply to, see Using IAM Policy Conditions for Fine-Grained Access Control (p. 55). Similarly, through setting conditions in your policy statements, you can decide which specific resources in your accounts can be added to a rule by an IAM user or role (using the events:TargetArn 55 Amazon CloudWatch Events User Guide Using Conditions condition key). For example, if you turn on CloudTrail in your account and you have a CloudTrail stream, CloudTrail events are also available to the users in your account through CloudWatch Events. If you want your users to use CloudWatch Events and access all the events but the CloudTrail events, you can add a deny statement on the PutRule API action with a condition that any rule created by that user or role cannot match the CloudTrail event type. For CloudTrail events, you can limit the access to a specific principal that the original API call was originated from (using the events:detail.userIdentity.principalId condition key). For example, you can allow a user to see all the CloudTrail events, except the ones that are made by a specific IAM role in your account that you use for auditing or forensics. Condition Key Key/Value Pair Evaluation Types events:source "events:source":"source " Source, Null Where source is the literal string for the source field of the event such as "aws.ec2" and "aws.s3". events:detail-type "events:detailtype":"detail-type " Detail Type, Null Where detail-type is the literal string for the detail-type field of the event such as "AWS API Call via CloudTrail" and "EC2 Instance State-change Notification". events: "events: Principal Id, Null detail.userIdentity.principalId detail.userIdentity.principalId":"principalid" Where principal-id is the literal string for the detail.userIdentity.principalId field of the event with detail-type "AWS API Call via CloudTrail" such as "AROAIDPPEZS35WEXAMPLE:AssumedRoleSessionName.". events:TargetArn "events:TargetArn":"target- ARN, Null arn " Where target-arn is the ARN of the target that can be put to a rule such as "arn:aws:lambda:*:*:function:*". For example policy statements for CloudWatch Events, see Overview of Managing Access Permissions to Your CloudWatch Events Resources (p. 41). Topics • Example 1: Limit Access to a Specific Source (p. 57) • Example 2: Define Multiple Sources That Can Be Used in an Event Pattern Individually (p. 58) • Example 3: Define a Source and a DetailType That Can Be Used in an Event Pattern (p. 59) • Example 4: Ensure That the Source is Defined in the Event Pattern (p. 60) • Example 5: Define a List of Allowed Sources in an Event Pattern With Multiple Sources (p. 61) 56 Amazon CloudWatch Events User Guide Example 1: Limit Access to a Specific Source • Example 6: Ensure That AWS CloudTrail Events for API Calls From a Certain PrincipalId Are Consumed (p. 62) Example 1: Limit Access to a Specific Source The following example policies can be attached to an IAM user. Policy A allows the PutRule API action for all events, whereas Policy B allows PutRule only if the event pattern of the rule being created matches Amazon EC2 events. Policy A:—allow any events { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowPutRuleForAllEvents", "Effect": "Allow", "Action": "events:PutRule", "Resource": "*" } ] } Policy B:—allow events only from Amazon EC2 { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowPutRuleForAllEC2Events", "Effect": "Allow", "Action": "events:PutRule", "Resource": "*", "Condition": { "StringEquals": { "events:source": "aws.ec2" } } } ] } EventPattern is a mandatory argument to PutRule. Hence, if the user with Policy B calls PutRule with an event pattern like the following: { "source": [ "aws.ec2" ] } The rule would be created because the policy allows for this specific source, that is, "aws.ec2". However, if the user with Policy B calls PutRulewith an event pattern like the following: { "source": [ "aws.s3" ] } 57 Amazon CloudWatch Events User Guide Example 2: Define Multiple Sources That Can Be Used in an Event Pattern Individually The rule creation would be denied because the policy does not allow for this specific source, that is, "aws.s3". Essentially, the user with Policy B is only allowed to create a rule that would match the events originating from Amazon EC2; hence, they are only allowed access to the events from Amazon EC2. See the following table for a comparison of Policy A and Policy B: Event Pattern { Allowed by Policy A Allowed by Policy B Yes Yes Yes No (Source aws.s3 is not allowed) Yes Yes Yes No (Source must be specified) "source": [ "aws.ec2" ] } { "source": [ "aws.ec2", "aws.s3" ] } { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ] } { "detail-type": [ "EC2 Instance State-change Notification" ] } Example 2: Define Multiple Sources That Can Be Used in an Event Pattern Individually The following policy allows events from Amazon EC2 or CloudWatch Events. In other words, it allows an IAM user or role to create a rule where the source in the EventPattern is specified as either "aws.ec2" or "aws.ecs". Not defining the source results in a "deny". { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowPutRuleIfSourceIsEC2OrECS", "Effect": "Allow", "Action": "events:PutRule", "Resource": "*", "Condition": { 58 Amazon CloudWatch Events User Guide Example 3: Define a Source and a DetailType That Can Be Used in an Event Pattern "StringEquals": { "events:source": [ "aws.ec2", "aws.ecs" ] } } } ] } See the following table for examples of event patterns that would be allowed or denied by this policy: Event Pattern Allowed by the Policy Yes { "source": [ "aws.ec2" ] } Yes { "source": [ "aws.ecs" ] } No { "source": [ "aws.s3" ] } No { "source": [ "aws.ec2", "aws.ecs" ] } No { "detail-type": [ "AWS API Call via CloudTrail" ] } Example 3: Define a Source and a DetailType That Can Be Used in an Event Pattern The following policy allows events only from the aws.ec2 source with DetailType equal to EC2 instance state change notification. { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowPutRuleIfSourceIsEC2AndDetailTypeIsInstanceStateChangeNotification", "Effect": "Allow", "Action": "events:PutRule", "Resource": "*", "Condition": { 59 Amazon CloudWatch Events User Guide Example 4: Ensure That the Source is Defined in the Event Pattern "StringEquals": { "events:source": "aws.ec2", "events:detail-type": "EC2 Instance State-change Notification" } } } ] } See the following table for examples of event patterns that would be allowed or denied by this policy: Event Pattern Allowed by the Policy No { "source": [ "aws.ec2" ] } No { "source": [ "aws.ecs" ] } Yes { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ] } No { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance Health Failed" ] } No { "detail-type": [ "EC2 Instance State-change Notification" ] } Example 4: Ensure That the Source is Defined in the Event Pattern The following policy allows creating rules with EventPatterns that must have the source field. In other words, an IAM user or role can't create a rule with an EventPattern that does not provide a specific source. { "Version": "2012-10-17", 60 Amazon CloudWatch Events User Guide Example 5: Define a List of Allowed Sources in an Event Pattern With Multiple Sources "Statement": [ { "Sid": "AllowPutRuleIfSourceIsSpecified", "Effect": "Allow", "Action": "events:PutRule", "Resource": "*", "Condition": { "Null": { "events:source": "false" } } } ] } See the following table for examples of event patterns that would be allowed or denied by this policy: Event Pattern Allowed by the Policy Yes { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ] } Yes { "source": [ "aws.ecs", "aws.ec2" ] } No { "detail-type": [ "EC2 Instance State-change Notification" ] } Example 5: Define a List of Allowed Sources in an Event Pattern With Multiple Sources The following policy allows creating rules with EventPatterns that can have multiple sources in them. Each source listed in the event pattern must be a member of the list provided in the condition. When using the ForAllValues condition, make sure that at least one of the items in the condition list is defined. { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowPutRuleIfSourceIsSpecifiedAndIsEitherS3OrEC2OrBoth", "Effect": "Allow", "Action": "events:PutRule", 61 Amazon CloudWatch Events User Guide Example 6: Ensure That AWS CloudTrail Events for API Calls From a Certain PrincipalId Are Consumed "Resource": "*", "Condition": { "ForAllValues:StringEquals": { "events:source": [ "aws.ec2", "aws.s3" ] }, "Null": { "events:source": "false" } } } ] } See the following table for examples of event patterns that would be allowed or denied by this policy: Event Pattern Allowed by the Policy Yes { "source": [ "aws.ec2" ] } Yes { "source": [ "aws.ec2", "aws.s3" ] } No { "source": [ "aws.ec2", "aws.autoscaling" ] } No { "detail-type": [ "EC2 Instance State-change Notification" ] } Example 6: Ensure That AWS CloudTrail Events for API Calls From a Certain PrincipalId Are Consumed All AWS CloudTrail events have the ID of the user who made the API call (PrincipalId) in the detail.userIdentity.principalId path of an event. With the help of the events:detail.userIdentity.principalId condition key, you can limit the access of IAM users or roles to the CloudTrail events for only those coming from a specific account. "Version": "2012-10-17", "Statement": [ { 62 Amazon CloudWatch Events User Guide Example 6: Ensure That AWS CloudTrail Events for API Calls From a Certain PrincipalId Are Consumed "Sid": "AllowPutRuleOnlyForCloudTrailEventsWhereUserIsASpecificIAMUser", "Effect": "Allow", "Action": "events:PutRule", "Resource": "*", "Condition": { "StringEquals": { "events:detail-type": [ "AWS API Call via CloudTrail" ], "events:detail.userIdentity.principalId": [ "AIDAJ45Q7YFFAREXAMPLE" ] } } } ] } See the following table for examples of event patterns that would be allowed or denied by this policy: Event Pattern Allowed by the Policy No { "detail-type": [ "AWS API Call via CloudTrail" ] } Yes { "detail-type": [ "AWS API Call via CloudTrail" ], "detail.userIdentity.principalId": [ "AIDAJ45Q7YFFAREXAMPLE" ] } No { "detail-type": [ "AWS API Call via CloudTrail" ], "detail.userIdentity.principalId": [ "AROAIDPPEZS35WEXAMPLE:AssumedRoleSessionName" ] } 63 Amazon CloudWatch Events User Guide CloudWatch Events Information in CloudTrail Logging Amazon CloudWatch Events API Calls in AWS CloudTrail AWS CloudTrail is a service that captures API calls made by or on behalf of your AWS account. This information is collected and written to log files that are stored in an Amazon S3 bucket that you specify. API calls are logged whenever you use the API, the console, or the AWS CLI. Using the information collected by CloudTrail, you can determine what request was made, the source IP address the request was made from, who made the request, when it was made, and so on. To learn more about CloudTrail, including how to configure and enable it, see the What is AWS CloudTrail in the AWS CloudTrail User Guide. Topics • CloudWatch Events Information in CloudTrail (p. 64) • Understanding Log File Entries (p. 65) CloudWatch Events Information in CloudTrail If CloudTrail logging is turned on, calls made to API actions are captured in log files. Every log file entry contains information about who generated the request. For example, if a request is made to create a CloudWatch Events rule (PutRule), CloudTrail logs the user identity of the person or service that made the request. The user identity information in the log entry helps you determine the following: • Whether the request was made with root or IAM user credentials • Whether the request was made with temporary security credentials for a role or federated user • Whether the request was made by another AWS service For more information, see the CloudTrail userIdentity Element in the AWS CloudTrail User Guide. 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, your log files are encrypted by using Amazon S3 server-side encryption (SSE). 64 Amazon CloudWatch Events User Guide Understanding Log File Entries If you want to be notified upon log file delivery, you can configure CloudTrail to publish Amazon SNS notifications when new log files are delivered. For more information, see Configuring Amazon SNS Notifications for CloudTrail in the AWS CloudTrail User Guide. You can also aggregate Amazon CloudWatch Logs 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 and Receiving CloudTrail Log Files from Multiple Accounts in the AWS CloudTrail User Guide. When logging is turned on, the following API actions are written to CloudTrail: • DeleteRule • DescribeRule • DisableRule • EnableRule • ListRuleNamesByTarget • ListRules • ListTargetsByRule • PutRule • PutTargets • RemoveTargets • TestEventPattern For more information about these actions, see the Amazon CloudWatch Events API Reference. Understanding Log File Entries CloudTrail log files contain one or more log entries. Each entry lists multiple JSON-formatted events. A log entry represents a single request from any source and includes information about the requested action, the date and time of the action, request parameters, and so on. The log entries are not an ordered stack trace of the public API calls, so they do not appear in any specific order. Log file entries for all API actions are similar to the examples below. The following log file entry shows that a user called the CloudWatch Events PutRule action. { "eventVersion":"1.03", "userIdentity":{ "type":"Root", "principalId":"123456789012", "arn":"arn:aws:iam::123456789012:root", "accountId":"123456789012", "accessKeyId":"AKIAIOSFODNN7EXAMPLE", "sessionContext":{ "attributes":{ "mfaAuthenticated":"false", "creationDate":"2015-11-17T23:56:15Z" } } }, "eventTime":"2015-11-18T00:11:28Z", "eventSource":"events.amazonaws.com", "eventName":"PutRule", 65 Amazon CloudWatch Events User Guide Understanding Log File Entries "awsRegion":"us-east-1", "sourceIPAddress":"AWS Internal", "userAgent":"AWS CloudWatch Console", "requestParameters":{ "description":"", "name":"cttest2", "state":"ENABLED", "eventPattern":"{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"]}", "scheduleExpression":"" }, "responseElements":{ "ruleArn":"arn:aws:events:us-east-1:123456789012:rule/cttest2" }, "requestID":"e9caf887-8d88-11e5-a331-3332aa445952", "eventID":"49d14f36-6450-44a5-a501-b0fdcdfaeb98", "eventType":"AwsApiCall", "apiVersion":"2015-10-07", "recipientAccountId":"123456789012" } 66 Amazon CloudWatch Events User Guide My rule was triggered but my Lambda function was not invoked Troubleshooting CloudWatch Events You can use the steps in this section to troubleshoot CloudWatch Events. Topics • My rule was triggered but my Lambda function was not invoked (p. 67) • I have just created/modified a rule but it did not match a test event (p. 68) • My rule did not self-trigger at the time specified in the ScheduleExpression (p. 69) • My rule did not trigger at the time that I expected (p. 69) • My rule matches IAM API calls but my rule was not triggered (p. 69) • My rule is not working because the IAM role associated with the rule is ignored when the rule is triggered (p. 70) • I created a rule with an EventPattern that is supposed to match a resource, but I don't see any events that match the rule (p. 70) • My event's delivery to the target experienced a delay (p. 70) • My rule was triggered more than once in response two identical events. What guarantee does CloudWatch Events offer for triggering rules or delivering events to the targets? (p. 70) • My rule is being triggered but I don't see any messages published into my Amazon SNS topic (p. 71) • My Amazon SNS topic still has permissions for CloudWatch Events even after I deleted the rule associated with the Amazon SNS topic (p. 72) • Which IAM condition keys can I use with CloudWatch Events (p. 72) • How can I tell when CloudWatch Events rules are broken (p. 72) My rule was triggered but my Lambda function was not invoked Make sure you have the right permissions set for your Lambda function. Run the following command using AWS CLI (replace the function name with your function and use the AWS region your function is in): aws lambda get-policy --function-name MyFunction --region us-east-1 67 Amazon CloudWatch Events User Guide I have just created/modified a rule but it did not match a test event You should see an output similar to the following: { "Policy": "{\"Version\":\"2012-10-17\", \"Statement\":[ {\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:events:useast-1:123456789012:rule/MyRule\"}}, \"Action\":\"lambda:InvokeFunction\", \"Resource\":\"arn:aws:lambda:useast-1:123456789012:function:MyFunction\", \"Effect\":\"Allow\", \"Principal\":{\"Service\":\"events.amazonaws.com\"}, \"Sid\":\"MyId\"} ], \"Id\":\"default\"}" } If you see the following: A client error (ResourceNotFoundException) occurred when calling the GetPolicy operation: The resource you requested does not exist. Or, you see the output but you can't locate events.amazonaws.com as a trusted entity in the policy, run the following command: aws lambda add-permission \ --function-name MyFunction \ --statement-id MyId \ --action 'lambda:InvokeFunction' \ --principal events.amazonaws.com \ --source-arn arn:aws:events:us-east-1:123456789012:rule/MyRule Note If the policy is incorrect, you can also edit the rule in the CloudWatch Events console by removing and then adding it back to the rule. The CloudWatch Events console will set the correct permissions on the target. If you're using a specific Lambda alias or version, you must add the --qualifier parameter in the aws lambda get-policy and aws lambda add-permission commands. aws lambda add-permission \ --function-name MyFunction \ --statement-id MyId \ --action 'lambda:InvokeFunction' \ --principal events.amazonaws.com \ --source-arn arn:aws:events:us-east-1:123456789012:rule/MyRule --qualifier alias or version I have just created/modified a rule but it did not match a test event When you make a change to a rule or to its targets, incoming events might not immediately start or stop matching to new or updated rules. Please allow a short period of time for changes to take effect. 68 Amazon CloudWatch Events User Guide My rule did not self-trigger at the time specified in the ScheduleExpression If, after this short period, events still do not match, you can also check several Events metrics for your rule in CloudWatch such as TriggeredRules, Invocations, and FailedInvocations for further debugging. You can also use the TestEventPattern action to test the event pattern of your rule with a test event to make sure the event pattern of your rule is correctly set. For more information, see TestEventPattern in the Amazon CloudWatch Events API Reference. My rule did not self-trigger at the time specified in the ScheduleExpression ScheduleExpressions are in UTC. Make sure you have set the schedule for rule to self-trigger in the UTC timezone. If the ScheduleExpression is correct, then follow the steps under I have just created/ modified a rule but it did not match a test event (p. 68). My rule did not trigger at the time that I expected CloudWatch Events doesn't support setting an exact start time when you create a rule to run every time period. The count down to run time begins as soon as you create the rule. You can use a cron expression to invoke targets at a specified time. For example, you can use a cron expression to create a rule that is triggered every 4 hours exactly on 0 minute. In the CloudWatch console, you'd use the cron expression 0 0/4 * * ? *, and with the AWS CLI you'd use the cron expression cron(0 0/4 * * ? *). For example, to create a rule named TestRule that is triggered every 4 hours using the AWS CLI, you would type the following at a command prompt: aws events put-rule --name TestRule --schedule-expression 'cron(0 0/4 * * ? *)' You can use the 0/5 * * * ? * cron expression to trigger a rule every 5 minutes. For example: aws events put-rule --name TestRule --schedule-expression 'cron(0/5 * * * ? *)' CloudWatch Events does not provide second-level precision in schedule expressions. The finest resolution using a cron expression is a minute. Due to the distributed nature of the CloudWatch Events and the target services, the delay between the time the scheduled rule is triggered and the time the target service honors the execution of the target resource might be several seconds. Your scheduled rule will be triggered within that minute but not on the precise 0th second. My rule matches IAM API calls but my rule was not triggered The IAM service is only available in the US East (N. Virginia) Region, so any AWS API call events from IAM are only available in that region. For more information, see Event Types for CloudWatch Events (p. 29). 69 Amazon CloudWatch Events User Guide My rule is not working because the IAM role associated with the rule is ignored when the rule is triggered My rule is not working because the IAM role associated with the rule is ignored when the rule is triggered IAM roles for rules are only used for relating events to Amazon Kinesis streams. For Lambda functions and Amazon SNS topics, you need to provide resource-based permissions. Make sure your regional AWS STS endpoints are enabled. CloudWatch Events talks to the regional AWS STS endpoints when assuming the IAM role you provided. For more information, see Activating and Deactivating AWS STS in an AWS Region in the IAM User Guide. I created a rule with an EventPattern that is supposed to match a resource, but I don't see any events that match the rule Most services in AWS treat : or / as the same character in Amazon Resource Names (ARNs). However, CloudWatch Events uses an exact match in event patterns and rules. Be sure to use the correct ARN characters when creating event patterns so that they match the ARN syntax in the event you want to match. Moreover, not every event has the resources field populated (e.g. AWS API Call events from CloudTrail). My event's delivery to the target experienced a delay Amazon CloudWatch Events tries to deliver an event to a target for up to 24 hours. The first attempt is made as soon as the event arrives in the event stream. However, if the target service is having problems or your account is being throttled, CloudWatch Events automatically reschedules another delivery in the future. If 24 hours has passed since the arrival of event, no more attempts are scheduled and the FailedInvocations metric is published in Amazon CloudWatch. My rule was triggered more than once in response two identical events. What guarantee does CloudWatch Events offer for triggering rules or delivering events to the targets? Amazon CloudWatch Events guarantees triggering a rule at least once in response to an event. In rare cases, the same rule can be triggered more than once for a given event, or the same target can be invoked more than once for a given triggered rule. 70 Amazon CloudWatch Events User Guide My rule is being triggered but I don't see any messages published into my Amazon SNS topic My rule is being triggered but I don't see any messages published into my Amazon SNS topic Make sure you have the right permission set for your Amazon SNS topic. Run the following command using AWS CLI (replace the topic ARN with your topic and use the AWS region your topic is in): aws sns get-topic-attributes --region us-east-1 --topic-arn "arn:aws:sns:useast-1:123456789012:MyTopic" You should see policy attribute similar to the following: "{\"Version\":\"2012-10-17\", \"Id\":\"__default_policy_ID\", \"Statement\":[{\"Sid\":\"__default_statement_ID\", \"Effect\":\"Allow\", \"Principal\":{\"AWS\":\"*\"}, \"Action\":[\"SNS:Subscribe\", \"SNS:ListSubscriptionsByTopic\", \"SNS:DeleteTopic\", \"SNS:GetTopicAttributes\", \"SNS:Publish\", \"SNS:RemovePermission\", \"SNS:AddPermission\", \"SNS:Receive\", \"SNS:SetTopicAttributes\"], \"Resource\":\"arn:aws:sns:us-east-1:123456789012:MyTopic\", \"Condition\":{\"StringEquals\":{\"AWS:SourceOwner\":\"123456789012\"}}}, {\"Sid\":\"Allow_Publish_Events\", \"Effect\":\"Allow\", \"Principal\":{\"Service\":\"events.amazonaws.com\"}, \"Action\":\"sns:Publish\", \"Resource\":\"arn:aws:sns:us-east-1:123456789012:MyTopic\"}]}" If you see a policy similar to the following, you have only the default policy set: "{\"Version\":\"2008-10-17\", \"Id\":\"__default_policy_ID\", \"Statement\":[{\"Sid\":\"__default_statement_ID\", \"Effect\":\"Allow\", \"Principal\":{\"AWS\":\"*\"}, \"Action\":[\"SNS:Subscribe\", \"SNS:ListSubscriptionsByTopic\", \"SNS:DeleteTopic\", \"SNS:GetTopicAttributes\", \"SNS:Publish\", \"SNS:RemovePermission\", \"SNS:AddPermission\", \"SNS:Receive\", \"SNS:SetTopicAttributes\"], \"Resource\":\"arn:aws:sns:us-east-1:123456789012:MyTopic\", \"Condition\":{\"StringEquals\":{\"AWS:SourceOwner\":\"123456789012\"}}}]}" 71 Amazon CloudWatch Events User Guide My Amazon SNS topic still has permissions for CloudWatch Events even after I deleted the rule associated with the Amazon SNS topic If you don't see events.amazonaws.com with Publish permission in your policy, use AWS CLI to set topic policy attribute. Copy current policy and add statement below to list of statements: {\"Sid\":\"Allow_Publish_Events\", \"Effect\":\"Allow\",\"Principal\":{\"Service\":\"events.amazonaws.com\"}, \"Action\":\"sns:Publish\", \"Resource\":\"arn:aws:sns:us-east-1:123456789012:MyTopic\"} The new policy should look like the one described above. Set topic attributes with the AWS CLI: aws sns set-topic-attributes --region us-east-1 --topic-arn "arn:aws:sns:useast-1:123456789012:MyTopic" --attribute-name Policy --attributevalue NEW_POLICY_STRING Note If the policy is incorrect, you can also edit the rule in the CloudWatch Events console by removing and then adding it back to the rule. The CloudWatch Events console will set the correct permissions on the target. My Amazon SNS topic still has permissions for CloudWatch Events even after I deleted the rule associated with the Amazon SNS topic When you create a rule with Amazon SNS as the target, CloudWatch Events adds the permission to your Amazon SNS topic on your behalf. If you delete the rule shortly after you create it, CloudWatch Events might be unable to remove the permission from your Amazon SNS topic. If this happens, you can remove the permission from the topic using the aws sns set-topic-attributes command. For more information about resource-based permissions for sending events, see Using Resource-Based Policies for CloudWatch Events (p. 50). Which IAM condition keys can I use with CloudWatch Events Amazon CloudWatch Events supports the AWS-wide condition keys (see Available Keys in the IAM User Guide), plus the following service-specific condition keys. For more information, see Using IAM Policy Conditions for Fine-Grained Access Control (p. 55). How can I tell when CloudWatch Events rules are broken You can use the following alarm to notify you when your CloudWatch Events rules are broken. 72 Amazon CloudWatch Events User Guide How can I tell when CloudWatch Events rules are broken To create an alarm to alert when rules are broken 1. 2. 3. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/. Click Create Alarm, and then in the CloudWatch Metrics by Category pane, select Events Metrics. On the Create Alarm dialog box, in the list of metrics, select the FailedInvocations check box. 4. 5. Above the graph, select Sum from the Statistic drop-down list. Select a period from the Period drop-down list, for example: 5 minutes. 6. 8. Click Next, and then under Alarm Threshold, in the Name field, enter a unique name for the alarm, for example: myFailedRules. In the Description field, enter a description of the alarm, for example: Rules are not delivering events to targets. In the is drop-down list, select >=. 9. In the field next to the is drop-down list, enter 1 and in the for field, enter 10. 7. 10. Under Actions, in the Whenever this alarm drop-down list, select State is ALARM. 11. In the Send notification to drop-down list, select an existing Amazon SNS topic or create a new one. 12. To create a new Amazon SNS topic, select New list. 13. In the Send notification to field, enter a name for the new Amazon SNS topic for example: myFailedRules, and in the Email list field, enter a comma-separated list of email addresses to be notified when the alarm changes to the ALARM state. 14. In the navigation pane, choose Create Alarm to complete the alarm creation process. 73 Amazon CloudWatch Events User Guide Document History The following table describes the important changes to the Amazon CloudWatch Events User's Guide. Change Description Release Date AWS CodeDeploy events Added support for events for AWS CodeDeploy. You can now use CloudWatch Events to initiate one or more actions when changes are detected in the state of a deployment or the state of an instance that belongs to an AWS CodeDeploy deployment group. For more information, see AWS CodeDeploy Events (p. 36). 9 September 2016 Scheduled events with 1 minute granularity Added support for scheduled events with 1 minute granularity. For more information, see Cron Expressions (p. 19) and Rate Expressions (p. 21). 19 April 2016 Amazon Simple Queue Service queues as targets Added support for Amazon Simple Queue Service queues as targets in Amazon CloudWatch Events. For more information, see What is Amazon CloudWatch Events? (p. 1). 30 March 2016 New service Initial release of CloudWatch Events, which you can use to view system events. For more information, see What is Amazon CloudWatch Events? (p. 1). 14 January 2016 74 Amazon CloudWatch Events User Guide AWS Glossary For the latest AWS terminology, see the AWS Glossary in the AWS General Reference. 75
Source Exif Data:
File Type : PDF File Type Extension : pdf MIME Type : application/pdf Linearized : No Page Count : 80 Profile CMM Type : Little CMS Profile Version : 2.1.0 Profile Class : Display Device Profile Color Space Data : RGB Profile Connection Space : XYZ Profile Date Time : 1998:02:09 06:49:00 Profile File Signature : acsp Primary Platform : Apple Computer Inc. CMM Flags : Not Embedded, Independent Device Manufacturer : Hewlett-Packard Device Model : sRGB Device Attributes : Reflective, Glossy, Positive, Color Rendering Intent : Perceptual Connection Space Illuminant : 0.9642 1 0.82491 Profile Creator : Little CMS Profile ID : 0 Profile Copyright : Copyright (c) 1998 Hewlett-Packard Company Profile Description : sRGB IEC61966-2.1 Media White Point : 0.95045 1 1.08905 Media Black Point : 0 0 0 Red Matrix Column : 0.43607 0.22249 0.01392 Green Matrix Column : 0.38515 0.71687 0.09708 Blue Matrix Column : 0.14307 0.06061 0.7141 Device Mfg Desc : IEC http://www.iec.ch Device Model Desc : IEC 61966-2.1 Default RGB colour space - sRGB Viewing Cond Desc : Reference Viewing Condition in IEC61966-2.1 Viewing Cond Illuminant : 19.6445 20.3718 16.8089 Viewing Cond Surround : 3.92889 4.07439 3.36179 Viewing Cond Illuminant Type : D50 Luminance : 76.03647 80 87.12462 Measurement Observer : CIE 1931 Measurement Backing : 0 0 0 Measurement Geometry : Unknown Measurement Flare : 0.999% Measurement Illuminant : D65 Technology : Cathode Ray Tube Display Red Tone Reproduction Curve : (Binary data 2060 bytes, use -b option to extract) Green Tone Reproduction Curve : (Binary data 2060 bytes, use -b option to extract) Blue Tone Reproduction Curve : (Binary data 2060 bytes, use -b option to extract) Creator : Amazon Web Services Format : application/pdf Title : Amazon CloudWatch Events - User Guide Language : en Date : 2016:09:23 18:21:14Z Producer : Apache FOP Version 2.1 PDF Version : 1.4 Creator Tool : DocBook XSL Stylesheets with Apache FOP Metadata Date : 2016:09:23 18:21:14Z Create Date : 2016:09:23 18:21:14Z Page Mode : UseOutlines Author : Amazon Web ServicesEXIF Metadata provided by EXIF.tools