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 ( )
  • The file content must start by shebang (i.e: )
  • 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 `

Requirements Compliance with NodeJs:

  • The file must be executable ( )
  • The file content must start by shebang (i.e: ) . Check the right path by running ())
  • “.js” must not be listed under

Example

  1. Download the lab environment and checkout the relevant branch:

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

4. Go to the control node :

You should see the PS1 of the container `

5. Inspect the content of

a. The first line is the shebang

b. “const option = process.argv[2];” to parse the value of the first agrument: or

c. If it is , “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:

>> option:

/playbook # inventory/dynamic_hosts.js --list{"webservers":["web1","web2"],"databases":["db1","db2"]}

>> option:

/playbook # inventory/dynamic_hosts.js --host web1{"webserver":"apache","welcomeMessage":"Hello Here"}

7. Validatation with ` command :

ansible-inventory --list

And

ansible-inventory --host web1

Software engineer, Cloud Architect, 5/5 AWS|GCP|PSM Certified, Owner of kubernetes.tn

Software engineer, Cloud Architect, 5/5 AWS|GCP|PSM Certified, Owner of kubernetes.tn