Dimitris Poulopoulos
Dimitris Poulopoulos

Reputation: 147

How to dynamically change the host in the SSH config file?

I'm trying to connect to a GCP instance, which changes its public IP every time it's restarted. To get the IP dynamically I use this gcloud command:

gcloud compute instances describe <vm-name> --zone europe-west --format='get(networkInterfaces[0].accessConfigs[0].natIP)'

Then I have this ssh config file:

Host MyHost
    ProxyCommand ~/.ssh/vm-connect

which points to a script vm-connect with the following contents

#!/bin/bash
get_host() {
    gcloud compute instances describe <vm-name> --zone europe-west1-b --format='get(networkInterfaces[0].accessConfigs[0].natIP)'
}

ssh minikf@$(get_host)

If I only run the script it connects to the VM successfully. But if I run ssh MyHost it gives me:

Pseudo-terminal will not be allocated because stdin is not a terminal.
-bash: line 1: SSH-2.0-OpenSSH_8.2p1: command not found

Upvotes: 4

Views: 4414

Answers (1)

shehz
shehz

Reputation: 51

I just solved this exact problem from another answer.

Here is the link to it: https://superuser.com/questions/1633430/ssh-config-with-dynamic-ip

Relevant bit:

ProxyCommand acts as an alternative for the raw TCP connection. It doesn't replace the whole SSH connection

%p will substitute the port for ssh, you can add IdentityFile and all other ssh_config file options.

Here is something that may work for you, in ~/.ssh/config add these lines

Host MyHost
    User minikf
    CheckHostIP no
    ProxyCommand bash -c "nc $(~/.ssh/vm-connect) %p"

Then just echo the host address from your script located in ~/.ssh/vm-connect

#!/bin/bash
get_host() {
    gcloud compute instances describe <vm-name> --zone europe-west1-b --format='get(networkInterfaces[0].accessConfigs[0].natIP)'
}

echo get_host

I have added CheckHostIP no so that ssh will not throw a warning when IP address is different from the one stored in known_hosts. This is optional.

Upvotes: 5

Related Questions