Search code examples
bashgoogle-cloud-platformgoogle-compute-enginegcloud

gcloud compute ssh --command flag not working


I am using google's compute ssh command from compute engine's vm1 to connect another project's vm2. The problem occur when i try to connect with --command flag. The shell command is not executed but ssh connection is established. However i can see the bash command in the processes of vm2 as pid =xxxx 'bash -c sudo su && service nginx stop && source /home/x/bin/activate && python example.py' When i terminated the ssh command from vm1, the bash command immediately starts on vm2. I could not figure it out what cause this problem.

sudo gcloud compute ssh --project=project_name vm_name --zone=zone --command='sudo su && service nginx stop && source /home/x/bin/activate && python example.py'

OS: ubuntu 18.04


Solution

  • That command set won't work. You're approaching it as if you were the one running the commands inside a terminal, in which case:

    • sudo su (would get you a root shell and all subsequent commands would run as root)
    • service nginx stop (you're root)
    • source /home/x/bin/activate (you're root)
    • python example.py (you're root)

    When you try to chain your commands with &&, it runs the next command after the first one worked and all the commands are actually being run as you:

    • sudo su (run as you, when this exits successfully, trigger next command)
    • service nginx stop (as you)
    • etc (as you)

    So what ends up happening is you get a root shell and then nothing. Unless that exits (cleanly), you won't run the next command in the chain and so you're waiting, because the root shell is also waiting. As @DazWilkin mentioned above, what you should actually be doing is removing the sudo su (you don't need a root shell, you can't do anything in there anyway) and preface your other commands with sudo instead so that they are each run with elevated perms.