traday traday - 1 month ago 10
Ruby Question

How can I trigger an event or notification when an AWS SSM RunCommand Script completes executing on my EC2 Instance?

Some background:

I am writing an application (using AWS Ruby SDK/API) that deploys another application on AWS EC2 instances. Specifically, I deploy it as an ECS Cluster of 4 ec2 instances and then start ECS Tasks (not services), one on each ec2 instance and run these docker images. That all works fine. The problem is that at some point I need to save one of those docker images off in my ECR repo. I do that by using Simple System Manager(SSM)'s aws:runShellScript to run the command on the ECS Container Instance. That command may take 1-4 minutes and I don't have any way of finding out when the command completes. Right now I do a sleep and then just grab the tagged container image from the repository and that is error prone.

The question:

Is there any way to:

  1. wait_until for an SSM run command to complete? or

  2. have my deploying application be notified through AWS Lambda or some such? or

  3. Listen for events?

Answer Source

Here are some options I can think of:

  • You could add a final step to the SSM command which would send an email or post to an SNS topic or something similar.
  • The AWS SSM send_command API takes a notification_config parameter which you can configure to send a notification to an SNS topic when the command is in certain states, like the "Success" state. This is probably the best option for monitoring the state of the command.

Once you have done something to post to an SNS topic, you can configure a Lambda function to be triggered by messages in that SNS topic.