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. 👋

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

More about me ➡️

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

Bootstrap Cloud-Native bootstrappers like Crossplane with K3d - Automation

I created a logo for the Crossplane Bootstrapper because all good projects deserve a logo. 😁 TL;DR ...

Popular Posts

Blog Archive