L'idée de ce script est de générer à la demande un fichier hosts pouvant être utilisé par Ansible contenant l'inventaire des serveurs gérés par spacewalk.

create_ansible_list.py :

#!/usr/bin/python

from __future__ import with_statement

import xmlrpclib
import getpass
import os
import fnmatch
import datetime
import time
import sys
import random
import ConfigParser
import base64
import logging

__author__ = "Sebastien Simonek"
__version__ = "1"
__maintainer__ = "Sebastien Simonek"
__email__ = "sebastien.simonek@coface.com"

"""
    create_ansible_list
    This script creates a list of groups with attached servers for ansible use.
    For question about api params, please connect to https://spacewalk/rhn/apidoc
"""


# Retrieve connection information from file
config = ConfigParser.ConfigParser()
config.read("/usr/local/etc/spacewalk-api.conf")
SATELLITE_URL = config.get("main", "SATELLITE_URL")
SATELLITE_LOGIN = config.get("main", "SATELLITE_LOGIN")
SATELLITE_PASSWORD = base64.b64decode(config.get("main", "SATELLITE_PASSWORD"))


# login to spacewalk, key is used by each api call (ie session)
client = xmlrpclib.Server(SATELLITE_URL, verbose=0)
key = client.auth.login(SATELLITE_LOGIN, SATELLITE_PASSWORD)


def get_servers_in_group(key, group):
    """
        Return an array of servers that belong on the specified group.
    """
    try:
        servers = client.systemgroup.listSystems(key, group)
        return servers
    except Exception as e:
        logging.error(traceback.format_exc())


def get_groups(key):
    """
        Return an array of spacewalk groups.
    """
    try:
        groups = client.systemgroup.listAllGroups(key)
        return groups
    except Exception as e:
        logging.error(traceback.format_exc())


try :
    #List groups defined in spacewalk
    groups = get_groups(key)

    # for each group, list servers and generate the hosts file
    try:
       # create a new file
       host_file = open('/etc/ansible/hosts', 'w+')
       host_file.write("### DON'T EDIT THIS FILE, IT IS AUTOMATICALY CREATED BY SPACEWALK ###\n")
       for group in groups:
           servers = get_servers_in_group(key, group['name'])
           host_file.write("[%s]\n" % group['name'])
           for server in servers:
               host_file.write("%s\n" % server['hostname'])
           host_file.write("\n")
    except IOError :
        logging.error(traceback.format_exc())
    finally:
        host_file.close()
finally:
        client.auth.logout(key)

Le fichier de config :

/usr/local/etc/spacewalk-api.conf

[main]
SATELLITE_URL = http://spacewalk/rpc/api
SATELLITE_LOGIN = user
SATELLITE_PASSWORD = cGFzc3dvcmQ=


Vous pouvez cronner la génération du fichier pour avoir un inventaire à jour.

Il est alors possible de lancer des commandes ansibles sur les groupes spacewalk.

Exemple:

uptime des serveurs RHEL7 de dev :

root@ansible-server: (~)# ansible "RHEL7:&DEV" -a uptime

Et voilà ;)