mercredi 11 mars 2020

Generate ansible host file from redhat satellite

Hi,

Here is a little script to generate ansible host list from redhat satellite.
The idea is to use HostCollection to create ansible groups.

You need to have hammer installed on the server.
My satellite-api.conf contains this keys:

   [main]
   SATELLITE_URL = https://mysatellite.domain.dns
   SATELLITE_LOGIN = ****************
   SATELLITE_PASSWORD = *****************
   SATELLITE_ORG = myOrg


Here is the script

#!/bin/bash 

fn_isHammer() {
    if [ ! -f /usr/bin/hammer ]
    then
       echo "Error: hammer is not installed on this machine"
       exit -1
    fi
}

fn_isConfFile() {
    if [ ! -s /usr/local/etc/satellite-api.conf ]
    then
       echo "Error: satellite-api.conf not found"
       exit -1
    fi
}


fn_getConfig() {
    fn_isConfFile
    login=$(grep SATELLITE_LOGIN /usr/local/etc/satellite-api.conf|awk  '{print $NF}')
    password=$(grep SATELLITE_PASSWORD /usr/local/etc/satellite-api.conf|awk '{print $NF}')
    url=$(grep SATELLITE_URL /usr/local/etc/satellite-api.conf|awk '{print $NF}')
    ORG=$(grep SATELLITE_ORG /usr/local/etc/satellite-api.conf|awk -F= '{print $NF}')
}

fn_getHostsByCollections() {
    for HC in $(hammer --no-headers -u $login -p$password \
                     -s $url host-collection list | awk '{print $3}')
    do
       echo "[${HC}]"
       hammer --no-headers -u $login -p$password -s $url \
                     host-collection hosts --name "${HC}" \
                     --organization $ORG | awk '{print $NF}'
       echo ""
    done
}

main() {
    fn_isHammer
    fn_getConfig
    fn_getHostsByCollections
}

main




Now just run the script by redirecting the output in a file:



/usr/local/bin/getHostList.sh > /tmp/myInventoryFile




The script will produce inventory like this (depends on your host collections)


[rhel7]
server1
server2
server3

[webservers]
server2
server3

[dbhost]
server1


Now you can use the inventory file with ansible:



ansible -i /tmp/myInventoryFile -l "webservers:&rhel7" -m ping

 




Aucun commentaire:

Enregistrer un commentaire