Search code examples
sshvirtual-machinegcloudprivate-network

Is there a way to execute commands remotely using gcloud compute ssh utility


I know it is possible to execute commands remotely using ssh (in a file) like so;

#!/bin/sh

ssh ${USER}@${SERVER_IP} <<EOF
 cd ${PROJECT_PATH}
 git pull
 exit
EOF

my question is this: it possible to do the same with gcloud compute ssh? I mean;

gcloud compute ssh vm-internal --zone us-central1-c --tunnel-through-iap << EOF
...
...
EOF

PS: The instance is private with no external IP hence the use of iap


Solution

  • As long as you can ssh onto the instance, you should be able to:

    gcloud compute ssh .... --command="bash -s" <<EOF
    echo "Hello Freddie"
    ls -l
    EOF
    

    You can test this (thanks to gcloud consistency using Cloud Shell):

    gcloud alpha cloud-shell ssh --command="bash -s" <<EOF
    echo "Hello Freddie"
    ls
    EOF
    

    NOTE you may not need the -s but I think it's preferred

    Yields:

    Automatic authentication with GCP CLI tools in Cloud Shell is disabled. To enable, please rerun command with `--authorize-session` flag.
    Hello Freddie
    Projects
    README-cloudshell.txt -> /google/devshell/README-cloudshell.txt
    stackoverflow