author Paul Tonelli <paul.tonelli@logilab.fr>
Mon, 11 Mar 2013 15:27:04 +0100
changeset 57 28cbe9dbaf1f
parent 55 a8fc89e61f2b
child 68 601c145e6326
permissions -rw-r--r--
added debian config file to avoir conf messages (do you want to replace previously modified config file...)

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

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

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 ###
    update_image(path + '/' + image_dirname)
    variate_image(path + '/' + image_dirname)
    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: