ansibleansible-inventory

Using Consul KV store for inventory details, possible?


Is it possible to use KV information from Consul to populate the inventory during runtime?

I would like to pull KV information from Consul when running ansible-playbooks to populate the inventory with the host and role assignment. Since consul_kv is a lookup plugin I'm assuming it doesn't work for inventory (at least it doesn't when I briefly tested it :) ).

The basic idea is to use --extra-vars and supply the hostname and from there pull the information from Consul.

Just need to know if it's possible using the built-in functions (if so which plugins would be appropriate if needed) or if some sort of workaround is the only way. E.g. create the inventory/role files via a script before running the playbook.


Solution

  • I still think the dynamic inventory is the most correct answer to your question, but if I strictly answer just the one you asked, then you will want to use add_host: to do what you described:

    - hosts: localhost
      connection: local
      gather_facts: no
      tasks:
      - add_host:
          name: '{{ item }}'
          groups:
          - consul_hosts
        with_consul_kv:
        - the/awesome/key/here/{{ and_jinja2_vars }}/or-whatever
    
    - hosts: consul_hosts
      tasks:
      - debug:
          msg: hello from {{ansible_host}}