Ansible GCP Dynamic inventory

What?

Allows for the auto discovery of VMs from within Ansible so playbooks can directly refer to them

Basic steps

  1. Ensure the dependencies are installed
pip install requests google-auth
  1. Enable gcp_compute plugin in ansible.cfg
[inventory]
enable_plugins = gcp_compute
  1. Create a file that ends with “gcp.yml” (e.g inv.gcp.yml) with the following contents (remembering to replace with the actual project_id). In this example we use the default service account on the machine.
plugin: gcp_compute
projects:
  - REPLACE_WITH_PROJECT_ID
auth_kind: machineaccount
service_account_email: default
keyed_groups:
  - key: labels
hostnames:
  - name
  1. Test it as follows
ansible-inventory --list -i inv.gcp.yml

References