_modules/vm_create.py
author Paul Tonelli <paul.tonelli@logilab.fr>
Mon, 11 Mar 2013 16:31:00 +0100
changeset 59 c062ff185a14
parent 55 a8fc89e61f2b
child 68 601c145e6326
permissions -rw-r--r--
updated and renamed user data options

#!/usr/bin/env python
'''
translation of a bash script to create a flavored virtual machine
'''

PROXY_ADDRESS = 'http://proxy.logilab.priv:3142/'
DEFAULT_PATH = '/mnt'
APT_PROXY_FILENAME = '/etc/apt/apt.conf.d/01proxy'
POLICY_FILENAME = '/usr/sbin/policy-rc.d'
POLICY_CONTENT =  'exit 101'
DEFAULT_MOUNT_DIR = 'variation'
DEFAULT_VARIATION_NAME = DEFAULT_MOUNT_DIR + '.sls'

from os import listdir, remove, stat, environ
import shutil
import salt.utils
import logging

log = logging.getLogger(__name__)

def update_image(chroot_dirname):
    '''
    update image using apt-get. Doing so, it creates a few files.
    In order to be executed in chroot, you should use is with
    create_proxy=True unless you have /run mounted

    CLI Example::

        salt '*' vm_create.update_image /mnt/variation
    '''
    _print_if_error(_chroot_exec(chroot_dirname, 'apt-get update'))
    _print_if_error(_chroot_exec(chroot_dirname, 'apt-get --force-yes -y install salt-minion'))

def variate_image(chroot_dirname, variation_filename=DEFAULT_VARIATION_NAME):
    '''
    do all code relevant to personalizing the machine here
    salt-minion should be available

    CLI Example::

        salt '*' vm_create.variate_image /mnt/variation

    '''
    log.info(_chroot_exec(chroot_dirname, 'salt-call  --local state.highstate'))


def create_variation(path=DEFAULT_PATH, upload_to_glance=None):
    '''
    complete function to create the new variation from a virtual machine

    CLI Example::

        salt '*' vm_create.create_variation
    '''
    image_dirname = DEFAULT_MOUNT_DIR
    ### Exec pre state here ###
    log.info(__salt__['state.sls']('ami_creator_pre'))
    update_image(path + '/' + image_dirname)
    variate_image(path + '/' + image_dirname)
    log.info(__salt__['state.sls']('ami_creator_post'))
    log.info('Image Not uploaded to glance !')
    return True

def upload_to_glance(path=DEFAULT_PATH, kernel_id=None, ramdisk_id=None):
    if not kernel_id:
        kernel_id = __salt__['openstack_client.upload_to_glance'](
                path, kernel_name, 'aki', '', image_dirname)
    if not ramdisk_id:
        ramdisk_id = __salt__['openstack_client.upload_to_glance'](
                path, ramdisk_name, 'ari', '', image_dirname)
    image_id = __salt__['openstack_client.upload_to_glance'](
            path, image_name, 'ami', 'kernel_id='
            + kernel_id + ' ramdisk_id=' + ramdisk_id)
    return image_id

def _chroot_exec(chroot_path, command):
    return __salt__['cmd.run_all']('chroot ' + chroot_path + ' ' + command)

def _print_if_error(ret):
    if ret['retcode'] != 0:
        log.error(ret['stderr'])