Modify EC2 Instance by Lambda (NodeJS) 🚀

modify instance
EC2 Instance Modification 
 
This is a simple program created to modify or change the EC2 instance with Lambda and use the Step Function Integration. With the help of a step function we will get a flow function according to what we defined. 
 
Here we will use several flows, the first is to stop the instance, the second is to modify the instance, and the third is to start the instance.

Scenario

We will create a flow that can change the EC2 instance type. For example, let's say we want to change the instance type from t3.nano to t3.micro. If we want to make it a scheduler, then we have to integrate with Cloudwatch. In this article, we will explain in a simple way how to modify the instance with Lambda and the step function. For other developments, maybe you can integrate with other services.
 
The rules are quite simple, create at least 3 functions in Lambda to stop, modify, start, and step functions in JSON format.
Lambda function list
Lambda function list
Note: Make sure all functions have an IAM role to access EC2. As a suggestion, don't give full access to IAM roles, so it's better to use it as needed because this is a security best practice by AWS that you can read here.
 
I suggest also setting the variable in Environment variables because if you want to change the value of the variable, you don't have to hardcode the values in the file.
 
Environment Variables
Next is to create a function that matches the function.
 
Stop function
 
Modify function
modify function
 
Start function
start function
 
Next is, we will create a state machine in Step function that will connect all flows from the Lambda function that we created earlier.
 
Step function JSON
Step function JSON
This is really a simple flow, because there are no choices or branching in the flow.
 
When this post was created, there was no graphical UI to create a step function flow. So we have to define all flows in json. But to make sure there are no errors in creating flows, AWS provides previews for each state.
 
Step function preview
Finally, we run new execution. At first we will get input for execution, we will just leave it at the default.
graph inspector
Graph inspector

When the state machine is running, we will see a graphical inspector for each state that is running. There are also several indexes that explain whether the state is successful, in progress, or failed, etc.

Step output
If we want to see whether the function we created produces output or not, we can select a state, then select the step output tab. There we will see the print of the function that we have created.
 
There are several things that must be considered when we create flow in a step function.
  • We need the type of state. Whether it is task, choices, wait, etc.
  • We need ARN if we want Lambda.
  • We need Next / End to continue or end execution.

In the near future I will provide it on github.

Happy coding!!👨‍💻👩‍💻