Skip to content

Files

Latest commit

af4bce9 · Apr 7, 2023

History

History

lambda-start-rds-instance

Start RDS instances using lamdba (The same way if you want to start RDS cluster)

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.

Permission for lambda

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": "*
        }
    ]
}

Setup Amazon EventBridge

Create a schedule to start RDS instance with Amazon EventBrige

  1. Go to Amazon EventBridge. In left menu under Scheduler, click Schedule group
  2. Enter group name such as rds-schedule-group
  3. Click Create schedule group
  4. In left menu under Scheduler, click Schedules
  5. On Schedules page, click Create schedules
  6. Enter schedule name such as start-rds-instances-schedule
  7. Enter description such as Schedule for start RDS instances
  8. Choose rds-schedule-group we created at step 2
  9. Schedule pattern, choose Recurring schedule
  10. Schedule type, choose Cron-based schedule
  11. Cron expression is 0 7 \* \* ? * it means we will start RDS instance at 07:00 everyday
  12. Flexible time window, choose off
  13. On Timeframe, select timezone, start date, time and end date, time
  14. Click Next
  15. On Select target, choose AWS Lambda and then choose your lambda function and then click Next
  16. On Setting, Retry policy and dead-letter queue (DLQ) keep default value
  17. 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
  18. On Review and create schedule click Create schedule

Run local

  1. Need install Sam cli and Docker desktop
  2. Open Docker desktop
  3. Run command sam local invoke [function_name] -e [event_path] eg: sam local invoke StartRDSInstance -e events/event.json

Deploy

  1. Run command sam build
  2. Run command sam deploy --guided

Ref

https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-rds/classes/startdbinstancecommand.html