Ansible is a great tool for managing configuration across a fleet of compute resources, but it struggles with dynamic sets of compute that are constantly being destroyed and spawned since it the user has to maintain a static list of hostnames.

I’ve brought together some scripts to make it trivial to connect Ansible to your Google Cloud compute infrastructure:

https://github.com/joeheaton/ansible-gcp

Clone the repo and edit inventory.gcp.yml:

---
plugin: gcp_compute
projects:
  - MY-PROJECT
auth_kind: application
keyed_groups:
  - key: labels
    prefix: label
  - key: zone
    prefix: zone
  - key: (tags.items|list)
    prefix: tag
groups:
  gke: "'gke' in name"
compose:
  # set the ansible_host variable to connect with the private IP address without changing the hostname
  ansible_host: name

The only variable you need to change here is the projects list, listing the Google Cloud projects that you want Ansible to manage.

Now let’s install Ansible and the Google Cloud dependencies:

# Create a Python virtual env in ./venv/
python3 -m venv venv
# Activate the virtual env
source venv/bin/activate
# Install dependencies: ansible, google-auth, pywinrm, requests
python3 -m pip install -r requirements.txt

When you’re ready to test the connection, run:

ansible-playbook -v -i inventory.gcp.yml test.playbook.yml

The first time you run this each day you will be prompted for your Google account password.

I hope you find this useful!