Modify the AWS RDS Instance size using Lambda Function
Published: 2023-03-30 06:20:48




This article gives you an overview of the AWS Lambda function to modify the RDS instance class using Python language in Lambda function without stopping the RDS instance.

Let’s follow this article to modify RDS instance using Lambda function.

Steps to create AWS Lambda Function for AWS RDS Instance class

we use the following steps to configure a lambda function.

**Step1: Create an IAM Policy**

The first step is to create IAM policy to gain access to RDS actions and AWS CloudWatch log events.

Navigate to IAM in the services and click on Policies => Create Policy.


![RDS Policy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9l78330vylmtkbplzwdj.png)


![Same policy add CloudWatch Logs](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htm06697eldprkfasv0g.png)


![Creating policy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/98nt8sjzupa65x7dq8ky.png)

**Step2: Create an IAM Role and attach “Lambda_RDS_modification_policy”**

In this step, we are creating an IAM role and attach the policy created in the previous step. Click on Roles -> Create Role:


![IAM Role](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dmrv0x9eynr5bimjt35v.png)

![Select policy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3s12jwkn8td85rixwetk.png)


![Create IAM Role with selected trusted entities](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n8je0csyjqo9irilawge.png)


![IAM Role created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2qenuo0ywnwdhavj1aj.png)

**Step3: Create an AWS Lambda Function**

Now we will create AWS Lambda function to modify RDS instance class. First you have to select “Author from scratch” -> Function Name -> Runtime (Python3.7 or 3.8) -> Existing Role “RDS_Lambda_Role”

![Lambda function creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xam9uhtb9zuqef1mufoe.png)

![Click on Create Function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/voejpa79lghzrvzinris.png)

![Lambda Function is created](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uy38zjsnkvb4lov7cuc8.png)

**Add inline policy in existing IAM Role**

Now, open a new tab for the IAM role and edit the existing Role RDS_Lambda. In the summary page, click on Add Inline Policy

![Add inline policy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w5ylaoxuiywvzm5adtdz.png)

In the Inline policy editor, paste the following JSON. Here, you note that we used the AWS lambda ARN in the resource section. You can copy ARN for your existing lambda ARN.

Lambda ARN follows the format: **arn:aws:lambda:Region-AWS Account:function:lambda_function_Name**

```
{   
   "Version": "2012-10-17",
   "Statement": [
{
      "Effect": "Allow",
      "Action": "lambda:GetFunctionConfiguration",
      "Resource": "arn:aws:lambda:us-east-1:11111111111:function:RDSStartFunction"
      }
   ]
}

```

![Manual RDS Schedule Policy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upau7bk5840y7rkzzs9o.png)


![RDS Schedule Role](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/leu7tceialhg0yqqyv5i.png)

**Step4: Function Code:** Scroll down and paste the Python code inside the editor. You need to select appropriate language in the run time. I go with the latest version Python 3.8

![This is the Python code to modify RDS instance class](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xqp9j76gwyay5z6ezgan.png)

**Python Code:**

Here we are using 2 environment variables:

- DBinstance

- DBinstanceClass

```
import sys
import botocore
import boto3
import json
from botocore.exceptions import ClientError
def lambda_handler(event, context):
    rds = boto3.client('rds')
    lambdaFunc = boto3.client('lambda')
    print ('Trying to get Environment variable')
    try:
        funcResponse = lambdaFunc.get_function_configuration(
            FunctionName='RDS_Instance_Modification_Function'
       )
        DBinstance = funcResponse['Environment']['Variables']['DBInstanceName']
        DBinstanceClass = funcResponse['Environment']['Variables']['DBinstanceClass']
        
        print (f'Starting RDS service for DBInstance : {DBinstance}')
        print (f'RDS instance class : {DBinstanceClass}')
     
        
        response = rds.modify_db_instance(DBInstanceIdentifier=DBinstance, DBInstanceClass=DBinstanceClass, ApplyImmediately=True)
        
        print (f'Success :: {response} ') 
        return json.dumps(dict(abc=123))
    except ClientError as e:
return json.dumps(dict(error=str(e)))
    
    return json.dumps(dict(abc=12345))
```

**<u>Creating Environment Variables:</u>**


![Adding env variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ktew7tniw8hq5uxacdl.png)

**Step5: I already created one testdb RDS instance for the testing**


![RDS Test Instance](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jt081n082a5z0hro77lb.png)

**Step6: Now we will test the Lambda Function**

Click on the “Test” button


![Test Lambda Function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6dfge7tls85559ls042s.png)

First time when you run it and as you already entered the “db.t2.micro” so the result will be like:


![Result of test function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/moyp03uoixrshgideyg2.png)

But now I will change the “DBinstanceClass” to “db.t2.small” so this time it will successfully modify the AWS RDS instance “testdb” class to “db.t2.small”

![Modify the RDS Instance Type](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ppidn5w86gc0dmmhqdu.png)

Now you will get the following logs after running the lambda function

![Logs of function](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1twbxu98uymobglj0fqg.png)

Here you will see that the RDS instance is now “modifying” status. It will take some time to show you the result as this instance size will be change from “db.t2.micro” to “db.t2.small”

![Modifying RDS Instance](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bg5sizv28sa26qxfaa6r.png)

Final result: after modification you will see that now the instance size is “db.t2.small” and status is now “Available”


![Modified Successfully](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1d3tt4vao99uut0vibhd.png)