Menu
Amazon CloudWatch Events
User Guide

Tutorial: Use CloudWatch Events to Relay Events to Amazon EC2 Run Command

You can use Amazon CloudWatch Events to invoke Amazon EC2 Systems Manager Run Command and perform actions on Amazon EC2 instances when certain events happen. In this tutorial, set up Run Command to run shell commands and configure each new instance that is launched in an Auto Scaling group. This tutorial assumes that you have already assigned a tag to the Auto Scaling group, with environment as the key and production as the value.

To create the CloudWatch Events rule

  1. Open the CloudWatch console at https://console.aws.amazon.com/cloudwatch/.

  2. In the navigation pane, choose Events, Create rule.

  3. For Event source, do the following:

    1. Choose Event Pattern, Build event pattern to match events by service.

    2. For Service Name, choose Auto Scaling. For Event Type, choose Instance Launch and Terminate.

    3. Choose Specific instance event(s), EC2 Instance-launch Lifecycle Action.

    4. By default, the rule matches any Auto Scaling group in the region. To make the rule match a specific group, choose Specific group name(s) and then select one or more groups.

    
                            The Event Source pane
  4. For Targets, choose Add Target, SSM Run Command.

  5. For Document, choose AWS-RunShellScript (Linux). (Note that there are many other Document options which cover both Linux and Windows instances.) For Target key, type tag:environment. For Target value(s), type production and choose Add.

  6. Under Configure parameter(s), choose Constant.

  7. For Commands, type a shell command and choose Add. Repeat this step for all commands to run when an instance launches.

  8. If necessary, type the appropriate information in WorkingDirectory and ExecutionTimeout.

  9. CloudWatch Events can create the IAM role needed for your event to run:

    • To create an IAM role automatically, choose Create a new role for this specific resource.

    • To use an IAM role that you created before, choose Use existing role.

    
                        The Target selector pane
  10. Choose Configure details. For Rule definition, type a name and description for the rule.

  11. Choose Create rule.