<filename>kspost.py
#!/usr/bin/env python
from datetime import datetime
import shutil
import json
import re

"""
ksconfig - kspost.py
====================
Kickstart %post script to apply configurations to system collected by kspre.py
See README.md for more information.
"""
__author__ = '<NAME>'
__copyright__ = 'Copyright 2015, <NAME>'
__license__ = 'BSD'
__version__ = '1.0.1'

# Settings Begin ##############################################################
DEBUG = False

# List of additional grub parameters
grub_param = ['net.ifnames=0', 'biosdevname=0']

# Interface Template
iface_tpl = """# Interface Configured by ksconfig on {date}
DEVICE={interface}
BOOTPROTO=static
HWADDR={hwaddr}
IPADDR={ipaddr}
NETMASK={netmask}
GATEWAY={gateway}
ONBOOT=yes
NM_CONTROLLED=no
"""

# /etc/resolv.conf Template
resolv_tpl = """# Generated by ksconfig on {date}
domain {domain}
search {searchdomain}
nameserver {primedns}
nameserver {secondns}

"""
# Settings End ################################################################

date = datetime.now().strftime('%Y%m%d')

if DEBUG:
    # Development/testing File Locations
    grub_cfg_location = 'tests/grub'
    modified_grub_cfg = 'tests/grub.out'
    grub_cfg_backup = 'tests/grub.back-%s' % date
else:
    # Production File Locations
    grub_cfg_location = '/mnt/sysimage/etc/default/grub'
    modified_grub_cfg = '/mnt/sysimage/etc/default/grub'
    grub_cfg_backup = '/mnt/sysimage/etc/default/grub.back-%s' % date

# Load Pre Script Data
server_config = json.load(open('/tmp/servercfg.json', 'r'))
disk_config = json.load(open('/tmp/disk.json', 'r'))


def copy_preconfig():
    """ Copy Configuration files created by %pre script
    """
    copy_tasks = [
        ['/tmp/servercfg.json', '/mnt/sysimage/tmp/'],
        ['/tmp/disk.json', '/mnt/sysimage/tmp/'],
        ['/tmp/disk.part', '/mnt/sysimage/tmp/']
    ]
    for source, destination in copy_tasks:
        try:
            shutil.copy(source, destination)
        except IOError:
            pass  # TODO: Add logging


def set_hostname():
    """ Set Hostname in the following locations:
    /etc/sysconfig/network (hostname)
    /etc/hosts (primary IP and hostname)
    """
    with open('/mnt/sysimage/etc/sysconfig/network', 'w') as networkfile:
        networkfile.write('HOSTNAME=%s\n' % server_config['hostname'])
    with open('/mnt/sysimage/etc/hostname', 'w') as hostnamefile:  # Req for 7+
        hostnamefile.write('%s\n' % server_config['hostname'])
    with open('/mnt/sysimage/etc/hosts', 'a') as hostsfile:
        hostsfile.write('%s\t%s\n' % (server_config['pripaddr'],
                                      server_config['hostname']))
        if server_config['second_interface']:
            if server_config['secondipaddr']:
                hostsfile.write('%s\t%s\n' % (server_config['secondipaddr'],
                                              server_config['hostname'] +
                                              server_config['second_pfix']))


def findmac(interface):
    """ Helper function to retrieve the MAC address for a given interface from
    the server configuration object.
    :param interface: Device ie: eth0
    :return: MAC Address of device or None
    """
    try:
        mac = server_config['interfaces'][str(interface)]['perm_address']
        mac = mac.upper()
    except KeyError:
        mac = None
    return mac


def configure_resolv():
    """ Backup resolv.conf and generate a new config with %pre script vars
    """
    shutil.copy('/mnt/sysimage/etc/resolv.conf',
                '/mnt/sysimage/etc/resolv.conf.orig')
    context = {
        "date": date,
        "domain": server_config['domain'],
        "searchdomain": server_config['domain'],
        "primedns": server_config['primedns'],
        "secondns": server_config['secondns']
    }
    with open('/mnt/sysimage/etc/resolv.conf', "w") as f:
        f.write(resolv_tpl.format(**context))


def configure_interface(interface, ip=None, nm=None, gw=None):
    """ Configures interface with params specified from %pre script
    :param interface: device ie: eth0
    :param ip: IP Address
    :param nm: Netmask
    :param gw: Gateway
    """
    scripts_path = '/mnt/sysimage/etc/sysconfig/network-scripts'
    shutil.copy('%s/ifcfg-%s' % (scripts_path, interface),
                '%s/ifcfg-%s.orig' % (scripts_path, interface))
    context = {
        "date": date,
        "interface": interface,
        "hwaddr": findmac(interface),
        "ipaddr": ip,
        "netmask": nm,
    }
    if gw:
        context["gateway"] = gw
    with open('%s/ifcfg-%s' % (scripts_path, interface), 'w') as f:
        f.write(iface_tpl.format(**context))


