I am trying to write script that starts VM, run a command and then stop it.
The code is (the project and zone are omitted for brevity):
gcloud compute instances start instance-1
gcloud compute ssh user@instance-1 --command 'echo check-ssh' -- -vvv
gcloud compute instances stop instance-1
When I run those steps in a terminal everything is going well, but when I run it through a file the ssh command fails fails and I get:
OpenSSH_8.2p1 Ubuntu-4ubuntu0.1, OpenSSL 1.1.1f 31 Mar 2020
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: include /etc/ssh/ssh_config.d/*.conf matched no files
debug1: /etc/ssh/ssh_config line 21: Applying options for *
debug2: resolve_canonicalize: hostname 34.68.81.200 is address
debug2: ssh_connect_direct
debug1: Connecting to 34.68.81.200 [34.68.81.200] port 22.
debug1: connect to address 34.68.81.200 port 22: Connection refused
ssh: connect to host 34.68.81.200 port 22: Connection refused
ERROR: (gcloud.compute.ssh) [/usr/bin/ssh] exited with return code [255].
The instance os is ubuntu 20.4.
something that may connect to this problem, when I try to connect to the root user through the terminal I get the same error.
Someone know what is the difference? how can I solve it?
When you request the gcloud compute instances start of a GCP Compute Instance you are literally requesting that it start and not that it has actually started. If you then turn around and perform an SSH request,the VM may not have reached an internal state where it is ready to receive SSH requests. Try putting a sleep delay between your VM start and SSH access (say ... 5 minutes) ... and see if that changes the story.
See also: