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
Open the CloudWatch console at https://console.amazonaws.cn/cloudwatch/
. -
In the navigation pane, choose Events, Create rule.
-
For Event source, do the following:
-
Choose Event Pattern, Build event pattern to match events by service.
-
For Service Name, choose Auto Scaling. For Event Type, choose Instance Launch and Terminate.
-
Choose Specific instance event(s), EC2 Instance-launch Lifecycle Action.
-
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.
-
-
For Targets, choose Add Target, SSM Run Command.
-
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), typeproduction
and choose Add. -
Under Configure parameter(s), choose Constant.
-
For Commands, type a shell command and choose Add. Repeat this step for all commands to run when an instance launches.
-
If necessary, type the appropriate information in WorkingDirectory and ExecutionTimeout.
-
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.
-
-
Choose Configure details. For Rule definition, type a name and description for the rule.
-
Choose Create rule.