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 engineer, Cloud/Kubernetes specialist, Free/Open source geek, and an author.

I believe in self CI/CD (Continuous Improvements/Development), also that "the whole is greater than the sum of its parts".

DevOps transformation, automation, data, and metrics are my preferred areas. And I like to help both businesses and people to grow.

Popular Posts