SSH tunneling to access AWS RDS using Bastion Host and IAM role

Image for post
Image for post

General

Opening SSH tunnel cli

ssh -N -L 3307:database-name.cluster-cdho8ligqqad.eu-central-1.rds.amazonaws.com:3306 -p 22 ec2-user@30.143.243.20

Setting for .ssh/config

Host rds_tunnel
User ec2-user
Hostname 30.143.243.20
Localforward 3307 database-name.cluster-cdho8ligqqad.eu-central-1.rds.amazonaws.com:3306
IdentityFile ~/.ssh/id_rsa.pem
ssh rds_tunnel

Access DB without IAM

mysql -u username -h 127.0.0.1 -P 3307 -p password

Access DB with IAM role

Image for post
Image for post
#!/usr/bin/env bashREGION="eu-central-1"
IAMDBUSER="user-iam-admin"
HOSTNAME="database-name.cluster-cdho8ligqqad.eu-central-1.rds.amazonaws.com"
# Make sure you have the right region for the token!!
TOKEN="$(aws rds generate-db-auth-token --hostname ${HOSTNAME} --port 3306 --username ${IAMDBUSER} --region=${REGION})"
mysql -h 127.0.0.1 -P 3307 --enable-cleartext-plugin --user=${IAMDBUSER} --password=${TOKEN}
CREATE USER user-iam-admin IDENTIFIED WITH AWSAuthenticationPlugin as 'RDS';
GRANT USAGE ON *.* TO 'user-iam-admin'@'%'REQUIRE SSL;

Conclusion

Written by

Lead Software/Infrastructure/Devops Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store