python_wiki:spacewalk_describe

This is an old revision of the document!


Spacewalk Describe

General Information

View/Edit descriptions for Spacewalk registered systems.

Checklist


Usage

sw_describe.py -h

usage: sw_describe.py [-h] [-l] [-e] [-d DESCRIBE] [-n NAME] [-g GROUP] [-t]
 
View/Edit descriptions for Spacewalk registered systems.
 
optional arguments:
  -h, --help            show this help message and exit
  -l, --list            List description(s) of single system or a group.
  -e, --edit            Edit description of a system (single systems only:
                        --name).
  -d DESCRIBE, --describe DESCRIBE
                        Set new description of system (use with --edit).
  -n NAME, --name NAME  Single system name (use with --list or --edit)
  -g GROUP, --group GROUP
                        Spacewalk group or 'all' (use with --list)
  -t, --test            Do not make any changes. Run test and output what
                        would have happened.

The Code

program-name.py
#!/usr/bin/python
# Title: sw_describe.py
# Description: View/Edit descriptions for Spacewalk registered systems
# Date: 2017-06-13
# Recent Changes:-Initial release
##############################################################################
 
#=======================
# Import Modules
#=======================
 
# Future print function capabilities
from __future__ import print_function
 
# sys: for stdout print buffer flush
import sys
 
# argparse: Command line arguments
import argparse
 
# ConfigParser: Use variables from external file (spacecmd config)
import ConfigParser
 
# os: Use bash environment variables for path to spacecmd config
import os
 
# xmlrpclib: Allows for parsing of Spacewalk APIs
import xmlrpclib
 
#=======================
# CUSTOMIZE HERE
#=======================
# Domain Name (include first '.')
domain_name=".example.com"
 
#=======================
# Get Script Arguments
#=======================
# Build argument parser information
parser = argparse.ArgumentParser(description="View/Edit descriptions for Spacewalk registered systems.")
parser.add_argument("-l","--list", help="List description(s) of single system or a group.", action="store_true", required=False)
parser.add_argument("-e","--edit", help="Edit description of a system (single systems only: --name).", action="store_true", required=False)
parser.add_argument("-d","--describe", help="Set new description of system (use with --edit).", required=False)
parser.add_argument("-n","--name", help="Single system name (use with --list or --edit)", required=False)
parser.add_argument("-g","--group", help="Spacewalk group or 'all' (use with --list)", required=False)
parser.add_argument("-t","--test", help="Do not make any changes. Run test and output what would have happened.", action="store_true", required=False)
args = vars(parser.parse_args())
 
# If testing, we don't actually want to do anything
if args['test'] == True:
  print("-->> Test run...no modifications will be made <<--")
 
# Requirement: Need to list OR edit
if args['list'] == True and args['edit'] == True:
  print(">> ERROR! Either list (-l) or edit (-e) descriptions..not both! Exiting...")
  exit(1)
elif args['list'] == False and args['edit'] == False:
  print(">> ERROR! Choose either to list (-l) or edit (-e) descriptions. Exiting...")
  exit(1)
 
# Requirement: Need a single system name OR a group name
if args['name'] and args['group']:
  print(">> ERROR! Choose a single system name (-n) OR a group name (-g)..not both! Exiting...")
  exit(1)
elif not args['name'] and not args['group']:
  print(">> ERROR! Choose a single system name (-n) OR a group name (-g). Exiting...")
  exit(1)
 
# Requirement: If editing, need a description
if args['edit'] == True and not args['describe']:
  print(">> ERROR! Need a description (-d <description>) when editing. Exiting...")
  exit(1)
 
# Requirement: Edits only for single systems
if args['edit'] == True and args['group']:
  print(">> ERROR! Edits for single systems (-n <name>) only. Exiting...")
  exit(1)
 
#=======================
# Config Settings
#=======================
# Read Spacecmd Config file - Path set from $HOME variable + expected spacecmd config file
config = ConfigParser.ConfigParser()
config.read(os.environ.get('HOME') + "/.spacecmd/config")
 
# Parse Spacecmd Config file - Set username, password, spacewalk server
spacewalk_login = config.get("spacecmd", "username")
spacewalk_password = config.get("spacecmd", "password")
spacewalk_server = config.get("spacecmd", "server")
#### End of Config Settings ####
 
#=====================================
# Functions; Main starts after
#=====================================
 
# Function: List Descriptions
def list_descriptions(system_type, system_name):
 
  # Single System
  if system_type == "single":
    # Get System Details
    sw_system = get_system_details(system_name)
 
    # Print System and Description
    print("--> " + system_name.strip(domain_name).upper() + ": " + get_system_description(sw_system['id']))
 
  # Group of Systems
  elif system_type == "group":
    # Get all Spacewalk Registered systems from group
    sw_system_list_details = get_system_list_details(system_name)
 
    # Loop through list and show descriptions
    for sw_system in sw_system_list_details:
      print("--> " + sw_system['name'].strip(domain_name).upper() + ": " + get_system_description(sw_system['id']))
 
  else:
    print("-> ERROR Unknown system type (single/group): " + system_type)
    exit(1)
 
  return
 
