Search code examples
google-cloud-platformansibleansible-inventory

Ansible dynamic inventory keyed groups gcp


I am trying to create a inventory file in ansible which groups all instances according to the instance group in the Google Cloud Platform.

Ansible docs give the following example to group instances according to their labels. When I use this example, it works and shows my instances grouped by their labels.

keyed_groups:
  - prefix: gcp
    key: labels

But I want to group them by their instance groups. I tried a lot of variations of the followin, but none of them worked.

keyed_groups:
  - prefix: gcp
    key: instance-groups

keyed_groups:
  - prefix: gcp
    key: compute_instance_groups

Any idea, what the syntax for my problem is?


Solution

  • The list of hosts is built by the gcp_compute ansible inventory plugin. This plugin examines the set of Compute Engine instances and builds a list. The set of items that we can use as keys is found here:

    If we look at this data, we do not find that a Compute Engine knows what (if any) instance group it belongs to.

    Stepping back, we find that to create an instance group we first create a compute engine template that describes what an instance looks like. Next we create an instance group that references that template. The instance group subsystem at GCP seems to manage groups separately from compute engine instances.

    If you want to be able to learn what instance group a compute engine belongs to, one solution would be to create a label in the template used to create the compute engine. For example:

    • instance_group: MyInstanceGroup

    Once you have done that, instances of compute engine created by the instance group and associated with that template will have a label called instance_group. At that point, you can then use the Ansible inventory plugin to group by labels.

    References: