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 and this is my "lite" technical blog!

I'm a passionate DevOps, Linux system administrator, RedHat Certified Engineer (RHCE), AWS SysOps/Solutions Architect, Free/Open source geek, author, interested in environment, calligraphy, and I believe that “Details Matter”!

Automation, data, and metrics are my preferred areas. I have a built-in monitoring chip, and too lazy to do anything manually :D

Popular Posts