I have Java based containers running AWS ECS Fargate. Now we are accessing AWS RDS Postgres database via username-password combo, but I wonder how to make this process more secure.
But I have a concern: How to avoid storing user passwords in .psql scripts (CREATE USER username WITH PASSWORD 'xxx')? I think better option will be to avoid using passwords completely, but I am not sure how to do it...
Loading passwords to Fargate containers is from AWS Secrets Manager - this is OK.
Do you have any advice, please?
EDIT: I will share my progress here so anyone can reproduce
Docs: https://docs.aws.amazon.com/.../.../.../UsingWithRDS.IAMDBAuth.html
- PHASE ONE -
Goal: PoC of IAM Auth (using IAM User)
- I have prepared my RDS instance to allow IAM Auth
- I have created IAM user, attached new IAM Policy to it and create an access key.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": "rds-db:*",
"Resource": "arn:aws:rds-db:eu-central-1:666:dbuser:db-YFVS/iam_user"
}
]
}
NOTE: In the resource is used resourceId, not arn! (this can be found in the Configuration tab of the rds instance)
CREATE USER iam_user;
GRANT rds_iam TO iam_user;
- I tested the connection (after exporting access key)
# Generate token
export RDSHOST="dev.aaaaa.eu-central-1.rds.amazonaws.com"
export PGPASSWORD="$(aws rds generate-db-auth-token --hostname $RDSHOST --port 5432 --region eu-central-1 --username iam_user )"
#Connect
psql "host=$RDSHOST port=5432 dbname=mydb user=iam_user password=$PGPASSWORD"
mydb->
Now I would like to proceed with Java implementation and furthermore move to Fargate
- PHASE TWO -
Goal: Implement IAM Auth into Python app
I have followed the tutorial here and it worked fine. I have used IAM credentials (key, secret) of the IAM user I created in the previous step. Also, I have loaded creds from ENVs instead of profile file.
https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.Python.html
import psycopg2
import sys
import boto3
ENDPOINT="postgresmydb.123456789012.us-east-1.rds.amazonaws.com"
PORT="5432"
USR="jane_doe"
REGION="us-east-1"
DBNAME="mydb"
session = boto3.Session(region_name='us-east-1',
aws_access_key_id=os.environ['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=os.environ['AWS_SECRET_ACCESS_KEY'])
token = client.generate_db_auth_token(DBHostname=ENDPOINT, Port=PORT, DBUsername=USR, Region=REGION)
try:
conn = psycopg2.connect(host=ENDPOINT, port=PORT, database=DBNAME, user=USR, password=token)
cur = conn.cursor()
cur.execute("""SELECT now()""")
query_results = cur.fetchall()
print(query_results)
except Exception as e:
print("Database connection failed due to {}".format(e))