Utz
Utz

Reputation: 23

gcloud execute commands on remote instance not working as expected

I'm new with gcp and gcloud commands. I'm trying to run the following -

[root@localhost ~]# gcloud compute ssh test --zone=us-central1-a --command=DISK_DEV=`lsblk | grep -i 10g | awk '{print $1}'` ; echo $DISK_DEV

[root@localhost ~]# gcloud compute ssh test --zone=us-central1-a --command="DISK_DEV=`lsblk | grep -i 10g | awk '{print $1}'` ; echo $DISK_DEV"

and it doesn't return the expected output (as it returns null instead of the relevant device).

If I run it on the remote instance, the same command returns the expected output (the device) -

[root@test ~]# DISK_DEV=`lsblk | grep -i 10g | awk '{print $1}'` ; echo $DISK_DEV
sdb

Please advice, Thank you.

Upvotes: 0

Views: 436

Answers (1)

DazWilkin
DazWilkin

Reputation: 40081

gcloud runs on your local host and invokes the command on the remote host.

You're trying to set an environment variable (DISK_DEV) on your local host to reflect the value on the remote host. This doesn't work.

Your command is syntactically incorrect too; you can't --command=[VAR]="...".

See: https://cloud.google.com/sdk/gcloud/reference/compute/ssh#--command

The only way to get this to work is to run the command lsblk | grep -i 10g | awk '{print $1}' and capture the output of the gcloud command and then parse that:

RESULT="$(gcloud ... --command='lsblk ...')"

I don't have an easy way to test the above but RESULT may include additional data from the remote shell that needs to be pruned.

Update

This works:

COMMAND="lsblk | grep -i 10g"

RESULT=$(\
  gcloud compute ssh ${INSTANCE} \
  --zone=${ZONE} \
  --project=${PROJECT} \
  --command="${COMMAND}")

DISK_DEV=$(echo ${RESULT} | awk '{print $1}')
echo ${DISK_DEV}
sda

Upvotes: 3

Related Questions