How to automatically run a python script when Google Cloud Compute Instance starts

I would like to have gcp turn on my instance in the morning and run a python script all day without me using ssh. I have added the startup-script metadata to the instance I have also added a cronjob to the Linux side but none of it works so please could someone help me. p.s I’m new to Linux and GCP

[my shell script]

#!/bin/bash
cd '/home/issaca/main/'
nohup python3 main.py &

Answer

You need to:

  • have a script stored on the vm

sudo cat /root/main.py

#!/usr/bin/env python3
from time import sleep
while True:
    sleep(5)
  • metadata startup-script to run your script on startup:
#!/bin/bash
/root/main.py

Then if you can check whether your script is running with

sudo ps aux | grep [m]ain

or

pgrep -a -u root python3

if your script is not running, check the logs with sudo journalctl -u google-startup-scripts.service or in the /var/log/[messages,syslog,daemon].log files.