Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting python script on Google Cloud Compute instance startup

I've been trying to find the best way to start a python script on startup of my cloud compute instance. So far, I haven't gotten it to run. The script does run when manually executed on the instance. I did make the file executable.

This is what I have tried so far:

1) Add script directly to metadata with key "startup-script". Script starts with:

#! /usr/bin/python3

Followed by the script contents.

Result: Won't run, doesn't show up in log.

2) Try to execute local script from metadata with key "startup-script":

#! /usr/bin/bash"
/home/dir/scripts/script.py.

Result: Won't run, doesn't show up in log.

3) Point to file located in storage bucket with "startup-script-url".

gs://project.appspot.com/folder/script.py

Result: Won't run, but shows "Found startup script" in log.

I hope anyone has some insights.

like image 785
Max Avatar asked Jan 25 '26 23:01

Max


1 Answers

This worked for me:

#! /bin/bash
cat <<EOF > /var/myScriptStackOverflow.py
with open("/var/python_was_here_stack_overflow.txt", "w") as file:
    file.write("Looks that the script is executed")
EOF
python3 /var/myScriptStackOverflow.py

The script above is explicit in respect to the paths, but this also works:

#! /usr/bin/python3
with open("/var/python_was_here_stack_overflow.txt", "w") as file:
    file.write("Looks that the script is executed this way as well...")

  • Edit the instance, paste the script above in the Custom metadata with the key startup-script:

enter image description here

  • Reset the instance
  • ssh inside the instance to check the results:
ls -la /var | grep -i py
-rw-r--r--  1 root root   119 Aug  3 17:33 myScriptStackOverflow.py
-rw-r--r--  1 root root    33 Aug  3 17:33 python_was_here_stack_overflow.txt
cat /var/myScriptStackOverflow.py 
with open("/var/python_was_here_stack_overflow.txt", "w") as file:
    file.write("Looks that the script is executed")
cat /var/python_was_here_stack_overflow.txt 
Looks that the script is executed
like image 117
Neo Anderson Avatar answered Jan 28 '26 13:01

Neo Anderson