Cloud administrator and Devops Engineers should know how they can run startup script in Google Cloud instances. We will see about AWS in another post. In this post i will be showing you the different methods to run a start up script in Google cloud instance.
There are multiple methods to run a startup script, But here we see only two major google recommended ways,
Method 1: Startup Script block under Automation
This is the simple and most recommended way to run startup script, Here you can just paste you shell script and it will run when instance bootup time.
Here i have show an example to add startup script.
In this script if you need any configuration file or anything from GCS bucket you should give proper access to instance to connect to google APIs to get the configuration file from bucket.
Method 2: Pass script in Metadata
This is also a recommended way this will be useful in lots of automations. In Metadata section also you can add metadata startup-script-url, you should pass the script file path in this method. For example i have my script in google bucket gs://devopstree-demo/devopstree-demo.sh, If our script is present inside the machine we can just give the path of the script,
This image shows how we should add startup script path in metadata. We should also add other metadata with this as per your compliance.
Once you add the script path and create the instance it will automatically run. This is more helpful in automations. Also you can get the logs from system logs.
We should make sure instance have access to connect to GCS when we take script from GCS[Google Cloud Storage].
We can also use shutdown-script metadata to run a script when shutdown happens. This will help us to collect lots of information about the shutdown or termination if it is in Instance Group. Here you have to give the content of your script. Basically we should paste the content of the script in the value of this shutdown-script key.
Also we can have shutdown-script-url metadata to run a shutdown script from google cloud bucket.