24/06/2015

Ansible module to list groups in inventory - Bash/AWK

Something I just remembered, just for fun, I created another versions of "Ansible module to list groups in inventory - Python" but with Bash, and AWK :D

As I mentioned in the other post, you can write Ansible modules with any language, actually Ansible does not care about language that used in modules, JSON output is just what matters. So I did the same function with Bash and AWK, but that was just for fun, ok? :D

AWK version:
#!/bin/bash
#7 minutes Ansible module to list groups in inventory (AWK version) :D
#You can view outupt of script like "JSON Pretty Print" outside Ansible by using:
#./listgroups | python -m json.tool 

awk 'BEGIN {ORS=" "};
     /^\[/{
       gsub(/[\[\]]/,"");
       groups_number++;
       groups_array[groups_number]=$0
     };
     END {
       print "{\"Inventory Groups\": [";
       for (group_in_array = 1; group_in_array <= groups_number-1; group_in_array++)
           printf "\"%s\", ",groups_array[group_in_array];
           printf "\"%s\"",groups_array[groups_number];
       print "]}"
     }' /etc/ansible/hosts

Bash version:
#!/bin/bash
#3 minutes Ansible module to list groups in inventory (Bash version) :D
#You can view outupt of script like "JSON Pretty Print" outside Ansible by using:
#./listgroups | python -m json.tool

inventory_file=$(awk '/^hostfile/{print $3}' /etc/ansible/ansible.cfg)
groups_array=($(awk 'BEGIN {ORS=" "}; /^\[/{gsub("[[]]",""); print}' $inventory_file))

init_array_for_json () {
for group in ${groups_array[@]}; do
  printf "\"$group\",";
done
}

printf "{\"Inventory Groups\": [$(init_array_for_json)]}" | sed 's/,]/]/g'

This is why I love Bash and AWK, they are always quick and handy :D
Powered by Blogger.

Hello, my name is Ahmed AbouZaid, I'm a passionate Tech Lead DevOps Engineer. 👋

With 16+ years of open-source contributions, 12+ years of professional hands-on experience in DevOps, and an M.Sc. in Data Engineering from Edinburgh Napier University (UK), I enjoy facilitating the growth of both businesses and individuals.

I specialize in Cloud-Native and Kubernetes. I'm also a Free/Open source geek and book author. My favorite topics are DevOps transformation, automation, data, and metrics.

Contact Me

Name

Email *

Message *

Start Your DevOps Engineer Journey!

Start Your DevOps Engineer Journey!
Start your DevOps career for free the Agile way in 2024 with the Dynamic DevOps Roadmap ⭐

Latest Post

2023 Highlights

Image generated with Craiyon . Finally, 2023 is over! What a year! One more crazy year, but it was the culmination ...

Popular Posts

Blog Archive