def edit_grub_config():
    """ Edits to /etc/sysconfig/grub
    :return:
    """
    shutil.copy(grub_cfg_location, grub_cfg_backup)
    infile = open(grub_cfg_location, 'r')
    grub_data = infile.readlines()
    infile.close()
    outfile = open(modified_grub_cfg, 'w')
    for line in grub_data:
        grub_cmdline = re.search('^GRUB_CMDLINE_LINUX="(.*)"$', line)
        if grub_cmdline:
            param_added = ''
            for param in grub_param:
                if param in grub_cmdline.group(1):
                    continue
                else:
                    param_added += ' %s' % param
            outfile.write('GRUB_CMDLINE_LINUX="%s %s"\n'
                          % (grub_cmdline.group(1), param_added))
        else:
            outfile.write(line)
    outfile.close()


def main():
    copy_preconfig()
    edit_grub_config()
    set_hostname()
    configure_resolv()
    configure_interface('eth0',
                        server_config['pripaddr'],
                        server_config['pripmask'],
                        server_config['pripgate'])
    if server_config['second_interface']:
        if server_config['secondipaddr']:
            configure_interface('eth1',
                                server_config['secondipaddr'],
                                server_config['secondipmask'],
                                server_config['secondipgate'])


if __name__ == "__main__":
    main()

<filename>kspost.py
#!/usr/bin/env python
from datetime import datetime
import shutil
import json
import re

"""
ksconfig - kspost.py
====================
Kickstart %post script to apply configurations to system collected by kspre.py
See README.md for more information.
"""
__author__ = '<NAME>'
__copyright__ = 'Copyright 2015, <NAME>'
__license__ = 'BSD'
__version__ = '1.0.1'

# Settings Begin ##############################################################
DEBUG = False

# List of additional grub parameters
grub_param = ['net.ifnames=0', 'biosdevname=0']

# Interface Template
iface_tpl = """# Interface Configured by ksconfig on {date}
DEVICE={interface}
BOOTPROTO=static
HWADDR={hwaddr}
IPADDR={ipaddr}
NETMASK={netmask}
GATEWAY={gateway}
ONBOOT=yes
NM_CONTROLLED=no
"""

# /etc/resolv.conf Template
resolv_tpl = """# Generated by ksconfig on {date}
domain {domain}
search {searchdomain}
nameserver {primedns}
nameserver {secondns}

"""
# Settings End ################################################################

date = datetime.now().strftime('%Y%m%d')

if DEBUG:
    # Development/testing File Locations
    grub_cfg_location = 'tests/grub'
    modified_grub_cfg = 'tests/grub.out'
    grub_cfg_backup = 'tests/grub.back-%s' % date
else:
    # Production File Locations
    grub_cfg_location = '/mnt/sysimage/etc/default/grub'
    modified_grub_cfg = '/mnt/sysimage/etc/default/grub'
    grub_cfg_backup = '/mnt/sysimage/etc/default/grub.back-%s' % date

# Load Pre Script Data
server_config = json.load(open('/tmp/servercfg.json', 'r'))
disk_config = json.load(open('/tmp/disk.json', 'r'))


def copy_preconfig():
    """ Copy Configuration files created by %pre script
    """
    copy_tasks = [
        ['/tmp/servercfg.json', '/mnt/sysimage/tmp/'],
        ['/tmp/disk.json', '/mnt/sysimage/tmp/'],
        ['/tmp/disk.part', '/mnt/sysimage/tmp/']
    ]
    for source, destination in copy_tasks:
        try:
            shutil.copy(source, destination)
        except IOError:
            pass  # TODO: Add logging


def set_hostname():
    """ Set Hostname in the following locations:
    /etc/sysconfig/network (hostname)
    /etc/hosts (primary IP and hostname)
    """
    with open('/mnt/sysimage/etc/sysconfig/network', 'w') as networkfile:
        networkfile.write('HOSTNAME=%s\n' % server_config['hostname'])
    with open('/mnt/sysimage/etc/hostname', 'w') as hostnamefile:  # Req for 7+
        hostnamefile.write('%s\n' % server_config['hostname'])
    with open('/mnt/sysimage/etc/hosts', 'a') as hostsfile:
        hostsfile.write('%s\t%s\n' % (server_config['pripaddr'],
                                      server_config['hostname']))
        if server_config['second_interface']:
            if server_config['secondipaddr']:
                hostsfile.write('%s\t%s\n' % (server_config['secondipaddr'],
                                              server_config['hostname'] +
                                              server_config['second_pfix']))


