Ansible  -  GCP dynamic inventory 2.0

The GCP module for Ansible has recently been updated to not rely on libcloud but the docs still continue to be slightly confusing, so I’m publishing a new article on how to set up Ansible GCP dynamic inventory.

As last time this assumes you already have:

First, install “requests” and “google-auth” packages.

pip install requests google-auth

Note: if you use Homebrew, you may need to install the module via the built-in python installation that Ansible uses, e.g.:

λ ansible --version | grep "python.*location"

ansible python module location = /usr/local/Cellar/ansible/2.7.8/libexec/lib/python3.7/site-packages/ansible

λ /usr/local/Cellar/ansible/2.7.8/libexec/bin/pip install requests google-auth

Then, create an inventory file ending in ‘gcp.yml’, e.g.:

λ cat inventory.gcp.yml
---
plugin: gcp_compute
projects:
  - my-project
zones:
  - "europe-west1-b"
filters: []
auth_kind: serviceaccount
service_account_file: "/Users/temikus/.gcp/project.json"

Note: I higly recommend setting the zones: parameter as otherwise the inventory script enumerates all existing zones which takes a considerable amount of time.

And boom, now we can control our instances with Ansible:

λ ansible -i inventory.gcp.yml all -m ping

34.76.50.119 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
 
1
Kudos
 
1
Kudos

Now read this

Tip: ssh `Match exec` and config for cloud instances

If you work a lot with ephemeral instances you will eventually run into this message: @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @... Continue →