Connecting to Servers through Bastion Host in GCP by using SSH tunnels (in Mac)
Overview
In order to keep security of servers, data engineers often use bastion host as a “door” to the server and connect to the server through this bastion by using SSH. In this article, we will create this kind of environment in GCP (in Figure 1 below) with the help of deployment manager and do SSH connection to the Server through Bastion. Note that if you have an environment in GCP and all services (including Bastion) are running, you can skip “Creating the environment in GCP” section below.
Creating the environment in GCP
Requirements
You need to have an account and a project in GCP in order to move the next stages. Furthermore, please, install gcloud command in order to run deployment manager commands below.
Creating
Please, pull the code from Github which will be used to create the environment in Figure 1 above. After pulling, run the following codes to create the environment:
# Setting a default project
gcloud config set project {project.id}# Run the deployment manager and create the environment
./deployments_create.sh my-infra infra.yaml
Connecting to Bastion with SSH tunnels
Run the following code and check whether you have .ssh folder:
ls ~/.ssh
If there is not such directory, create the one:
mkdir ~/.ssh
chmod 700 ~/.ssh
After the code above, generate the ssh-keys by running ssh-keygen. You are asked a series of questions. Accept all the defaults by pressing Enter. Enter a passphrase for your SSH key if you want.
After the code above, run the following:
cd ~/.ssh
chmod 600 *
After generating the keys, copy “.pub” version of the secrets you generated above to the “Metadata” of the “Compute Engine” in GCP:
and most importantly, currently, firewall Ingress rule source ranges are 0.0.0.0/0, meaning you can enter to bastion from any IP. In order to increase security, delete this 0.0.0.0/0 and insert your IP there:
DO NOT FORGET TO INCLUDE YOUR IP IN BASTION FIREWALL so that you can connect with your IP to the servers.
Finally, connect to the server through Bastion by using SSH tunnels by using following codes:
ssh -i ~/.ssh/id_rsa {metadata_username}@{bastion_public_ip} -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -f -N -L 10610:{server_private_ip}:22ssh localhost -p 10610
metada_username: your “username” in Metadata of Compute Engine in GCP
THAT’S IT !!!!