import Ansible inventory from Spacewalk

Ansible supports dynamic inventories, if you have Spacewalk and Ansible installed on different machines, the Paython script provided by Ansible Github doesn’t work.

You need to configured SSH with no password authentication between both hosts before running the script.

#!/usr/bin/bash
#copy this file to /etc/ansible/hosts or call it using ansible command with -i (Exa: ansible all -i <inventory file path>  -m ping)
spacewalk_server=
while (( $# > 0 ))
do
case $1 in
--list) PARM="list"
;;
--host) PARM="host"; L_HOST=$2
;;
-l) PARM="list"
;;
-h) PARM="host"; L_HOST=$2;break
;;
*) break
;;
esac
shift
done
if [ "$PARM" == "list" ]; then
ssh $spacewalk_server spacewalk-report inventory | sed -e 's/ /_/g' | awk -F, 'BEGIN { printf "{ \n \"_meta\": { \n \"hostvars\": { \n" }{ if (NR=="1")
{for (i=1;i<=NF;i++) header[i]=$i} else{ print "\""$3"\": {"; for (i=1;i<=NF;i++) { if (i==NF) {srv_var[i]=$i; printf "\t\"%s\" : \"%s\" \n",header[i],srv_var[i]} else { srv_var[i]=$i; printf "\t\"%s\" : \"%s\", \n",header[i],srv_var[i]} } print " },"}}END{ printf "}, \n }, \n" }' #echo "{" ssh $spacewalk_server spacewalk-report system-groups-systems | sed -e 's/ /_/g' | awk -F, 'BEGIN{ gid=$1; hosts_num=0 } { if($1!="group_id") { host_list[$3]=$4; group_list[$1]=$2; if(gid==$1){if (hosts_num > "0") {printf ",\"%s\"",$4; hosts_num++} if (hosts_num=="0") {printf ",\"%s\"",$4; hosts_num++} } if(gid!=$1 && NR>1) { if (NR>2) print "],\n"; printf " \"%s\": [\"%s\"",$2,$4 ;gid=$1}}}END{printf "],\n\n \"ungrouped\": [ ], \n \n \"all\": { \n \"hosts\": [";j=0; for (i in host_list) { if (j==0) { printf"\"%s\"",host_list[i]; j=1 } else {printf",\"%s\"",host_list[i]} };print "],"; printf "\n \t \"children\": [\"ungrouped\" "; for (i in group_list) {printf",\"%s\"",group_list[i]} printf "] \n } \n}\n"}'
elif [ "$PARM" == "host" ]; then
ssh $spacewalk_server spacewalk-report inventory | sed -e 's/ /_/g' | awk -F, -v linux_host=$L_HOST '{ if (NR=="1") {for (i=1;i<=NF;i++) header[i]=$i}
else{ if ($3==linux_host) { print "{"; for (i=1;i<=NF;i++) {srv_var[i]=$i; printf "\t\"%s\" : \"%s\" \n",header[i],srv_var[i]}
print " }" } }}'
fi

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s