def findmac(interface):
    """ Helper function to retrieve the MAC address for a given interface from
    the server configuration object.
    :param interface: Device ie: eth0
    :return: MAC Address of device or None
    """
    try:
        mac = server_config['interfaces'][str(interface)]['perm_address']
        mac = mac.upper()
    except KeyError:
        mac = None
    return mac


def configure_resolv():
    """ Backup resolv.conf and generate a new config with %pre script vars
    """
    shutil.copy('/mnt/sysimage/etc/resolv.conf',
                '/mnt/sysimage/etc/resolv.conf.orig')
    context = {
        "date": date,
        "domain": server_config['domain'],
        "searchdomain": server_config['domain'],
        "primedns": server_config['primedns'],
        "secondns": server_config['secondns']
    }
    with open('/mnt/sysimage/etc/resolv.conf', "w") as f:
        f.write(resolv_tpl.format(**context))


def configure_interface(interface, ip=None, nm=None, gw=None):
    """ Configures interface with params specified from %pre script
    :param interface: device ie: eth0
    :param ip: IP Address
    :param nm: Netmask
    :param gw: Gateway
    """
    scripts_path = '/mnt/sysimage/etc/sysconfig/network-scripts'
    shutil.copy('%s/ifcfg-%s' % (scripts_path, interface),
                '%s/ifcfg-%s.orig' % (scripts_path, interface))
    context = {
        "date": date,
        "interface": interface,
        "hwaddr": findmac(interface),
        "ipaddr": ip,
        "netmask": nm,
    }
    if gw:
        context["gateway"] = gw
    with open('%s/ifcfg-%s' % (scripts_path, interface), 'w') as f:
        f.write(iface_tpl.format(**context))


def edit_grub_config():
    """ Edits to /etc/sysconfig/grub
    :return:
    """
    shutil.copy(grub_cfg_location, grub_cfg_backup)
    infile = open(grub_cfg_location, 'r')
    grub_data = infile.readlines()
    infile.close()
    outfile = open(modified_grub_cfg, 'w')
    for line in grub_data:
        grub_cmdline = re.search('^GRUB_CMDLINE_LINUX="(.*)"$', line)
        if grub_cmdline:
            param_added = ''
            for param in grub_param:
                if param in grub_cmdline.group(1):
                    continue
                else:
                    param_added += ' %s' % param
            outfile.write('GRUB_CMDLINE_LINUX="%s %s"\n'
                          % (grub_cmdline.group(1), param_added))
        else:
            outfile.write(line)
    outfile.close()


def main():
    copy_preconfig()
    edit_grub_config()
    set_hostname()
    configure_resolv()
    configure_interface('eth0',
                        server_config['pripaddr'],
                        server_config['pripmask'],
                        server_config['pripgate'])
    if server_config['second_interface']:
        if server_config['secondipaddr']:
            configure_interface('eth1',
                                server_config['secondipaddr'],
                                server_config['secondipmask'],
                                server_config['secondipgate'])


if __name__ == "__main__":
    main()

#!/usr/bin/env python ksconfig - kspost.py ==================== Kickstart %post script to apply configurations to system collected by kspre.py See README.md for more information. # Settings Begin ############################################################## # List of additional grub parameters # Interface Template # Interface Configured by ksconfig on {date} DEVICE={interface} BOOTPROTO=static HWADDR={hwaddr} IPADDR={ipaddr} NETMASK={netmask} GATEWAY={gateway} ONBOOT=yes NM_CONTROLLED=no # /etc/resolv.conf Template # Generated by ksconfig on {date} domain {domain} search {searchdomain} nameserver {primedns} nameserver {secondns} # Settings End ################################################################ # Development/testing File Locations # Production File Locations # Load Pre Script Data Copy Configuration files created by %pre script # TODO: Add logging Set Hostname in the following locations:     /etc/sysconfig/network (hostname)     /etc/hosts (primary IP and hostname) # Req for 7+ Helper function to retrieve the MAC address for a given interface from     the server configuration object.     :param interface: Device ie: eth0     :return: MAC Address of device or None Backup resolv.conf and generate a new config with %pre script vars Configures interface with params specified from %pre script     :param interface: device ie: eth0     :param ip: IP Address     :param nm: Netmask     :param gw: Gateway Edits to /etc/sysconfig/grub     :return: