Cloud administrators and DevOps Engineers should know how they can run a 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 startup 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 shown an example to add startup script.
In this script, if you need any configuration file or anything from the GCS bucket you should give proper access to instance to connect to Google APIs to get the configuration file from the GCS bucket.
Method 2: Pass script in Metadata
This is also a recommended way this will be useful in lots of automation. In the 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 a startup script path in the 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 automation. Also, you can get the logs from system logs.
We should make sure instances have access to connect to GCS when we take the script from GCS[Google Cloud Storage].
We can also use shutdown-script metadata to run a script when the shutdown happens. This will help us to collect lots of information about the shutdown or termination if it is in the 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.