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.

[app]
app.server.com
app2.server.com

[web]
web1.server.com
web2.server.com

[databases]
db1.server.com
db2.server.com

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.

app.server.com
app2.server.com
web1.server.com
web2.server.com

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

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

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

$ chmod +x script.sh

And now finally run it.

$ ./script.sh

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

[app]
app.server.com
app2.server.com
[web]
web1.server.com
web2.server.com

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.

Spread the love

Leave a Comment