- 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
.
@JimFawkes I managed to get it working by creating a profile and assumed this user when creating the db auth token:
Create AWS Profile
aws configure --profile dbuser
AWS Access Key ID [None]: xxxxxxxxxxxxx
AWS Secret Access Key [None]: xxxxxxxxxxxxxxxxxx
Default region name [None]: eu-west-1
Default output format [None]: json
aws --profile dbuser rds generate-db-auth-token --hostname RDS.Enpoint.amazonaws.com --port 5432 --region us-east-1 --username "Postgres Privisioned User"
Using this token as password in PGADmin authenticates and connects to the instance