google-cloud-platformgoogle-compute-enginegoogle-kubernetes-enginegce-instance-group

How to set environment variables on the VMs at managed instance group level


We are using queue based managed instance scaling. We need to setup environment variables on the VMs by instance-groups (so that same VM image can be used to subscribe to different queues in different instance-groups). I don’t see the option to define an environment variables when I create an instance-group.

Is there a way to use the same image across multiple instance groups and still achieve different VM behavior based on either different environment variable at instance group level or some other way?

Example: Create 2 managed-instance-groups with the same VM image. One has environment variable 'queue-name' set to 'queue-1' and the other has 'queue-name' set to 'queue-2'. The application deployed to the VMs in first instance-group pulls tasks from pub/sub queue 'queue-1' and on other group pulls tasks from 'queue-1'.


Solution

  • Using two templates same VM image

    In order to create two instances groups with the same VM image having a different behaviour you can definitely make use of two different instance templates.

    In this way you will be able to change networking configuration, startup and shutdown scripts or metadata.

    For example you could make use of a startup script to set up the different environment variables and in this way connect to one. Fort example like here.

    Using same Template same VM image

    On the other hand if you cannot make use of two different templates I would propose a small hack but I guess there are several ways to do it.

    As you noticed there is no a direct way to do it (since there is the possibility to customise already in the template creation).

    I would add in the startup script a small portion of code that making use of the gcloud command understand which is the name of the instance group it belongs to and basing itself on this info set up in different ways an environment variable.

    In this way you will need merely to follow some kind of pattern naming your instances, but I am sure you can find more elegant solution.

    Or you could even base your decision on the hostname of the machine (but I like this solution even less).