Example #1
0
def edit_chef_environment(server_url, cert, username, environment, attributes):
    """
    _edit_chef_environment_

    For a given chef server, edit the override attributes in the named
    environment making changes for each dotted key:value pair in attributes

    Eg:

    attributes = {
        'application.app_version': 'x.y.z',
        'application.some_url': 'http://www.google.com'
    }
    will result in changes:
      env.override_attributes['application']['app_version'] = 'x.y.z'
      env.override_attributes['application']['some_url'] = 'http://www.google.com'

    :param server_url: URL of your chef server
    :param cert: Client.pem file location
    :param username: Chef username matching the cert
    :param environment: name of chef environment eg 'production'
    :param attributes: dict of dotted attribute key value pairs to change
      in the env

    """
    with chef.ChefAPI(server_url, cert, username):
        env = chef.Environment(environment)
        overrides = env.override_attributes
        LOGGER.info("Editing Chef Server Environment: {} as {}".format(
            environment, username))
        for attr, new_value in attributes.iteritems():
            LOGGER.info(" => Setting {}={}".format(attr, new_value))
            set_dotted(overrides, attr, new_value)
        env.save()
Example #2
0
def active(bot, trigger):
    '''Display the current active set for an environment'''
    env_input = trigger.group(2)
    if env_input is None:
        bot.say('Please give me a chef environment')
        return
    url = bot.config.chef.url
    key = bot.config.chef.key
    username = bot.config.chef.username
    api = chef.ChefAPI(url, key, username)
    api.set_default()
    all_envs = chef.Environment.list().names
    if env_input in ('prod', 'production', 'all'):
        #Select all production environments
        envs = [env for env in all_envs if 'production-' in env]

        if env_input == 'all':
            envs.append('staging')
    elif env_input in all_envs:
        envs = [env_input]
    elif 'production-' + env_input in all_envs:
        envs = ['production-' + env_input]
    else:
        bot.say("{} isn't an environment I recognize".format(env_input))
        return

    for env_name in sorted(envs):
        env = chef.Environment(env_name)
        if 'active_set' in env.default_attributes['heat']:
            bot.say('{}: Current active set is {}'.format(
                    env_name,
                    env.default_attributes['heat']['active_set'].upper()))
        else:
            bot.say('There is no active set for {}'.format(env_name))
Example #3
0
    def test_update_environment(self):
        import chef
        cluster_name = self.test_chef.config_manager.get_clustername()
        env_name = self.test_chef.get_env_name(self.dist_sys_name,
                                               cluster_name)
        vars_dict = self.test_chef._get_cluster_tmpl_vars()
        env_attrs = self.test_chef._generate_env_attributes(vars_dict)
        test_env = self.test_chef.get_create_environment(env_name)
        self.assertIsNotNone(test_env)
        self._register(test_env)

        self.test_chef._update_env(test_env, env_attrs)
        expected_env = {
            "name": "openstack_icehouse-test",
            "description": "Environment",
            "cookbook_versions": {
            },
            "json_class": "Chef::Environment",
            "chef_type": "environment",
            "default_attributes": {
            },
            "override_attributes": {
                "compute": {
                    "syslog": {
                        "use": False
                    },
                    "libvirt": {
                        "bind_interface": "eth0"
                    },
                    "novnc_proxy": {
                        "bind_interface": "vnet0"
                    },
                    "xvpvnc_proxy": {
                        "bind_interface": "eth0"
                    }
                },
                "db": {
                    "bind_interface": "vnet0",
                    "compute": {
                        "host": "12.234.32.100"
                    },
                    "identity": {
                        "host": "12.234.32.100"
                    }
                },
                "mq": {
                    "user": "******",
                    "password": "******",
                    "vhost": "/nova",
                    "network": {
                        "service_type": "rabbitmq"
                    }
                }
            }
        }
        chef_env = chef.Environment(env_name, self.chef_test_api)
        self.maxDiff = None
        self.assertDictEqual(expected_env, chef_env.to_dict())
