AstroNomad
AstroNomad

Reputation: 117

How to configure RDS PostgresSQL DB inside AWS Lambda within VPC?

How can I move the DB Configuration and schema creation from Terraform into AWS Lambda, and then create a cloudwatch event which can invoke the Lambda to perform the operation.

This operation can be creating the connection, schema and then running some alembic scripts.

For example:

    provider "postgresql" {
  host     = "127.0.0.1"
  database = "${var.db1_name}"
  username = "my_role"
  password = "foobar"
  sslmode  = "disable"
}

resource "postgresql_schema" "my_schema1" {
  name = "my_schema"
}

If my schema.tf file looks like this,

How can these moved to lambda.py and package them together as a zip? Any help is appreciated, thank you!

Upvotes: 0

Views: 166

Answers (1)

Shivkumar Mallesappa
Shivkumar Mallesappa

Reputation: 3077

Create RDS Instance using boto3

import boto3

client = boto3.client('rds')

response = conn.create_db_instance(
        AllocatedStorage=10,
        DBName="test",
        DBInstanceIdentifier="my-first-rds-instance",
        DBInstanceClass="db.t2.micro",
        Engine="mysql",
        MasterUsername="root",
        MasterUserPassword="pass1234",
        Port=3306,
        VpcSecurityGroupIds=["sg-7fa4d512"],
    )

print (response)

If you want to configure other parameters for RDS you can have a look here.

Create CloudWatch Event:

import boto3

AWS_REGION = "us-west-2"

client = boto3.client('events', region_name=AWS_REGION)

response = cloudwatch.put_rule(
    Name='AlarmStateChange',
    EventPattern='{"source": ["aws.cloudwatch"], "detail-type": ["CloudWatch Alarm State Change"]}',
    State='ENABLED'
)

response = cloudwatch.put_targets(
    Rule='AlarmStateChange',
    Targets=[
        {
            'Arn': 'arn:aws:lambda:us-west-2:585584209241:function:DemoFunction',
            'Id': 'myCloudWatchEventsTarget',
        }
    ]
)

print(response)

If you want to configure other parameters for CW you can have a look here.

For Operation, you will have to create another Lambda Function and add the necessary code.

Hope this helps.

Upvotes: 1

Related Questions