0
votes

I currently run my playbooks via

# ansible-playbook -i myscript.py myplaybook.yaml

where myscript.py generates the relevant host information (per the documentation) and myplaybook.py starts with

---
- hosts: all
(...)

This works fine.

I now would like to

  • receive the inventory via a web service: include within the playbook a call to the web service and receive the inventory in the appropriate format, whatever it is (I control the web service)
  • as well as make use of this inventory directly within the playbook, without the -i parameter, having the host: all directive understand that it is supposed to use it.

Is this something which is possible in ansible? I am under the impression that the inventory is needed at the start of the playbook (= that it cannot be generated within the playbook)

1

1 Answers

2
votes

You can create your inventory dynamically with add_host module.
Start with something like this and modify it to your needs:

---
- hosts: localhost
  tasks:
    - add_host: name={{item}} group=hosts_from_webservice
      with_url: https://mywebservice/host_list_as_simple_strings
      # in this example web service should return one ip/hostname by line:
      # 10.1.1.1
      # 10.1.1.2
      # 10.1.1.3

    - add_host: name={{(item | from_json).host}} group=hosts_from_webservice description={{(item | from_json).desc}}
      with_url: https://mywebservice/host_list_as_json_strings
      # in this example web service should return JSON object on every line:
      # {"host":"10.1.1.1","desc":"hello"}
      # {"host":"10.1.1.2","desc":"world"}
      # {"host":"10.1.1.3","desc":"test"}

- hosts: hosts_from_webservice
  tasks:
    - debug: msg="I'm a host from webservice"