Why and when is required?
The dynamic inventories will be useful to get dynamically the hostnames/machines, which means that they are required when the machines/servers can be changed very quickly. In this way, they inventories will be not outdated.
How it works?
The location can be in the
ansible.cfg configuration file. By default, it is configured to be
/etc/ansible/hosts. For further information check Working With Dynamic Inventory
You can find many scripts made by the community. See it here: https://github.com/ansible/ansible/tree/devel/contrib/inventory
Creating your own dynamic inventory
The dynamic inventory scripts can be written in any language, however, it needs to return the result in JSON format and implement some required default parameter/options and be executable by ansible which means that should start with
#!/usr/bin/python for example.
- list: to return all hosts as the following example.
“myservices” : [ “server1.mydomain.com”],
“databases” : [ “mydb1.mydomain.com”]
- host: to return the list of vars/groups which is associated with the hosts.
“myservices” : [ “server1.mydomain.com”]
Check here an example of this implementation.
NOTE: It is important to highlight that the static host need have the declaration of the dynamic group defined in the inventories. Following an example.
[dynamic] # This group is populated by a dynamic inventory. [webserver] web.mydomain.com
For further information see Developing dynamic inventory.