I know that Ansible could use as inventory virtually anything, including scripts. However, all inventories on my day job are static, and we keep them in a source repository, and until now, I haven't had a chance to create or use one.
- Script should accept at least two arguments:
- --list - return all hosts as a response
- --host <hostname> - return a singe host
- The script result is valid invnetory JSON data
Lets combain all we have learned and create a simple dynamic inventory script with two groups, one static and one dynamic.
Script accepts required parameters and returns group and hstnames only for the --list argument, otherwise it returns an empty (almost) JSON object. To demonstrate the dynamic nature of the script I use special environment variable $RANDOM. For odd number script returns a list ["localhost] and empty list for even numbers. On the screenshot below, you may see a different set of targets for the same command.
Athough, this code is merely a demonstration of capabilities, some advanced version could be useful fo automated collection or module tests.
Sample code and playbook are published on the site Github project.