It’s been long time since i wrote a blog post. In this post i would like to show an example of lambda to connect to PostgreSQL database and execute the query.
- Build a PostgreSQL psycopg module in order to connect to database. I’ve built a custom compiled python library to connect to latest PostgreSQL 9.6 database using this. You may download the package from here
- Write a sample lambda that updates the url in the table. It calls the function to update.
import psycopg2 def lambda_handler(event,context): conn_string = "dbname='test' port='5432' user='username' password='password' host='RDSEndpoint'" conn = psycopg2.connect(conn_string) cursor = conn.cursor() cursor.execute("select system_env_host('ramasankarmolleti.com')") conn.commit() cursor.close() print("working")
- You may also download python code here
- Now, let’s create a lambda function
- In the above screenshot I’ve created a test_lambda_role iam role to get access to lambda services. Once you create the lambda, then combine both step1 and step2 as one zip file and upload the zip file in lambda you may download the combined zip file here
- Next, Here comes to access to Database from lambda. You need to create a security group that have access to PostgreSQL database from the lambda. I’ve created a security group and attached to lambda.
- Now, we have lambda deployed and run the lambda for testing. Click on test to test the lambda. This will prompt you to create test even as below
- After creating test even you can run the lambda by clicking test before that make sure lambda function name is updated to function name you created. In this example function name is UpdateHost_Python as shown in below
- Now, Click on test to test the lambda.
- Here you go lambda is successfully executed
- Let’s see the results in the database. You can see the results that host is updated to ramasankarmolleti.com.
Hope you enjoyed the post!