Running bash script on GCP VM instance programmatically

Issue

I’ve read multiple posts on running scripts on GCP VMs but unfortunately could not find an answer that would satisfy my needs.
I have a Go application and I’m looking for a way to run a bash script on a VM instance programatically.
I’m using a Google Cloud Golang SDK which allows me to fetch VM instance info. Unfortunately SDK does not contain a functionality that allows running a bash script on a specific instance(unlike an Azure Cloud SDK for example).

Options I’ve found:

  1. Google Cloud Compute SDK has an option to set a startup script, that
    will run every time an instance is restarted.
  2. Add instance-level public SSH key. Establish an SSH connection and
    run a script using Go SSH client.

Problems:

  1. Obviously startup script will require an instance reboot and this is not possible in my use case.
  2. SSH might be also problematic, in case instance is not running SSH
    daemon or SSH port is not open. Also, SSH daemon config does not
    permit root login by default(PermitRootLogin might be false), thus
    script might be running on a non privileged user, making this option not
    suitable either.

I should probably note that I am not authorised to change configuration of those VMs (for example change ssh daemon conf to permit root login), I can just use a token based authentication to access them, preferably through SDK, though other options are also possible as long as I am not exposing the instance to additional risks.
What options do I have? Is this even doable? Am I missing something?

Thanks!

Solution

As said by Kolban, there is no such API to trigger from outside a bash inside the VM. The best solution is to deploy a webserver (a REST API) that call the bash and to expose it (externally or internally).


But you can also cheat. You can create a daemon on your VM that you run with a startup script and that listen a custom metadata; let’s say check it every seconds.

When the metadata is updated, the daemon can perform actions. You can imagine that the metadata contain the script to run with the parameters. At the end of the run, the metadata is cleaned by the daemon.

So now, to run your bash, call the setMetadata Api. It’s not out of the box, but you can have something similar of what you expected.

Answered By – guillaume blaquiere

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.