Ansible Dynamic Inventory with NodeJS
Dynamic Inventory Requirements
The most famous programing language is Python used to develop a dynamic Ansible inventory.
However, I am showing here that it is possible to do that with NodeJS and any other language. The most important thing is to comply with dynamic inventory requirements:
- The file must be executable (
chmod +x inventory/myfile.py
) - The file content must start by shebang (i.e:
#!/usr/bin/python
) - When it is called with “ — list” option, the stdout must be a JSON object presents all groups, and each group is an array of hosts names.
- When it is called with “ — host <myhost>”, the stdout must be JSON object presents all variables of the specific host myhost.
- The file extension is not ignored by Ansible configuration under the attribute
inventory_ignore_extensions
`
Requirements Compliance with NodeJs:
- The file must be executable (
chmod +x inventory/myfile.js
) - The file content must start by shebang (i.e:
#!/usr/bin/node
) . Check the right path by running (which node
)) - “.js” must not be listed under
inventory_ignore_extensions
Example
- Download the lab environment and checkout the relevant branch:
git clone -b dynamic-inventory-nodejs https://github.com/abdennour/infra-4-ansible.git
2. Follow README to configure the app (generate ssh-key,….)
This is Optional as we are only playing with inventory.
3. Run the lab environment docker-compose up -d
4. Go to the control node : docker-compose exec controlnode ash
You should see the PS1 of the container /playbook #
`
5. Inspect the content of inventory/dynamic_hosts.js
/playbook # cat inventory/dynamic_hosts.js
a. The first line is the shebang
b. “const option = process.argv[2];” to parse the value of the first agrument: --list
or --host
c. If it is --host
, “const hostName = process.argv[3];” is to parse the hostname.
d. “const printer = (data) => console.log(JSON.stringify(data))” : To print data on the STDOUT in JSON format not JS object format.
6. Play with this file:
>> --list
option:
/playbook # inventory/dynamic_hosts.js --list{"webservers":["web1","web2"],"databases":["db1","db2"]}
>> --host
option:
/playbook # inventory/dynamic_hosts.js --host web1{"webserver":"apache","welcomeMessage":"Hello Here"}
7. Validatation with ansible-inventory
` command :
ansible-inventory --list
And
ansible-inventory --host web1