Add Cognito signed-up users to RDS Postgres database by AWS Lambda function

Add Cognito signed-up users to RDS Postgres database by AWS Lambda function

·

2 min read

This article describes when a user is signed up to a Cognito user pool, an AWS lambda function is triggered and adds the user to a table in an RDS PostgreSQL database.

Create an AWS lambda function

image

Paste the codes to the lambda function

import os
import psycopg2

def lambda_handler(event, context):
    user = event['request']['userAttributes']
    print("***** USER *****: ")
    print(user)
    user_display_name = user["name"]
    user_handle = user["preferred_username"]
    user_email = user["email"]
    user_cognito_id = user["sub"]
    try:
        conn = psycopg2.connect(os.getenv('CONNECTION_URL'))
        cur = conn.cursor()
        sql = f"""
        INSERT INTO users (
            display_name,
            handle,
            email,
            cognito_user_id
        ) VALUES(
            '{user_display_name}',
            '{user_handle}',
            '{user_email}',
            '{user_cognito_id}'
        )
        """
        print(sql)
        cur.execute(sql)
        conn.commit() 

    except (Exception, psycopg2.DatabaseError) as error:
        print(error)

    finally:
        if conn is not None:
            cur.close()
            conn.close()
            print('Database connection closed.')

    return event

Add the environment variable

image

Add a layer for the lambda function

image

For the ARN of the layer, refer to Psycopg2-lambda-layer on github to find the ARN of related region.

Add trigger for the lambda function

In AWS Cognito user pool, under User pool properties, add lambda trigger.

image

Add lambda trigger

image

Connect the lambda function to a VPC

In IAM, Create a policy to be added to the role

image

image

Add and attach a policy AWSLambdaVPCAccessExecutionRole to the role of the lambda function, so that the lambda can be connected to a VPC

image

image

Click "Add permissions", then "Attach polacies", then choose AWSLambdaVPCAccessExecutionRole.

Connect the lambda function to a VPC

image

After "Save", the VPC is connected to the lambda.

Sign up an user in our app

It creates an user in the Cognito user pool, which trigger the lambda function to be called. But an error log is observed in CloudWatch.

column "email" of relation "users" does not exist

This is because the scheme of the database has not been updated. After updating it, the user creation is successful. And we see the user in the Postgres database users table.

image