# Function: Edit Descriptions
def edit_descriptions(system_type, system_name):
 
  # Single System
  if system_type == "single":
    # Get System Details
    sw_system = get_system_details(system_name)
 
    # Edit System Description
    if args['describe']:
      # Show existing description
      print("-> System (" + system_name.strip(domain_name).upper() + ") current description: " + get_system_description(sw_system['id']))
 
      # Get new description from argument
      new_description = args['describe']
 
      if not new_description:
        # If new_description is empty, do not set
        print("--> Will NOT set new description for: " + system_name.strip(domain_name).upper())
      else:
        if args['test'] == True:
          # Testing; don't actually set the description
          print("--> I would have set the new description for (" + system_name.strip(domain_name).upper() + ") to: " + new_description)
        else:
          # Not testing; Set new description and display it
          print("--> Setting the new description for (" + system_name.strip(domain_name).upper() + ") to: " + new_description)
          set_system_description(sw_system['id'], {'description': new_description})
 
    else:
      # Error catching for edit 'describe' argument
      print("-> ERROR! Unknown edit condition encountered.")
      exit(1)
 
  else:
    print("-> ERROR Unhandled system type for editing (single only): " + system_type)
    exit(1)
 
  return
 
##-- Utility functions: Short/Reusable --##
# Function: Get all group names
def get_all_groups():
  # Get all group details
  all_groups = server.systemgroup.listAllGroups(key)
  group_list = []
 
  # Build a list of just group names
  for group in all_groups:
    group_list.append(group['name'])
 
  return group_list
 
# Function: Get a list of system details given a group name
def get_system_list_details(group_name):
  if group_name == "all":
    # Get all systems
    system_list_details = server.system.listSystems(key)
  else:
    # Get a group's systems
    system_list_details = server.systemgroup.listSystemsMinimal(key, group_name)
 
  return system_list_details
 
# Function: Get a system's details
def get_system_details(system_name):
 
  # Get the system's id
  system_id = get_system_id(system_name)
  if system_id == None:
    print("--> Error: (" + system_name + ") not found in Spacewalk!")
    exit(1)
  else:
    # Get System Details
    system_details = server.system.getDetails(key, system_id)
 
  return system_details
 
# Function: Get a system's description
def get_system_description(system_id):
 
  # Retrieve system details
  system_details = server.system.getDetails(key, system_id)
 
  return system_details['description']
 
# Function: Set a system's description
def set_system_description(system_id, new_description):
 
  try:
    server.system.setDetails(key, system_id, new_description)
  except:
    print("-> ERROR setting system description")
    return False
 
  return True
 
# Function: Get a system's id
def get_system_id(system_name):
 
  # Create all system name variants
  system_name_lower = system_name.strip(domain_name).lower()
  system_name_lower_fqdn = system_name_lower + domain_name
  system_name_upper = system_name.strip(domain_name).upper()
  system_name_upper_fqdn = system_name_upper + domain_name
 
  # Attempt to get the system's id for each
  system_id_lower = server.system.getId(key, system_name_lower)
  system_id_lower_fqdn = server.system.getId(key, system_name_lower_fqdn)
  system_id_upper = server.system.getId(key, system_name_upper)
  system_id_upper_fqdn = server.system.getId(key, system_name_upper_fqdn)
 
  # Check each for success
  if system_id_lower:
    system_id = system_id_lower[0]['id']
  elif system_id_lower_fqdn:
    system_id = system_id_lower_fqdn[0]['id']
  elif system_id_upper:
    system_id = system_id_upper[0]['id']
  elif system_id_upper_fqdn:
    system_id = system_id_upper_fqdn[0]['id']
  else:
    # System cannot be found
    system_id = None
 
  return system_id
 
#===================
# Main starts here
#===================
 
# Banner
print("===== Spacewalk Describe =====")
 
# Setup server info (rpc api endpoint)
spacewalk_url = "https://" + spacewalk_server + "/rpc/api"
server = xmlrpclib.Server(spacewalk_url)
 
# Attempt to login and get a session id
try:
  key = server.auth.login(spacewalk_login, spacewalk_password)
except:
  print("->ERROR: Spacewalk Login failed. Exiting...")
  exit(1)
 
#-- Group Name Validation --#
if args['group'] and args['group'] != "all":
  #- Ensure group exists if it is not "all" systems -#
  try:
    # Get group's details
    group_details = server.systemgroup.getDetails(key, args['group'])
 
    # If no systems are in the group, there is nothing to do
    if group_details['system_count'] == 0:
      print("->The group(" + args['group'] + ") has zero systems in it. Nothing to do...")
      exit(1)
 
  except:
    print("->ERROR: The group(" + args['group'] + ") does not exist. Exiting...")
 
    print("\n-> Available 'all' groups are:")
    group_list = get_all_groups()
    for group in group_list:
      if group.startswith("all"):
        print("--> " + group)
    print("--> all")
    exit(1)
 
#-- Edit or List System Descriptions --#
 
if args['list'] == True:
  # List Descriptions
  print(">> List System Descriptions")
 
  if args['group']:
    list_descriptions("group", args['group'])
  elif args['name']:
    list_descriptions("single", args['name'])
  else:
    print("-> ERROR: Group/Name not set! Exiting...")
    exit(1)
 
elif args['edit'] == True:
  # Edit Descriptions
  print(">> Edit System Descriptions")
 
  if args['group']:
    edit_descriptions("group", args['group'])
  elif args['name']:
    edit_descriptions("single", args['name'])
  else:
    print("-> ERROR: Group/Name not set! Exiting...")
    exit(1)
 
else:
  # Error catching, should not get here
  print("-> ERROR: Unknown list/edit state. List=" + args['list'] + " , Edit=" + args['edit'] + ". Exiting...")
  exit(1)
 
# Logout of Spacewalk server
server.auth.logout(key)

  • python_wiki/spacewalk_describe.1499486037.txt.gz
  • Last modified: 2019/05/25 23:50
  • (external edit)