Tutorial: Use CloudWatch Events to Relay Events to Amazon Systems Manager Run Command - Amazon CloudWatch Events
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China.

Tutorial: Use CloudWatch Events to Relay Events to Amazon Systems Manager Run Command


Amazon EventBridge is the preferred way to manage your events. CloudWatch Events and EventBridge are the same underlying service and API, but EventBridge provides more features. Changes you make in either CloudWatch or EventBridge will appear in each console. For more information, see Amazon EventBridge.

You can use Amazon CloudWatch Events to invoke Amazon 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 Amazon EC2 Auto Scaling group. This tutorial assumes that you have already assigned a tag to the Amazon EC2 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.amazonaws.cn/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 Amazon EC2 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.

  4. For Targets, choose Add Target, SSM Run Command.

  5. For Document, choose Amazon-RunShellScript (Linux). There are many other Document options that 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.

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

  11. Choose Create rule.