Create an ansible format inventory

Here we will see how to create an ansible format inventory using a bash script. As we know it’s very important to make sure that your inventory file should be up-to-date and should be in a specific format so it’s easier to run multiple playbooks using the same Inventory file.

Create an ansible format inventory
An Image containing the bash script to create an ansible format inventory. Don’t worry, the same script is listed as text below so you can copy it 🙂

Let’s say you have a playbook to stop services on web servers and there is another playbook that starts MySQL service on database servers. However, you don’t want to create a separate inventory file for each playbook because it’s difficult to maintain. So what you will do is create an ansible format inventory file as below.




As shown above, all the servers are separated into different categories. So you can mention in the playbook the name of the server category where the actions need to be performed. In this way, you can use the same inventory file for many playbooks

hosts : app

However, it’s difficult to create an ansible formatted list, especially when you have exported a list from somewhere in the .csv format. In most cases, your list would look like as below.

If you try to manually update this list especially when the list is long, then it would take years. However, you can use the below bash script that will convert the list into an ansible format.

How to convert the list into an ansible format using Bash?

Script Usage.

Create a file named raw_inventory.txt and put all the servers. As shown below.

Create another file called and copy the below script. Make sure that raw_inventory.txt and are in the same directory.

# Script to format list of servers into ansible format.
 while read nameX
 do label="${nameX%%[.0-9]*}"
    if [[ "$label" != "$last" ]]
    then echo "[$label]" # or printf "\n$label\n" for a separator line
    echo "$nameX"
 done < $file > Inventory 

As you would do for any bash script, make sure you assign execute permission.

$ chmod +x

And now finally run it.

$ ./

In the same directory, you will see there is a file generated called Inventory which contains the formatted list same as below.


Also, look at How to pass extra variables to the Ansible playbook which will be helpful when you are trying to make your scripts more dynamic.

Leave a Comment