I'm trying to add some automation to our AWS environments. I'd like to use a Lambda function to power off our RDS Clusters at a certain time of the evening using EventBridge. The Lambda function would use Python.
The question is - we have different environments and I would like to use Python to let us decide which environment to target. So, for example, I can run the script and based on my choosing I could power off all clusters in our QA environment while keeping the clusters powered on in the rest of the environments.
Is this possible?
CodePudding user response:
Yes, that's definitely possible and there are a couple of ways you can approach this.
The simplest is probably to create separate CloudWatch events/Event Bridge rules for your stages and let them trigger the same Lambda function. When Lambda is triggered like that it will receive an event with the name of the rule that triggered it like this:
{
"version": "0",
"id": "53dc4d37-cffa-4f76-80c9-8b7d4a4d2eaa",
"detail-type": "Scheduled Event",
"source": "aws.events",
"account": "123456789012",
"time": "2015-10-08T16:53:06Z",
"region": "us-east-1",
"resources": [
"arn:aws:events:us-east-1:123456789012:rule/database-prod-on"
],
"detail": {}
}
You can use the name of the rule that triggered the lambda function to figure out which action to perform. I suggest settling on a naming pattern like this for the rules:
- database-dev-on
- database-dev-off
- database-qa-on
- database-qa-off
- database-prod-on
- database-prod-off
That allows you to parse the rule name in Python and decide what to do:
def lambda_handler(event, context):
rule_arn = event["resources"][0]
rule_name = rule_arn.split("/")[-1] # returns something like database-dev-on
resource, environment, action = rule_name.split("-")
# List the resources for the environment and turn them on or off
(Note: I didn't run the code, should be approximately correct)
CodePudding user response:
Altough you can create your own solution to achieve that, you can also use the AWS Instance Scheduler implementation.
With this, the scheduled start/stop of resources like EC2 instances, RDS instances and RDS cluster are based on tags.
So you can specify a different tag value for your clusters depending on the environment and set an appropiate schedule.
In addition, it supports cross-account instance scheduling and is easy to deploy. Behind the scenes, it is based on Lambda, Cloud Watch Event Rules and DynamoDB.
