Implement a Lambda function to run commands via SSM

4.5k Views Asked by At

I have a run document in ssm to install some agents on the server. Now, I wanted to automate this task by running these documents whenever a new instance is launched. I want to achieve this through aws lambda(script to implement run commands upon launch of a new instance) Any help would be appreciated !!!

2

There are 2 best solutions below

0
On

Unfortunately this is a very broad questions, one that could not possibly be answered simply.

I would first suggest you decide which language you wish to write your lambda function in currently there are .NET, python, Node.js, Java and Go.

Node.js is a fairly easy language to start with as it's well supported and you can write it within the inline AWS code editor.

I would suggest looking at the template Node.js lambda functions that aws provides when creating a new lambda function within the console. This will help you see how that could be put together and the various ways that may be used. If you get the hang of these and find them easy enough to understand then you can look at the Node.js SSM api which should be available by default in the lambda runtime and try out running a few commands.

Of course if you're not competent in Node.js and primarily use another language then that's an entirely different question.

There are many resources and examples online for writing lambdas that can be found very easily.

1
On

Use a cloudwatch rule for this.

Create a cloudwatch rule for EC2 Instance State-change Notification and running state. Use lambda as the target and invoke the SSM command from lambda (via API) on the instance. The event will have the details you need like instance id. Hope you are familiar with AWS API's and how to use it. You will need a proper IAM role for your Lambda for this to work. Also, remember Cloudwatch events are region specific and can only invoke a lambda in the same region.

enter image description here