Esempio n. 1
0
def clean(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    return sudo_dry('rm -rf {0}'.format(
        args['chef_file_dest']
    ), args, logger=logger)
Esempio n. 2
0
def bootstrap(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    with settings(hide('warnings', 'stdout', 'stderr'), warn_only=True):
        result = sudo_dry("command -v chef-solo", args, logger=logger)

    if not result.failed:
        logger.info("-> Chef already boostrapped.")
        return

    logger.info("-> Installing Prerequisite Packages...")
    sudo_dry("apt-get update", args, logger=logger)
    sudo_dry("apt-get upgrade -y", args, logger=logger)
    sudo_dry("apt-get update", args, logger=logger)
    sudo_dry("apt-get install -y {0}".format(' '.join([
        'autoconf',
        'binutils-doc',
        'bison',
        'build-essential',
        'curl',
        'flex',
        'gcc',
        'git-core',
        'libreadline-dev',
        'libssl-dev',
        'libtool',
        'libxml2-dev',
        'libxslt-dev',
        'zlib1g-dev',
    ])), args, logger=logger)

    ruby(args, config, logger=logger)

    gem(args, config, logger=logger)
Esempio n. 3
0
def clean(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    return sudo_dry('rm -rf {0}'.format(args['chef_file_dest']),
                    args,
                    logger=logger)
Esempio n. 4
0
def sudo_dry(cmd, args, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    if args['dry_run']:
        logger.info("[SUDO] {0}".format(cmd))
    else:
        return sudo(cmd)
Esempio n. 5
0
def version(args):
    if args['version']:
        formatter = logging.Formatter('%(message)s')
        logger = setup_custom_logger('chef-solo-cup',
                                     args=args,
                                     formatter=formatter)
        logger.info('Chef Solo Cup {0}'.format(__version__))
        sys.exit(0)
Esempio n. 6
0
def sudo_dry(cmd, args, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    if args['dry_run']:
        logger.info("[SUDO] {0}".format(cmd))
    else:
        return sudo(cmd)
Esempio n. 7
0
def add_line_if_not_present_dry(args, filename, line, run_f=run, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    cmd = "grep -q -e '{0}' {1} || echo '{0}' >> {1}".format(line, filename)
    if args['dry_run']:
        logger.info("[SUDO] {0}".format(cmd))
    else:
        run_f(cmd)
Esempio n. 8
0
def add_line_if_not_present_dry(args, filename, line, run_f=run, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    cmd = "grep -q -e '{0}' {1} || echo '{0}' >> {1}".format(line, filename)
    if args['dry_run']:
        logger.info("[SUDO] {0}".format(cmd))
    else:
        run_f(cmd)
Esempio n. 9
0
def version(args):
    if args['version']:
        formatter = logging.Formatter('%(message)s')
        logger = setup_custom_logger(
            'chef-solo-cup',
            args=args,
            formatter=formatter
        )
        logger.info('Chef Solo Cup {0}'.format(__version__))
        sys.exit(0)
Esempio n. 10
0
def rsync_project_dry(args, logger=None, **kwargs):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    if args['dry_run']:
        logger.info("[RSYNC_PROJECT] From {0} to {1} with opts='{2}' excluding='{3}'".format(kwargs.get('local_dir'), kwargs.get('remote_dir'), kwargs.get('extra_opts'), kwargs.get('exclude')))  # noqa
    else:
        out = rsync_project(**kwargs)
        if out.return_code != 0:
            logger.info("[RSYNC_PROJECT] Failed command with status code {0}, please run `chef-solo-cup clean` against this node".format(out.return_code))  # noqa
            sys.exit(0)
Esempio n. 11
0
def default(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    sync(args, config, logger=logger)
    command = ' && '.join([
        "cd {0}", "source /etc/profile",
        "`which chef-solo` -c {0}/{1} -j {0}/dna/{2} -l {3}"
    ])
    return sudo_dry(command.format(args['chef_file_dest'], args['config_path'],
                                   'default.json', args['loglevel']),
                    args,
                    logger=logger)
Esempio n. 12
0
def ruby(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    logger.info("-> Installing Ruby 1.9.2")
    return sudo_dry("apt-get install -y {0}".format(' '.join([
        'ruby1.9.1',
        'ruby1.9.1-dev',
        'rubygems1.9.1',
        'irb1.9.1',
        'ri1.9.1',
        'rdoc1.9.1',
        'libopenssl-ruby1.9.1',
    ])), args, logger=logger)
Esempio n. 13
0
def gem(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    logger.info("-> Installing Chef ...")
    gem_install_command = 'gem install -v {0} {1} --no-rdoc --no-ri'
    sudo_dry(gem_install_command.format(
        args['ohai_version'],
        'ohai'
    ), args, logger=logger)
    return sudo_dry(gem_install_command.format(
        args['chef_version'],
        'chef'
    ), args, logger=logger)
Esempio n. 14
0
def chef(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    install_url = 'curl -sSL https://www.opscode.com/chef/install.sh'
    install_command = '{0} | sudo bash -s -- -v {1}'.format(
        install_url, args['chef_version'])
    uninstall_command = 'gem uninstall -a chef ohai'

    logger.info("-> Installing Chef ...")
    response = sudo_dry(uninstall_command, args, logger=logger)
    if response:
        return sudo_dry(install_command, args, logger=logger)
    return response
Esempio n. 15
0
def chef(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    install_url = 'curl -sSL https://www.opscode.com/chef/install.sh'
    install_command = '{0} | sudo bash -s -- -v {1}'.format(
        install_url, args['chef_version']
    )
    uninstall_command = 'gem uninstall -a chef ohai'

    logger.info("-> Installing Chef ...")
    response = sudo_dry(uninstall_command, args, logger=logger)
    if response:
        return sudo_dry(install_command, args, logger=logger)
    return response
Esempio n. 16
0
def _get_api_response(args, region=None, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    if not args['api_url']:
        return None

    request_url = '{0}/nodes/group?status={1}'.format(
        args['api_url'],
        'running'
    )
    if region is not None:
        request_url = '{0}&region={1}'.format(request_url, region)

    request = urllib2.Request(request_url)

    has_username = '******' in args
    has_password = '******' in args
    if has_username and has_password:
        base64string = base64.encodestring('{0}:{1}'.format(
            args['api_username'], args['api_password']
        )).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

    result = urllib2.urlopen(request)

    if int(result.getcode()) not in [200, 201, 204]:
        error = 'Bad response from api'
        try:
            data = json.loads(result.read())
            error = data.get('message', 'Bad response from api')
        except:
            pass
        logger.error(error)
        sys.exit(1)

    response = None
    try:
        response = json.loads(result.read())
    except ValueError:
        logger.error('Invalid json response from api')
        sys.exit(1)

    groups = response['groups']
    if 'None' in groups:
        del groups['None']

    return groups
Esempio n. 17
0
def rsync_project_dry(args, logger=None, **kwargs):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    if args['dry_run']:
        logger.info(
            "[RSYNC_PROJECT] From {0} to {1} with opts='{2}' excluding='{3}'".
            format(kwargs.get('local_dir'), kwargs.get('remote_dir'),
                   kwargs.get('extra_opts'), kwargs.get('exclude')))  # noqa
    else:
        out = rsync_project(**kwargs)
        if out.return_code != 0:
            logger.info(
                "[RSYNC_PROJECT] Failed command with status code {0}, please run `chef-solo-cup clean` against this node"
                .format(out.return_code))  # noqa
            sys.exit(0)
Esempio n. 18
0
def default(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    sync(args, config, logger=logger)
    command = ' && '.join([
        "cd {0}",
        "source /etc/profile",
        "`which chef-solo` -c {0}/{1} -j {0}/dna/{2} -l {3}"
    ])
    return sudo_dry(command.format(
        args['chef_file_dest'],
        args['config_path'],
        'default.json',
        args['loglevel']
    ), args, logger=logger)
Esempio n. 19
0
def update(args, config, delete_files=False, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    sync(args, config, logger=logger)

    command = ' && '.join([
        "cd {0}", "source /etc/profile",
        "`which chef-solo` -c {0}/{1} -j {0}/{2} -l {3}"
    ])
    if delete_files:
        command += ' && rm -rf {0}'.format(args['chef_file_dest'])

    return sudo_dry(command.format(args['chef_file_dest'], args['config_path'],
                                   config.get('dna_path'), args['loglevel']),
                    args,
                    logger=logger)
Esempio n. 20
0
def _get_api_response(args, region=None, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    if not args['api_url']:
        return None

    request_url = '{0}/nodes/group?status={1}'.format(args['api_url'],
                                                      'running')
    if region is not None:
        request_url = '{0}&region={1}'.format(request_url, region)

    request = urllib2.Request(request_url)

    has_username = '******' in args
    has_password = '******' in args
    if has_username and has_password:
        base64string = base64.encodestring('{0}:{1}'.format(
            args['api_username'], args['api_password'])).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

    result = urllib2.urlopen(request)

    if int(result.getcode()) not in [200, 201, 204]:
        error = 'Bad response from api'
        try:
            data = json.loads(result.read())
            error = data.get('message', 'Bad response from api')
        except:
            pass
        logger.error(error)
        sys.exit(1)

    response = None
    try:
        response = json.loads(result.read())
    except ValueError:
        logger.error('Invalid json response from api')
        sys.exit(1)

    groups = response['groups']
    if 'None' in groups:
        del groups['None']

    return groups
Esempio n. 21
0
def update(args, config, delete_files=False, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    sync(args, config, logger=logger)

    command = ' && '.join([
        "cd {0}",
        "source /etc/profile",
        "`which chef-solo` -c {0}/{1} -j {0}/{2} -l {3}"
    ])
    if delete_files:
        command += ' && rm -rf {0}'.format(args['chef_file_dest'])

    return sudo_dry(command.format(
        args['chef_file_dest'],
        args['config_path'],
        config.get('dna_path'),
        args['loglevel']
    ), args, logger=logger)
Esempio n. 22
0
def sync(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    if args['sync'] == "git":
        # TODO: Allow this to be any host
        add_line_if_not_present_dry(args, '~/.ssh/known_hosts', "github.com,207.97.227.239 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==", logger=logger)  # noqa
        run_dry(' ; '.join([
            'if [ -d {1}/.git ]',
            'then cd {1} && git pull origin master',
            'else rm -rf {1} && git clone {0} {1}',
            'fi'
        ]).format(
            args['repository'],
            args['chef_file_dest']
        ), args, logger=logger)
    else:
        with settings(hide('stdout'), warn_only=True):
            rsync_exclusions = list(args['rsync_exclusions'])
            if not rsync_exclusions:
                rsync_exclusions = []
            rsync_exclusions.append('.git')

            rsync_project_dry(
                args,
                logger=logger,
                extra_opts="-Caz",
                delete=True,
                exclude=rsync_exclusions,
                local_dir="./",
                remote_dir=args['chef_file_dest'],
                capture=True
            )

    return sudo_dry("chmod -R a+w {0}".format(
        args['chef_file_dest']
    ), args, logger=logger)
Esempio n. 23
0
def test(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    return sudo_dry("hostname", args, logger=logger)
Esempio n. 24
0
def sudo_command(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    return sudo_dry(args['cmd'], args, logger=logger)
Esempio n. 25
0
def sudo_command(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    return sudo_dry(args['cmd'], args, logger=logger)
Esempio n. 26
0
def inspect(args, config, logger=None):
    if logger is None:
        logger = setup_custom_logger('chef-solo-cup', args)

    logger.info(config)