Search code examples
google-cloud-platformdebianstartupgnu-screengnu-parallel

How to connect to a gcloud instance and run a command either on startup or consecutively in one line


I'm trying to run a command when I start my gcloud vm server. I added the following command in the console custom metadata key:

startup-script 

value:

#! /bin/bash
parallel 'screen -d -m python3 Documents/myscript.py' ::: arg1 arg2

But when I start the vm instance, it doesn't run because I don't see any screens when I type screen -list. However, when I connect with the gcp tool over SSH using the following command to connect

gcloud beta compute ssh --zone "us-west1-c" "instance-1" --project "unique-kakaw-123456" 

and then run

parallel 'screen -d -m python3 Documents/myscript.py' ::: arg1 arg2

consecutively, it runs properly.

How do I either, get my script to run on start up on gcp, or failing which, use the gcloud command to run the command in the same line so then when I hit enter, it will connect to the server and run the command right after. Because if I put both the above commands in the same line and add a ; it won't work obviously.

For some reason, I can add the script to rc.d and update on my ubuntu pc at home and it works fine. I don't know why it doesn't work on gcp.


Solution

  • The startup script should be working. Here's what could be happening:

    1. Python script is not being executed because it cannot be found

    Compute Engine documentation says:

    The instance always executes startup scripts as root after the network is available.

    So, if the Python script is in your home directory, provide the full path (replace [USER] with the actual user):

    #! /bin/bash
    parallel 'screen -d -m python3 /home/[USER]/Documents/myscript.py' ::: arg1 arg2
    

    2. Python script runs and then exits, so screen terminates the window

    Screen's User Manual says:

    When a program terminates, screen (per default) kills the window that contained it. If this window was in the foreground, the display switches to the previously displayed window; if none are left, screen exits.

    Thus if your Python script exits prematurely, add this to your /etc/screenrc:

    zombie qr
    

    Here is what this parameter does:

    When a string of two keys is specified to the zombie command, ‘dead’ windows will remain in the list.


    For the record, I replicated your startup script configuration in my GCP instance (providing the full path) and I can confirm it does work: there were two screens running with my Python script, each with its own argument.