Sub topic 6
Connecting and Managing Credentials
This chapter assumes you can use the AWS CLI, understand VPC subnets and security groups, and have created a private RDS instance like the demo-pg instance from the previous chapter. It covers how clients find an instance, how they authenticate, and where the credentials live.
The endpoint is a DNS name, not an IP address
Every RDS instance gets a DNS endpoint such as demo-pg.example.us-east-1.rds.amazonaws.com. Applications must connect through this name and never through a cached IP address. During a Multi-AZ failover or a host replacement, RDS changes what the name resolves to. A client that pinned the old IP address keeps talking to a dead host.
The DNS name resolves differently depending on where the query comes from:
- Inside the VPC, and from peered networks that resolve it, the name returns the instance's private IP address.
- From the internet, the name returns a public IP address only if the instance is publicly accessible. For a private instance there is nothing public to reach.
Set a low DNS cache lifetime in your client. Java applications are a common trap. Some JVMs cache DNS results indefinitely unless you configure networkaddress.cache.ttl. Connection pools also hold open sockets to the old host, so configure a connection validation query or a maximum connection lifetime so stale connections are replaced after a failover.
Reading the endpoint
You can read the endpoint and port from the console or the API. The following script waits for the instance to become available, then prints the endpoint and the ARN of the managed secret.
import boto3
rds = boto3.client("rds")
rds.get_waiter("db_instance_available").wait(DBInstanceIdentifier="demo-pg")
instance = rds.describe_db_instances(DBInstanceIdentifier="demo-pg")["DBInstances"][0]
endpoint = instance["Endpoint"]
print(endpoint["Address"], endpoint["Port"])
print(instance["MasterUserSecret"]["SecretArn"])The MasterUserSecret key exists only when RDS manages the master password. If you set the password yourself, the key is missing and the script raises a KeyError.
Network path comes first
Authentication is the second hurdle. Before a client can send a password, a TCP connection must reach the instance. Three things must all be true:
- The client has a route to the instance's subnets, for example it runs in the same VPC, in a peered VPC, or across a VPN or Direct Connect link.
- The instance's security group has an inbound rule for the database port (5432 for PostgreSQL, 3306 for MySQL and MariaDB) from the client's source.
- Network ACLs on both subnets allow the traffic in both directions.
The best practice is to use the client's security group as the rule source instead of a CIDR range. For example, allow inbound TCP 5432 from the application's security group. The rule then follows the application as instances come and go.
Three ways to authenticate
RDS databases authenticate users with whatever the engine supports. RDS adds two ways of managing the secret.
| Method | Where the secret lives | Lifetime | Good fit |
|---|---|---|---|
| Native password you manage | In your own configuration or code | Until you change it | Prototypes only |
| Password managed by RDS in Secrets Manager | AWS Secrets Manager | Rotated automatically, every 7 days by default | Master user, admin tasks, many applications |
| IAM database authentication | Nowhere. A token is generated on demand | 15 minutes per token | Applications on AWS with IAM roles |
Master credentials managed in Secrets Manager
The create-db-instance example in the previous chapter used --manage-master-user-password. With that flag RDS generates the master password, stores it in a Secrets Manager secret it owns, and rotates it on a schedule. You never see the password at creation time and it never appears in your templates or shell history.
Retrieve it when you need it:
SECRET_ARN=$(aws rds describe-db-instances \
--db-instance-identifier demo-pg \
--query "DBInstances[0].MasterUserSecret.SecretArn" \
--output text)
aws secretsmanager get-secret-value \
--secret-id "$SECRET_ARN" \
--query SecretString \
--output textThe secret is a JSON document with username and password keys. Some points to know:
- The secret is encrypted with a KMS key. By default that is the AWS managed key
aws/secretsmanager. A customer managed key lets you control who can decrypt it, but your callers then needkms:Decrypton that key too. - The caller needs
secretsmanager:GetSecretValueon the secret. This is how you restrict who can read the master password. - You cannot edit or delete the secret directly while RDS manages it. Disable management with
modify-db-instance --no-manage-master-user-password, or delete the instance. - Rotation changes the password in the database and the secret together. An application that read the password once at startup and keeps using it will fail after the next rotation. Re-read the secret when a connection fails with an authentication error, or fetch it through a caching client library.
IAM database authentication
With IAM database authentication, the client does not send a stored password. Instead it asks IAM to sign a token, and uses the token as the password. The database checks the signature. Benefits: no long-lived password to leak or rotate, access is governed by IAM policy, and every token request is traceable in CloudTrail.
Setting it up has three parts:
- Enable it on the instance:
aws rds modify-db-instance --db-instance-identifier demo-pg --enable-iam-database-authentication --apply-immediately. - Create a database user that is tied to IAM. In PostgreSQL, create the user and grant it the
rds_iamrole:
``sql CREATE USER app_user WITH LOGIN; GRANT rds_iam TO app_user; ``
- Attach an IAM policy that allows
rds-db:connecton the resourcearn:aws:rds-db:REGION:ACCOUNT:dbuser:DBI_RESOURCE_ID/app_user. Note that the resource uses the instance'sDbiResourceId(it looks likedb-ABCDEF...), not the instance name.
The client then generates a token and connects. This example uses boto3 and psycopg2:
import boto3
import psycopg2
host = "demo-pg.example.us-east-1.rds.amazonaws.com"
rds = boto3.client("rds", region_name="us-east-1")
token = rds.generate_db_auth_token(
DBHostname=host, Port=5432, DBUsername="app_user", Region="us-east-1"
)
conn = psycopg2.connect(
host=host,
port=5432,
dbname="postgres",
user="app_user",
password=token,
sslmode="verify-full",
sslrootcert="global-bundle.pem",
)
with conn, conn.cursor() as cur:
cur.execute("SELECT current_user")
print(cur.fetchone())Limits and gotchas:
- A token is valid for 15 minutes, but the validity applies to opening a connection. An established connection stays open after the token expires. Generate a fresh token for each new connection.
- IAM authentication requires TLS. The connection is rejected without it.
- There is a cap on new IAM-authenticated connections per second, which depends on the instance class. High connection churn is a poor fit. Use a connection pool, or RDS Proxy, which a later chapter covers.
- Engine and version support varies. Check the documentation for your engine before relying on it.
Connecting over TLS
Use sslmode=verify-full with the RDS certificate bundle so the client checks both the certificate chain and the hostname. Download global-bundle.pem from the RDS documentation, then connect:
psql "host=demo-pg.example.us-east-1.rds.amazonaws.com port=5432 dbname=postgres user=appadmin sslmode=verify-full sslrootcert=global-bundle.pem"psql prompts for the password. For scripts, supply it through the PGPASSWORD environment variable or a .pgpass file, never on the command line where other users can see it in the process list. Lower settings such as sslmode=require encrypt traffic but do not verify the server, so an attacker who can intercept traffic could impersonate the database.
Reaching a private instance from your laptop
A private instance has no public address, so your laptop cannot connect directly. Common options:
- A bastion host (an EC2 instance in the VPC) with an SSH tunnel, for example
ssh -L 5432:ENDPOINT:5432 user@bastion. You then connectpsqltolocalhost. Note thatverify-fullfails againstlocalhostbecause the name does not match the certificate. Useverify-cafor a tunnel, or map the real hostname to127.0.0.1in your hosts file. - AWS Systems Manager Session Manager port forwarding, which avoids opening SSH ports.
- A VPN or Direct Connect link into the VPC.
Making the instance publicly accessible is the option to avoid. If you do it for a short test, restrict the security group to your own IP address.
Common errors
| Symptom | Likely cause |
|---|---|
| Timeout | Missing security group rule, no route, or a NACL block |
| `password authentication failed` | Wrong or rotated password, or a stale cached secret |
| `PAM authentication failed` with IAM (MySQL) or token errors | Expired token, wrong user, or missing `rds-db:connect` permission |
| `no pg_hba.conf entry ... no encryption` | The server requires TLS and the client did not use it |
| `certificate verify failed` | Outdated or missing CA bundle, or a hostname mismatch |
Exercise
An application reads the RDS-managed master secret once at startup and works for several days. It then starts failing with "password authentication failed" although nobody changed anything. What is the likely cause, and what two changes would you make?
Show answer
RDS rotated the managed master password on its schedule (every 7 days by default), so the password the application cached is stale. First, have the application re-read the secret when authentication fails, or use a caching secrets client that refreshes it. Second, stop using the master user in the application: create a dedicated database user with limited privileges, and use IAM database authentication or a separate secret for it.
Exercise
You enabled IAM database authentication and attached a policy allowing rds-db:connect, but connections are rejected. Name three things to check.
Show answer
Check that the database user exists and has the rds_iam role (PostgreSQL) or is created with the AWS authentication plugin (MySQL). Check that the policy resource uses the instance's DbiResourceId and the exact database user name. Check that the client connects over TLS and generated the token within the last 15 minutes for the correct host, port, user, and Region.