Using AWS against... AWS: How to control resources using Lambda
There are many ways to administrate resources in your AWS accounts because you have the power of IAC, which means that you can deploy/start/stop any services just using Code.
To do it, we usually use templates and CloudFormation or other tools that can enable the interaction with your accounts, maybe directly from a bash console, maybe using AWS pipeline.
Using a joke from a friend of mine, it is always funny to use AWS against AWS: this is the case when you need to stop resources that AWS starts and you don't want to pay for unused resources (and you don't have all the scripts to recreate all the instances). Let's see it
CONDITION
Suppose you have created a simple DocumentDB cluster which you need to stops. You don't have all the ability to recreate the instances each time using external disks as backup. You just stop the cluster when you don't use it.
If you wait too much, AWS will restart the cluster (after a week) and you will pay for it, even if you don't use it.
You need to remember it.. or you can leave AWS make it.
TIMING
We will use a scheduled operation for that, which means that you will create a schedule Event bridge and let be the trigger for our Lambda Function
It is scheduled for example every day at 8. Or maybe twice a day. Or maybe you can start it every 20 minutes because you are so afraid to spend even a penny.
LAMBDA FUNCTION
To easily test and deploy, we will use typescript and nodeJs. The logic is quite simple:
- we will call the describe cluster passing the name of the cluster
- we will extract the status information
- if the status is not stopped or stopping (or backing-up) we can try to stop it
- we will call the command for stop
- we will call the describe status until the status is stopping, waiting a while between each call
We then just return an ok response.
We can easily test it (the input is not so important because it's just time event, no other information are available)
Here the code
There are all the imports we need from documentDb and also there is a function (an async function) which is able to call the describe status whenever we need it.
ROLE AND PERMISSION
This is simple, because we just use the Lambda to call describe and stop, so we just used the rds:* (it's not the best choice..but we are not in production of course)
CONCLUSION
This is intended to be not for production. However this is a correct approach if you need to start and stop instances or clusters every day.
For example if you have the cloud formation template for deploy a kubernetes cluster and you want to stop it every day, you can call the code directly in the function and create the schedule using event bridge.
Please use always as much automation you can, enjoy all features of cloud!
Commenti
Posta un commento