2

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

1 Answers1

5

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.

shehz
  • 51
  • 1
  • 3
  • 1
    The echo is incorrect. Also, the function is not needed - just the raw gcloud command. Note that on my system, I needed to provide the path to the gcloud binary. Also `StrictHostKeyChecking no` is useful to avoid the warning that the key has changed with every reboot of the GCP instance – SiHa Jul 06 '22 at 11:00