How to connect to the RDS instance in the private subnet from your local client machine

Problem:

Need to get access to the RDS instance in the private subnet. RDS instance and the bastion hosts are in the same VPC. RDS PostgreSQL instance was taken as an example. RDS database configured without public access

Simplified scheme:

rds.png

Solution notes:

  1. The main thing to remember here is that we are connecting to the database instance which listens only on the specific port. In our case, RDS PostgreSQL database by default listens on port 5432. Don't confuse it with SSH'ing into the instance. SSH works on port 22.
  2. Edit inbound rules of RDS database security group (SG-RDS) to allow traffic from bastion host. As source address select the security group of the bastion host (SG-bastion)
  3. In the security group of the bastion host (SG-bastion) allow inbound traffic from your internet IP address of the local machine to the SSH port 22
  4. Create EC2 key-pair for bastion host and store private file on your machine for SSH connections
  5. Use sshuttle tool to forward traffic from the bastion host on your local machine

Prerequisistes:

  1. sshuttle tool installed on the local machine
  2. SSH key-pair saved on your local machine for SSH connection to the bastion host
  3. psql installed on the machine. For Ubuntu 20.04 to install the latest version of psql use:
    sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
    wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
    sudo apt-get update
    sudo apt-get -y install postgresql
    

Connection steps:

  1. On the RDS instance edit Inbound rules and allow traffic from bastion security group on port 5432: SG-RDS
  2. On your local machine use sshuttle tool to forward traffic from the bastion host. Export public IP address of your bastion host:
    export BASTION_IP=[public_ip_address_of_your_bastion_host]
    
  3. As I'm using EC2 t2.micro username for the machine is ec2-user. Name can change depending on the type of the machine.
    sshuttle -r ec2-user@$BASTION_IP [VPC_CIDR] --dns --ssh-cmd 'ssh -i ~/[path_to_your_private_key]'
    
    For example:
    sshuttle -r ec2-user@$BASTION_IP 10.0.0.0/16 --dns --ssh-cmd 'ssh -i ~/ec2-access.pem'
    
  4. Successful connection is established with the following message:
    client: Connected
    
  5. Open another terminal window and connect to your RDS database (before that get Endpoint address of your database):
    psql --host=postgres.cyze9njgytrq.eu-central-1.rds.amazonaws.com --port=5432 --username=postgres --password --dbname=postgres
    
  6. Enter the database Master password and get access to the command shell: psql

Reference:

  1. Relational database - Amazon RDS
  2. Connecting to a DB instance running the PostgreSQL database engine