- Amazon RDS for PostgreSQL
- Amazon Aurora PostgreSQL
supports IAM DB authentication.
Here's how to do it.
- Launch PostgreSQL instance with IAM auth enabled
- Create IAM auth user with rds_iam ROLE(
CREATE USER jane_doe WITH LOGIN; GRANT rds_iam to jane_doe;
) - Add new policy for IAM access(for policy template, see
iam-policy.json
) - Request atemporary credential(
$ aws rds generate-db-auth-token
) and use it as DB user password
If you're calling aws rds generate-db-auth-token
API from IAM credentials, IAM auth is quite straightforward.
Just pass your temp password via an environment variable(PGPASSWORD
).
$ RDSHOST=xxx.yyy.us-east-1.rds.amazonaws.com
$ USERNAME=jane_doe
$ export PGPASSWORD="$( aws rds generate-db-auth-token --hostname $RDSHOST --port 5432 --username $USERNAME )"
$ psql "host=$RDSHOST dbname=$DBNAME user=$USERNAME"
But if you're calling that API from IAM role(e.g. EC2 instance profile/Lambda), you need a workaround. As of writing this, PostgreSQL does not support Role-based authentication. To cirsumvent this, you need to explicitly assume IAM role.
iam_auth_psql.sh
is a simple helper script for this workaround. Just modify variables at the top of the script and run $ bash iam_auth_psql.sh
.