AWS EventBridge combined with TypeScript CDK (Cloud Development Kit) simplifies the management and automation of tasks on AWS EC2 instances, especially when integrating with AWS Systems Manager (SSM).
Establishing an Event Role First, create a role that permits EventBridge to send commands to EC2 instances:
const eventRole = new iam.Role(this, 'EventRole', { assumedBy: new iam.ServicePrincipal('events.amazonaws.com'), inlinePolicies: { allowRunCommand: new iam.PolicyDocument({ statements: [ new iam.PolicyStatement({ actions: ['ssm:SendCommand'], resources: ['*'], // Replace with a specific resource ARN if needed }), ], }), }, });
Setting up an Event Rule Now, craft an event rule that triggers command execution on an EC2 instance upon a specific event occurrence. Here’s an example that demonstrates a generic event listener and executes a command to write to a file on the EC2 instance:
new events.CfnRule(this, 'updaterule', { eventPattern: { source: ["aws.ec2"], detail: { eventName: ["<youreventname>"] // Replace '<youreventname>' with the desired event name } }, roleArn: eventRole.roleArn, targets: [ { arn: `arn:aws:ssm:${this.region}::document/AWS-RunShellScript`, id: '1', roleArn: eventRole.roleArn, input: JSON.stringify({ commands: [`echo 'this is from events' > /home/ec2-user/event_log.txt`], }), runCommandParameters: { runCommandTargets: [{ key: "instanceids", values: [ec2Instance.instanceId] }] // key values can be tags , or arrays of ids } } ] })
This rule listens to events originating from ‘aws.ec2’ and responds to any event matching the specified event name. We can generalize event listening and execute a command on the EC2 instance - in this case, writing ’this is from events’ into a file named ’event_log.txt’ in the home directory of the EC2 user.
The command can be sent to fleet of ec2Instances using tags or resource group. See https://docs.aws.amazon.com/systems-manager/latest/userguide/send-commands-multiple.html
By leveraging event names and potentially other parameters within the ‘detail’ section, we can tailor our automated responses to specific events, allowing for a more responsive and efficient AWS infrastructure. Event names and parameters can be found in eventTrail.
AWS EventBridge, combined with SSM, IAM roles and event rules, empowers us to automate tasks on EC2 instances with ease, enhancing operational efficiency and allowing for a more streamlined management experience.