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
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
Add a layer for the lambda function
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.
Add lambda trigger
Connect the lambda function to a VPC
In IAM, Create a policy to be added to the role
Add and attach a policy AWSLambdaVPCAccessExecutionRole
to the role of the lambda function, so that the lambda can be connected to a VPC
Click "Add permissions", then "Attach polacies", then choose AWSLambdaVPCAccessExecutionRole
.
Connect the lambda function to a VPC
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.