Hands-On: Create & Connect to PostgreSQL
Spin up a small PostgreSQL database with a managed password, then query it from Python.
1 min read
--manage-master-user-password tells RDS to generate the admin password and store it in Secrets Manager,
so you never see or copy it anywhere.
Try it
Terminal
aws rds create-db-instance \
--db-instance-identifier notesnap-db \
--engine postgres \
--db-instance-class db.t4g.micro \
--allocated-storage 20 \
--storage-type gp3 \
--master-username notesnap_admin \
--manage-master-user-password \
--no-publicly-accessible \
--backup-retention-period 7
aws rds wait db-instance-available --db-instance-identifier notesnap-db
aws rds describe-db-instances --db-instance-identifier notesnap-db \
--query 'DBInstances[0].[Endpoint.Address, MasterUserSecret.SecretArn]'Then connect from code running inside the VPC, such as a Lambda function in the same VPC or an EC2 instance:
Python
import json
import boto3
import psycopg # pip install "psycopg[binary]"
secret = json.loads(
boto3.client("secretsmanager").get_secret_value(SecretId="rds!db-1a2b3c4d-AbCdEf")["SecretString"]
)
with psycopg.connect(
host="notesnap-db.c9xyzexample.us-east-1.rds.amazonaws.com",
dbname="postgres",
user=secret["username"],
password=secret["password"],
sslmode="require",
) as conn:
print(conn.execute("SELECT version()").fetchone()[0])Watch out
--no-publicly-accessible keeps the database off the internet. That's what you want. To connect from your
laptop, use a bastion host via Session Manager port forwarding, not a public database.
Key takeaways
- create-db-instance with --manage-master-user-password keeps credentials in Secrets Manager.
- Keep databases private and connect from inside the VPC.
- Always connect over TLS (sslmode=require).
Check your understanding
Pick an answer to see the explanation.
1. Why use --manage-master-user-password?