In order to save money we can stop RDS instance whenever we are not using it. To do it we are using lambda, AWS SDK v3 and Amazon EventBridge to create a schedule to stop RDS instance. After that we need start it again. We will stop RDS instances at 19:00 and start at 07:00 everyday. This is a demo how to start RDS instance automatically.
To start RDS instances we need allows permissions for lambda
{
"Version": "2012-10-17",
"Statement": [
<!-- Permission start RDS instance -->
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "rds:StartDBInstance",
"Resource": "*"
},
<!-- Permission write log into cloudwatch -->
{
"Effect": "Allow",
"Action": "logs:CreateLogGroup",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*
}
]
}
Create a schedule to start RDS instance with Amazon EventBrige
- Go to Amazon EventBridge. In left menu under Scheduler, click Schedule group
- Enter group name such as rds-schedule-group
- Click Create schedule group
- In left menu under Scheduler, click Schedules
- On Schedules page, click Create schedules
- Enter schedule name such as start-rds-instances-schedule
- Enter description such as Schedule for start RDS instances
- Choose rds-schedule-group we created at step 2
- Schedule pattern, choose Recurring schedule
- Schedule type, choose Cron-based schedule
- Cron expression is
0 7 \* \* ? *
it means we will start RDS instance at 07:00 everyday - Flexible time window, choose off
- On Timeframe, select timezone, start date, time and end date, time
- Click Next
- On Select target, choose AWS Lambda and then choose your lambda function and then click Next
- On Setting, Retry policy and dead-letter queue (DLQ) keep default value
- On Settings, Permission choose Create new role for this schedule and then enter role name such as EventBridge-Lambda-Start-RDS-Instance (You can choose Use existing role if you created role before) and then click Next
- On Review and create schedule click Create schedule
- Need install Sam cli and Docker desktop
- Open Docker desktop
- Run command
sam local invoke [function_name] -e [event_path] eg: sam local invoke StartRDSInstance -e events/event.json
- Run command
sam build
- Run command
sam deploy --guided