Ni hao ma ?

Aller au contenu | Aller au menu | Aller à la recherche

lundi 14 novembre 2016

PYTHON - Générer un fichier host pour ansible depuis l'inventaire spacewalk

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à ;)

jeudi 1 septembre 2011

Weblogic - Script python pour avoir le status d'un domaine Weblogic

# ==============================================================
# domain_status.py
# ==============================================================
# ==============================================================
# recuperation des arguments passe en option
#
# ==============================================================
adminurl = sys.argv[1]
username = sys.argv[2]
passwd = sys.argv[3]

# ==============================================================
# connection a admin weblogic
#
# ==============================================================

def connect_weblogic(username,password,adminurl):
        try :
                connect(username,password,adminurl)
        except :
                print 'Cannot connect to ' + adminurl
                exit()

# ==============================================================
# lecture des MBEAN
#
# ==============================================================

def getMBeanByType(mbeanType):
    return adminHome.getMBeansByType(mbeanType)

# ==============================================================
# formatage de date
#
# ==============================================================

def fmtDate(t):
        from time import *
        return strftime("%d/%m %H:%M:%S",localtime(t))

# ==============================================================
# connexion et affichage des status
#
# ==============================================================

redirect("/dev/null",toStdOut='false')
connect_weblogic(username,passwd,adminurl)

listeServer = ls('Servers',returnMap='true')

domainRuntime()
listeRunning = ls('ServerRuntimes',returnMap='true')

fmt = "%11s %10s %18s %6s %5s %5s %7s %7s %11s %10s %10s %15s"


print fmt % ("Server","State","Uptime","Active","Idle","Total","Hogging","Standby","Pending Req","QueueLength","Throughput","Completed Req")

for srv in listeServer:
        if listeRunning.size()>0 and listeRunning.indexOf(srv)>=0:
                cd("/ServerRuntimes/"+srv)
                uptime = cmo.getActivationTime()/1000
                tp = getMBean('ThreadPoolRuntime/ThreadPoolRuntime')
                thp = "%.1f" % tp.getThroughput()
                active = 0
                import re
                for thrd in tp.getExecuteThreads():
                        if not re.search("ACTIVE",thrd.getName()) is None:
                                active = active +1

                print fmt % (srv,cmo.getState(),fmtDate(uptime),str(active),str(tp.getExecuteThreadIdleCount()),str(tp.getExecuteThreadTotalCount()),

str(tp.getHoggingThreadCount()),str(tp.getStandbyThreadCount()),str(tp.getPendingUserRequestCount()),str(tp.getQueueLength()),

str(thp),str(tp.getCompletedRequestCount()) )
        else:
                print fmt % (srv,"SHUTDOWN","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A","N/A")

# ==============================================================
# déconnexion
#
# ==============================================================
disconnect()
exit()

Vous pouvez lancer ce script depuis un script shell  :

#! /bin/sh
. /opt/platform103/weblogic/wlsserver_10.3/server/bin/setWLSEnv.sh > /dev/null 2>&1
java weblogic.WLST $*
exit $?

Pour le lancer :

./lancwlst.sh domain_status.py t3://127.0.0.1:7001 reader reader

Initializing WebLogic Scripting Tool (WLST) ...

Welcome to WebLogic Server Administration Scripting Shell

Type help() for help on available commands


 Server    State         Uptime Active  Idle Total Hogging Standby Pending Req QueueLength Throughput  Completed Req
 server  RUNNING     01/09 08:54:37      1     0     6       0       5           0          0        7.5           95204
 admin  RUNNING     31/08 17:51:28      2     1     9       0       7           0          0       11.0          584537

Et Voilà