Example #4
0
def chef_noop(bot, trigger):
    '''Display a list of noop hosts in a chef environment'''
    env_name = trigger.group(2)
    if env_name is None:
        bot.say('Please give me a chef environment')
        return
    url = bot.config.chef.url
    key = bot.config.chef.key
    username = bot.config.chef.username
    api = chef.ChefAPI(url, key, username)
    api.set_default()
    env = chef.Environment(env_name)
    noop = env.default_attributes['base']['noop']
    bot.say('The following nodes have noop set: {}'.format(', '.join(noop)))
Example #5
0
    def clean(self):
        try:
            for node_name in chef.Node.list(api=self.api):
                node = chef.Node(node_name, api=self.api)
                node.delete()
                logging.info('delete node %s', node_name)
        except Exception as error:
            logging.error('failed to delete some nodes')
            logging.exception(error)

        try:
            for client_name in chef.Client.list(api=self.api):
                if client_name in ['chef-webui', 'chef-validator']:
                    continue
                client = chef.Client(client_name, api=self.api)
                client.delete()
                logging.info('delete client %s', client_name)
        except Exception as error:
            logging.error('failed to delete some clients')
            logging.exception(error)

        try:
            for env_name in chef.Environment.list(api=self.api):
                if env_name == '_default':
                    continue
                env = chef.Environment(env_name, api=self.api)
                env.delete()
                logging.info('delete env %s', env_name)
        except Exception as error:
            logging.error('failed to delete some envs')
            logging.exception(error)

        try:
            for databag_name in chef.DataBag.list(api=self.api):
                databag = chef.DataBag(databag_name, api=self.api)
                for item_name, item in databag.items():
                    item.delete()
                    logging.info(
                        'delete item %s from databag %s',
                        item_name, databag_name
                    )
        except Exception as error:
            logging.error('failed to delete some databag items')
            logging.exception(error)
Example #6
0
def active(bot, trigger):
    '''Display the current active set for an environment'''
    env_name = trigger.group(2)
    if env_name is None:
        bot.say('Please give me a chef environment')
        return
    url = bot.config.chef.url
    key = bot.config.chef.key
    username = bot.config.chef.username
    api = chef.ChefAPI(url, key, username)
    api.set_default()
    envs = chef.Environment.list().names
    if env_name not in envs:
        bot.say("{} isn't an environment I recognize".format(env_name))
        return
    env = chef.Environment(env_name)
    if 'active_set' in env.default_attributes['heat']:
        bot.say('Current active set is {}'.format(
                env.default_attributes['heat']['active_set'].upper()))
    else:
        bot.say('There is no active set for {}'.format(env_name))
Example #7
0
    def perform(self, cm):
        """
        Delete the environment and associated data.

        """
        filter = '{0}_'.format(self.infra_id)
        for role in cm.list_roles():
            if role.startswith(filter):
                log.debug("[CM] Removing role: %r", role)
                try:
                    chef.Role(role, api=cm.chefapi).delete()
                    log.debug("[CM] Done")
                except Exception as ex:
                    log.exception('Error removing role:')
                    log.info('[CM] Removing role failed - ignoring.')

        log.debug("[CM] Dropping environment %r", self.infra_id)
        try:
            chef.Environment(self.infra_id, api=cm.chefapi).delete()
            log.debug("[CM] Done")
        except Exception as ex:
            log.exception('Error dropping environment:')
            log.info('[CM] drop_infrastructure failed - ignoring.')
Example #8
0
def env_collect_data(api, max_records):
    log_prefix = 'chef - env:'

    if VERBOSE:
        print log_prefix + ' collecting data'
    all_envs = list(chef.Environment.list())
    total_envs = len(all_envs)

    if VERBOSE:
        print '%s found %d environments' % (log_prefix, total_envs)

    count = 1
    env_data = {}

    for env in all_envs:
        if VERBOSE:
            print "%s loading env %d/%d" % (log_prefix, count, total_envs)
        env_data[env] = chef.Environment(env).to_dict()

        if max_records and count == max_records:
            break

        count += 1
    return env_data
Example #9
0
 def perform(self, cm):
     log.debug("[CM] Creating environment %r", self.infra_id)
     chef.Environment(self.infra_id, api=cm.chefapi).save()
     log.debug("[CM] Done")
Example #10
0
 def get_create_environment(self, env_name):
     import chef
     env = chef.Environment(env_name, api=self.chef_api)
     env.save()
     return env