Instance templates are global resources in GCP i.e the same template can be used to create managed instance groups in any regions in the GCP. However if a zone is specified in the template, then that template can be used only in that particular zone.
Instance templates define the machine type, image, identity tags and other instance properties. This is done to maintain the identical instances in the managed instance group. Later, this instance group can be used for creating an autoscaling group and can also be load-balanced.
Instance template can be created either in console or with gcloud like this:
gcloud compute instance-templates \
create sample-template \
--image CentOS 6 \
--tags http \
--scopes=sql-admin,storage-ro,logging-write \
--metadata startup-script-url=\
gs://<bucket-name>/<startup-script>.sh,\
<other-variable>=<value>
The above command creates an instance template based on CentOS 6 image, with a tag, some scopes and an startup script.
- The compute engine's default service account has permissions(scope) for reading the buckets from the same project and writing logs to stackdriver. When you override the scope, make sure you also specify the default scopes namely storage-ro and logging-write.
- Startup scripts are the best way to configure your instance like installing some packages, starting up a docker container and so on.
- Other metadata can also be specified which can be used in the compute engine for some other purposes.
- Firewall rules can also be specified in the form of tags. In the above eg, the http tag allows ingress traffic on port 80.
- Other customisations like setting up the network, sub-network, disk sizes can also be specified in the template configuration.
Best Practices: From my perspective, it is better to create a custom image with all your software installed than to use a startup script. As the time taken to launch new instances in the group should be as minimum as possible. This will increase the speed at which you scale your web app.
This is part 1 of 3-part series about building an autoscaled, load-balanced backend.