I am trying to run a script that is on my machine on a Google Compute instance. I'd like the script to connect in and do its work, and was surprised to see behavior from below:
#!/bin/bash
gcloud compute ssh myinstance
echo "blah" > /tmp/test.txt
This script does connect to myinstance
, but it writes /tmp/test.txt
on my machine, not the compute instance. The ssh connection remains when the script ends, my terminal is connected.
I had expected it to connect, write the file to the compute instance, and disconnect from ssh. How do I maintain scripts on my machine and run then against various compute instances easily, by ssh? The main use case is going from Mac to Ubuntu.
WORK_PROJECTS_PATH="$HOME/path"
BACKEND_SCRIPT_NAME="redeploy_backend.sh"
LOCAL_BACKEND_SCRIPT_PATH="$WORK_PROJECTS_PATH/myproject/scripts/deploy/$BACKEND_SCRIPT_NAME"
REMOTE_BACKEND_SCRIPT_TEMP_PATH="/tmp/$BACKEND_SCRIPT_NAME"
REMOTE_BACKEND_SCRIPT_PATH="/home/path/$BACKEND_SCRIPT_NAME"
GCP_INSTANCE="myproject-staging"
gcloud config set project myproject_name
# move current version of script over each time to ensure it's up to date
gcloud compute ssh $GCP_INSTANCE --command="sudo rm -f $REMOTE_BACKEND_SCRIPT_PATH"
# sending to temp path allows you to skip entering the compute instance password
gcloud compute copy-files $LOCAL_BACKEND_SCRIPT_PATH $GCP_INSTANCE:$REMOTE_BACKEND_SCRIPT_TEMP_PATH
gcloud compute ssh $GCP_INSTANCE --command="sudo mv $REMOTE_BACKEND_SCRIPT_TEMP_PATH $REMOTE_BACKEND_SCRIPT_PATH"
gcloud compute ssh $GCP_INSTANCE --command="sudo chmod +x $REMOTE_BACKEND_SCRIPT_PATH"
# run the script on the server from your machine
gcloud compute ssh $GCP_INSTANCE --command="$REMOTE_BACKEND_SCRIPT_PATH"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With