geerlingguy / ansible-for-devops

Ansible for DevOps examples.
https://www.ansiblefordevops.com
MIT License
8.36k stars 3.44k forks source link

Chapter 9 (DigitalOcean Provisioner): add_hosts task fails due to changes in the DO API #469

Open ellisgeek opened 2 years ago

ellisgeek commented 2 years ago

In Chapter 9 when setting up the digital ocean provisioner I ran into an issues with the task "Add DigitalOcean hosts to inventory groups." because the jinja template "{{ item.1.data.ip_address }}" was failing to return the ip of the droplet.

It turns out this is because DO has changed their api a little bit and now returns a networks dict. See the stripped example json below

{
  "created_droplets": {
    "results": [
      {
        "data": {
          "droplet": {
            "name": "a4d.lamp.varnish",
            "networks": {
              "v4": [
                {
                  "gateway": "yyy.yyy.yyy.yyy",
                  "ip_address": "yyy.yyy.yyy.yyy",
                  "netmask": "255.255.240.0",
                  "type": "private"
                },
                {
                  "gateway": "xxx.xxx.xxx.xxx",
                  "ip_address": "xxx.xxx.xxx.xxx",
                  "netmask": "255.255.240.0",
                  "type": "public"
                }
              ],
              "v6": []
            }
          }
        }
      }
    ]
  }
}

I did some digging and came up with the following.

- name: Add DO Hosts to inventory groups
  add_host:
    name: "{{ (item.1.data.droplet.networks.v4 | selectattr('type', 'equalto', 'public') | first).ip_address }}"

Edit: I found #457 after making this and it looks like the solution there is more complete and it is indeed not fixed in version 1.14.

geerlingguy commented 2 years ago

Indeed, I've tested and confirmed this to be the case (it also broke one of my own playbooks that I run ever few months). Annoying that the attribute is now buried pretty deep, but I guess it's part of their push to make the networking for Droplets more robust / less public-IP-centric.