Exemple #1
0
    def run(self, conn, tmp, module_name, module_args, inject):
        args = parse_kv(module_args)
        if not 'hostname' in args:
            raise ae("'hostname' is a required argument.")

        vv("created 'add_host' ActionModule: hostname=%s" % (args['hostname']))

        result = {'changed': True}

        new_host = Host(args['hostname'])
        inventory = self.runner.inventory

        # add the new host to the 'all' group
        allgroup = inventory.get_group('all')
        allgroup.add_host(new_host)
        result['changed'] = True

        # add it to the group if that was specified
        if 'groupname' in args:
            if not inventory.get_group(args['groupname']):
                new_group = Group(args['groupname'])
                inventory.add_group(new_group)

            ngobj = inventory.get_group(args['groupname'])
            ngobj.add_host(new_host)
            vv("created 'add_host' ActionModule: groupname=%s" %
               (args['groupname']))
            result['new_group'] = args['groupname']

        result['new_host'] = args['hostname']

        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #2
0
    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):

        # the group_by module does not need to pay attention to check mode.
        # it always runs.

        args = {}
        if complex_args:
            args.update(complex_args)
        args.update(parse_kv(self.runner.module_args))
        if not 'key' in args:
            raise ae("'key' is a required argument.")

        vv("created 'group_by' ActionModule: key=%s" % (args['key']))

        inventory = self.runner.inventory

        result = {'changed': False}

        ### find all groups
        groups = {}

        for host in self.runner.host_set:

            data = inject['hostvars'][host]
            if not check_conditional(
                    template.template(self.runner.basedir,
                                      self.runner.conditional, data)):
                continue
            group_name = template.template(self.runner.basedir, args['key'],
                                           data)
            group_name = group_name.replace(' ', '-')
            if group_name not in groups:
                groups[group_name] = []
            groups[group_name].append(host)

        result['groups'] = groups

        ### add to inventory
        for group, hosts in groups.items():
            inv_group = inventory.get_group(group)
            if not inv_group:
                inv_group = ansible.inventory.Group(name=group)
                inventory.add_group(inv_group)
            for host in hosts:
                del self.runner.inventory._vars_per_host[host]
                inv_host = inventory.get_host(host)
                if not inv_host:
                    inv_host = ansible.inventory.Host(name=host)
                if inv_group not in inv_host.get_groups():
                    result['changed'] = True
                    inv_group.add_host(inv_host)

        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #3
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' run the pause action module '''

        # note: this module does not need to pay attention to the 'check'
        # flag, it always runs

        hosts = ', '.join(self.runner.host_set)
        args = {}
        if complex_args:
            args.update(complex_args)
        # extra template call unneeded?
        args.update(parse_kv(template.template(self.runner.basedir, module_args, inject)))

        # Are 'minutes' or 'seconds' keys that exist in 'args'?
        if 'minutes' in args or 'seconds' in args:
            try:
                if 'minutes' in args:
                    self.pause_type = 'minutes'
                    # The time() command operates in seconds so we need to
                    # recalculate for minutes=X values.
                    self.seconds = int(args['minutes']) * 60
                else:
                    self.pause_type = 'seconds'
                    self.seconds = int(args['seconds'])
                    self.duration_unit = 'seconds'
            except ValueError, e:
                raise ae("non-integer value given for prompt duration:\n%s" % str(e))
    def _request(self, path, data = None, method = 'GET'):
        encoder = json.JSONEncoder()
        postData = {}

        if data:
            method = 'POST'
            for key in data:
                item = data.get(key)
                if type(item) is list or type(item) is dict:
                    if len(item) > 0 or key == 'recipients':
                        item = encoder.encode(item)
                if type(item) is int or type(item) is unicode or type(item) is bool:
                    item = str(item)
                if item and type(item) is str and len(item) > 0:
                    postData.__setitem__(key, item)

        request_result = {}
        try:
            if method == 'GET':
                request_result = requests.get('https://api.serverdensity.io/' + path, params = {'token': self.api_token})
            elif method == 'POST':
                request_result = requests.post('https://api.serverdensity.io/' + path, params = {'token': self.api_token}, data = postData)
            elif method == 'DELETE':
                request_result = requests.delete('https://api.serverdensity.io/' + path, params = {'token': self.api_token})
        except ae, e:
            raise ae('No result from ServerDensity API')
Exemple #5
0
    def run(self, conn, tmp, module_name, module_args, inject):
        args = parse_kv(module_args)
        if not "hostname" in args:
            raise ae("'hostname' is a required argument.")

        vv("created 'add_host' ActionModule: hostname=%s" % (args["hostname"]))

        result = {"changed": True}

        new_host = Host(args["hostname"])
        inventory = self.runner.inventory

        # add the new host to the 'all' group
        allgroup = inventory.get_group("all")
        allgroup.add_host(new_host)
        result["changed"] = True

        # add it to the group if that was specified
        if "groupname" in args:
            if not inventory.get_group(args["groupname"]):
                new_group = Group(args["groupname"])
                inventory.add_group(new_group)

            ngobj = inventory.get_group(args["groupname"])
            ngobj.add_host(new_host)
            vv("created 'add_host' ActionModule: groupname=%s" % (args["groupname"]))
            result["new_group"] = args["groupname"]

        result["new_host"] = args["hostname"]

        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #6
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
        ''' run the pause action module '''

        # note: this module does not need to pay attention to the 'check'
        # flag, it always runs

        hosts = ', '.join(self.runner.host_set)
        args = {}
        if complex_args:
            args.update(complex_args)
        # extra template call unneeded?
        args.update(parse_kv(template.template(self.runner.basedir, module_args, inject)))

        # Are 'minutes' or 'seconds' keys that exist in 'args'?
        if 'minutes' in args or 'seconds' in args:
            try:
                if 'minutes' in args:
                    self.pause_type = 'minutes'
                    # The time() command operates in seconds so we need to
                    # recalculate for minutes=X values.
                    self.seconds = int(args['minutes']) * 60
                else:
                    self.pause_type = 'seconds'
                    self.seconds = int(args['seconds'])
                    self.duration_unit = 'seconds'
            except ValueError, e:
                raise ae("non-integer value given for prompt duration:\n%s" % str(e))
Exemple #7
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        # the group_by module does not need to pay attention to check mode.
        # it always runs.

        args = {}
        if complex_args:
            args.update(complex_args)
        args.update(parse_kv(self.runner.module_args))
        if not 'key' in args:
            raise ae("'key' is a required argument.")

        vv("created 'group_by' ActionModule: key=%s"%(args['key']))

        inventory = self.runner.inventory

        result = {'changed': False}

        ### find all groups
        groups = {}

        for host in self.runner.host_set:
            data = {}
            data.update(inject)
            data.update(inject['hostvars'][host])
            conds = self.runner.conditional
            if type(conds) != list:
                conds = [ conds ]
            next_host = False
            for cond in conds:
                if not check_conditional(cond, self.runner.basedir, data, fail_on_undefined=self.runner.error_on_undefined_vars):
                    next_host = True
                    break
            if next_host:
                continue
            group_name = template.template(self.runner.basedir, args['key'], data)
            group_name = group_name.replace(' ','-')
            if group_name not in groups:
                groups[group_name] = []
            groups[group_name].append(host)

        result['groups'] = groups

        ### add to inventory
        for group, hosts in groups.items():
            inv_group = inventory.get_group(group)
            if not inv_group:
                inv_group = ansible.inventory.Group(name=group)
                inventory.add_group(inv_group)
            for host in hosts:
                del self.runner.inventory._vars_per_host[host]
                inv_host = inventory.get_host(host)
                if not inv_host:
                    inv_host = ansible.inventory.Host(name=host)
                if inv_group not in inv_host.get_groups():
                    result['changed'] = True
                    inv_group.add_host(inv_host)

        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #8
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        if self.runner.check:
            return ReturnData(conn=conn, comm_ok=True, result=dict(skipped=True, msg='check mode not supported for this module'))

        args = {}
        if complex_args:
            args.update(complex_args)
        args.update(parse_kv(module_args))
        if not 'hostname' in args and not 'name' in args:
            raise ae("'name' is a required argument.")

        result = {}

        # Parse out any hostname:port patterns
        new_name = args.get('name', args.get('hostname', None))
        vv("creating host via 'add_host': hostname=%s" % new_name)

        if ":" in new_name:
            new_name, new_port = new_name.split(":")
            args['ansible_ssh_port'] = new_port
        
        # create host and get inventory    
        new_host = Host(new_name)
        inventory = self.runner.inventory
        
        # Add any variables to the new_host
        for k in args.keys():
            if not k in [ 'name', 'hostname', 'groupname', 'groups' ]:
                new_host.set_variable(k, args[k]) 
                
        
        # add the new host to the 'all' group
        allgroup = inventory.get_group('all')
        allgroup.add_host(new_host)
       
        groupnames = args.get('groupname', args.get('groups', '')) 
        # add it to the group if that was specified
        if groupnames != '':
            for group_name in groupnames.split(","):
                if not inventory.get_group(group_name):
                    new_group = Group(group_name)
                    inventory.add_group(new_group)
                grp = inventory.get_group(group_name)
                grp.add_host(new_host)
            vv("added host to group via add_host module: %s" % group_name)
            result['new_groups'] = groupnames.split(",")
            
        result['new_host'] = new_name
        
        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #9
0
    def run(self, conn, tmp, module_name, module_args, inject):
        ''' run the pause actionmodule '''
        hosts = ', '.join(self.runner.host_set)
        args = parse_kv(template(self.runner.basedir, module_args, inject))

        # Are 'minutes' or 'seconds' keys that exist in 'args'?
        if 'minutes' in args or 'seconds' in args:
            try:
                if 'minutes' in args:
                    self.pause_type = 'minutes'
                    # The time() command operates in seconds so we need to
                    # recalculate for minutes=X values.
                    self.seconds = int(args['minutes']) * 60
                else:
                    self.pause_type = 'seconds'
                    self.seconds = int(args['seconds'])
                    self.duration_unit = 'seconds'
            except ValueError, e:
                raise ae("non-integer value given for prompt duration:\n%s" % str(e))
Exemple #10
0
    def run(self, conn, tmp, module_name, module_args, inject):
        args = parse_kv(self.runner.module_args)
        if not 'key' in args:
            raise ae("'key' is a required argument.")

        vv("created 'group_by' ActionModule: key=%s"%(args['key']))

        inventory = self.runner.inventory

        result = {'changed': False}

        ### find all groups
        groups = {}
        for host in self.runner.host_set:
            data = inject['hostvars'][host]
            if not check_conditional(template(self.runner.basedir, self.runner.conditional, data)):
                continue
            group_name = template(self.runner.basedir, args['key'], data)
            group_name = group_name.replace(' ','-')
            if group_name not in groups:
                groups[group_name] = []
            groups[group_name].append(host)

        result['groups'] = groups

        ### add to inventory
        for group, hosts in groups.items():
            inv_group = inventory.get_group(group)
            if not inv_group:
                inv_group = ansible.inventory.Group(name=group)
                inventory.add_group(inv_group)
            for host in hosts:
                inv_host = inventory.get_host(host)
                if not inv_host:
                    inv_host = ansible.inventory.Host(name=host)
                if inv_group not in inv_host.get_groups():
                    result['changed'] = True
                    inv_group.add_host(inv_host)

        return ReturnData(conn=conn, comm_ok=True, result=result)
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        # the group_by module does not need to pay attention to check mode.
        # it always runs.

        args = {}
        if complex_args:
            args.update(complex_args)
        args.update(parse_kv(self.runner.module_args))
        if not 'key' in args:
            raise ae("'key' is a required argument.")

        vv("created 'group_by' ActionModule: key=%s"%(args['key']))

        inventory = self.runner.inventory

        result = {'changed': False}

        ### find all groups
        groups = {}

        for host in self.runner.host_set:
Exemple #12
0
    def run(self, conn, tmp, module_name, module_args, inject):
        args = parse_kv(self.runner.module_args)
        if not 'key' in args:
            raise ae("'key' is a required argument.")

        vv("created 'group_by' ActionModule: key=%s" % (args['key']))

        inventory = self.runner.inventory

        result = {'changed': False}

        ### find all groups
        groups = {}
        for host in self.runner.host_set:
            data = inject['hostvars'][host]
            group_name = template(self.runner.basedir, args['key'], data)
            group_name = group_name.replace(' ', '-')
            if group_name not in groups:
                groups[group_name] = []
            groups[group_name].append(host)

        result['groups'] = groups

        ### add to inventory
        for group, hosts in groups.items():
            inv_group = inventory.get_group(group)
            if not inv_group:
                inv_group = ansible.inventory.Group(name=group)
                inventory.add_group(inv_group)
            for host in hosts:
                inv_host = inventory.get_host(host)
                if not inv_host:
                    inv_host = ansible.inventory.Host(name=host)
                if inv_group not in inv_host.get_groups():
                    result['changed'] = True
                    inv_group.add_host(inv_host)

        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #13
0
    def run(self, conn, tmp, module_name, module_args, inject):
        ''' run the pause actionmodule '''
        args = self.runner.module_args
        hosts = ', '.join(map(lambda x: x[1], self.runner.host_set))

        (self.pause_type, sep, pause_params) = args.partition('=')

        if self.pause_type == '':
            self.pause_type = 'prompt'
        elif not self.pause_type in self.PAUSE_TYPES:
            raise ae("invalid parameter for pause, '%s'. must be one of: %s" % \
                         (self.pause_type, ", ".join(self.PAUSE_TYPES)))

        # error checking
        if self.pause_type in ['minutes', 'seconds']:
            try:
                int(pause_params)
            except ValueError:
                raise ae("value given to %s parameter invalid: '%s', must be an integer" % \
                             self.pause_type, pause_params)

        # The time() command operates in seconds so we need to
        # recalculate for minutes=X values.
        if self.pause_type == 'minutes':
            self.seconds = int(pause_params) * 60
        elif self.pause_type == 'seconds':
            self.seconds = int(pause_params)
            self.duration_unit = 'seconds'
        else:
            # if no args are given we pause with a prompt
            if pause_params == '':
                self.prompt = "[%s]\nPress enter to continue: " % hosts
            else:
                self.prompt = "[%s]\n%s: " % (hosts, pause_params)

        vv("created 'pause' ActionModule: pause_type=%s, duration_unit=%s, calculated_seconds=%s, prompt=%s" % \
                (self.pause_type, self.duration_unit, self.seconds, self.prompt))

        try:
            self._start()
            if not self.pause_type == 'prompt':
                print "[%s]\nPausing for %s seconds" % (hosts, self.seconds)
                time.sleep(self.seconds)
            else:
                # Clear out any unflushed buffered input which would
                # otherwise be consumed by raw_input() prematurely.
                tcflush(sys.stdin, TCIFLUSH)
                raw_input(self.prompt)
        except KeyboardInterrupt:
            while True:
                print '\nAction? (a)bort/(c)ontinue: '
                c = getch()
                if c == 'c':
                    # continue playbook evaluation
                    break
                elif c == 'a':
                    # abort further playbook evaluation
                    raise ae('user requested abort!')
        finally:
            self._stop()

        return ReturnData(conn=conn, result=self.result)
    def ssh_config(self,
                   customers,
                   customer_name,
                   cage_name,
                   conn,
                   tmp,
                   module_name,
                   module_args,
                   inject,
                   complex_args=None,
                   **kwargs):
        try:
            args = {}
            if complex_args:
                args.update(complex_args)
            args.update(parse_kv(module_args))

            if not 'dest' in args:
                raise ae("'dest' is a required argument.")
            if not 'identity_file' in args:
                raise ae("'identity_file' is a required argument.")

            dest = args.get('dest', None)
            identity_file = args.get('identity_file', None)
            default_user = args.get('user', 'ec2-user')
            bastion_user = args.get('bastion_user',
                                    args.get('user', 'ec2-user'))

            # Iterate though all hosts in the customer, cage pair

            bastion_entries = []
            entries = []
            for host in customers[customer_name][cage_name]:
                data = {}
                data.update(inject)
                data.update(inject['hostvars'][host])

                # TODO use nucleator facts instead
                private_ip = data['ec2_private_ip_address']
                user = data.get('ansible_ssh_user', default_user)
                instance_name = host
                bastion_suffix = instance_name.split(".")
                short_name = bastion_suffix.pop(0)

                bastion_suffix = "{0}.{1}".format(
                    cage_name,
                    data['hostvars']['localhost']['customer_domain'])
                configfile = os.path.join(dest, customer_name, cage_name)

                if short_name == "bastion":
                    bastion_user = user
                    bastion_entries += ssh_config_bastion_entry(
                        "".join((short_name, "-", cage_name)), instance_name,
                        instance_name, bastion_user, identity_file)
                else:
                    # host shortcut by FQDN (except bastion, which uses for-real external routing)
                    entries += ssh_config_entry(
                        "".join((short_name, "-", cage_name)), instance_name,
                        private_ip, user, identity_file, configfile,
                        bastion_user, bastion_suffix)

                # host shortcut by "Group-Cage"
                entries += ssh_config_entry(
                    "".join((short_name, "-", cage_name)), "".join(
                        (short_name, "-", cage_name)), private_ip, user,
                    identity_file, configfile, bastion_user, bastion_suffix)

                # host shortcut by private_ip
                entries += ssh_config_entry(
                    "".join((short_name, "-", cage_name)), private_ip,
                    private_ip, user, identity_file, configfile, bastion_user,
                    bastion_suffix)

            config = ssh_config_header()
            config += SEPARATOR
            config += "".join(bastion_entries)
            config += SEPARATOR
            config += "".join(entries)

        except Exception, e:
            result = dict(failed=True, msg=type(e).__name__ + ": " + str(e))
            return ReturnData(conn=conn, comm_ok=False, result=result)
Exemple #15
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        if self.runner.noop_on_check(inject):
            return ReturnData(conn=conn, comm_ok=True, result=dict(skipped=True, msg='check mode not supported for this module'))

        args = {}
        if complex_args:
            args.update(complex_args)
        args.update(parse_kv(module_args))
        if not 'hostname' in args and not 'name' in args:
            raise ae("'name' is a required argument.")

        result = {}

        # Parse out any hostname:port patterns
        new_name = args.get('name', args.get('hostname', None))
        vv("creating host via 'add_host': hostname=%s" % new_name)

        if ":" in new_name:
            new_name, new_port = new_name.split(":")
            args['ansible_ssh_port'] = new_port
        
        # redefine inventory and get group "all"
        inventory = self.runner.inventory
        allgroup = inventory.get_group('all')

        # check if host in cache, add if not
        if new_name in inventory._hosts_cache:
            new_host = inventory._hosts_cache[new_name]
        else:
            new_host = Host(new_name)
            # only groups can be added directly to inventory
            inventory._hosts_cache[new_name] = new_host
            allgroup.add_host(new_host)

        # Add any variables to the new_host
        for k in args.keys():
            if not k in [ 'name', 'hostname', 'groupname', 'groups' ]:
                new_host.set_variable(k, args[k]) 
                
        
        groupnames = args.get('groupname', args.get('groups', args.get('group', ''))) 
        # add it to the group if that was specified
        if groupnames != '':
            for group_name in groupnames.split(","):
                group_name = group_name.strip()
                if not inventory.get_group(group_name):
                    new_group = Group(group_name)
                    inventory.add_group(new_group)
                grp = inventory.get_group(group_name)
                grp.add_host(new_host)

                # add this host to the group cache
                if inventory._groups_list is not None:
                    if group_name in inventory._groups_list:
                        if new_host.name not in inventory._groups_list[group_name]:
                            inventory._groups_list[group_name].append(new_host.name)

                vv("added host to group via add_host module: %s" % group_name)
            result['new_groups'] = groupnames.split(",")
            
        result['new_host'] = new_name

        # clear pattern caching completely since it's unpredictable what
        # patterns may have referenced the group
        inventory.clear_pattern_cache()
        
        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #16
0
                    self.pause_type = 'seconds'
                    self.seconds = int(args['seconds'])
                    self.duration_unit = 'seconds'
            except ValueError, e:
                raise ae("non-integer value given for prompt duration:\n%s" % str(e))
        # Is 'prompt' a key in 'args'?
        elif 'prompt' in args:
            self.pause_type = 'prompt'
            self.prompt = "[%s]\n%s:\n" % (hosts, args['prompt'])
        # Is 'args' empty, then this is the default prompted pause
        elif len(args.keys()) == 0:
            self.pause_type = 'prompt'
            self.prompt = "[%s]\nPress enter to continue:\n" % hosts
        # I have no idea what you're trying to do. But it's so wrong.
        else:
            raise ae("invalid pause type given. must be one of: %s" % \
                         ", ".join(self.PAUSE_TYPES))

        vv("created 'pause' ActionModule: pause_type=%s, duration_unit=%s, calculated_seconds=%s, prompt=%s" % \
                (self.pause_type, self.duration_unit, self.seconds, self.prompt))

        ########################################################################
        # Begin the hard work!
        try:
            self._start()
            if not self.pause_type == 'prompt':
                print "[%s]\nPausing for %s seconds" % (hosts, self.seconds)
                time.sleep(self.seconds)
            else:
                # Clear out any unflushed buffered input which would
                # otherwise be consumed by raw_input() prematurely.
                tcflush(sys.stdin, TCIFLUSH)
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        if self.runner.noop_on_check(inject):
            return ReturnData(conn=conn, comm_ok=True, result=dict(skipped=True, msg='check mode not supported for this module'))

        args = {}
        if complex_args:
            args.update(complex_args)
        args.update(parse_kv(module_args))
        if not 'api_token' in args:
            raise ae("'api_token' is a required argument.")

        self.api_token = args.get('api_token')

        self.force_update = args.get('force', False)
        self.cache_file_name = args.get('cache', False)
        cleanup = args.get('cleanup', False)
        just_download = args.get('readonly', False)

        if just_download:
          self.force_update = False
          self.cache_file_name = tempfile.mktemp(prefix='sd_', suffix='.json')
          cleanup = False

        result = {}

        self.list_all()

        if just_download:
          vv('Downloaded settings to %s' % self.cache_file_name)
          return ReturnData(conn=conn, comm_ok=True, result=result)

        services = {}
        devicegroup_alerts = {}
        servicegroup_alerts = {}

        vv('Ensure hosts...')
        for host in self.runner.host_set:
            vv('- ' + host)
            host_vars = self.runner.inventory.get_variables(host)
            facts = host_vars.get('ansible_facts', {})
            location = host_vars.get('location')
            if not location:
                location = {}

            host_services = host_vars.get('sd_services')
            if host_services:
                for host_service in host_services:
                    name = host_service.get('name')
                    if not services.has_key(name):
                        services.__setitem__(name, host_service)

            host_group = host_vars.get('sd_group')
            if not host_group:
                host_group = 'All others'

            host_devicegroup_alerts = host_vars.get('sd_devicegroup_alerts')
            if host_devicegroup_alerts:
                for name in host_devicegroup_alerts:
                    host_devicegroup_alert = host_devicegroup_alerts.get(name)
                    if not devicegroup_alerts.has_key(host_group):
                        devicegroup_alerts.__setitem__(host_group, {})
                    alerts = devicegroup_alerts.get(host_group)
                    if not alerts.has_key(name):
                        alerts.__setitem__(name, host_devicegroup_alert)
                        devicegroup_alerts.__setitem__(host_group, alerts)

            host_servicegroup_alerts = host_vars.get('sd_servicegroup_alerts')
            if host_servicegroup_alerts:
                for name in host_servicegroup_alerts:
                    if not servicegroup_alerts.has_key(name):
                        host_servicegroup_alert = host_servicegroup_alerts.get(name)
                        servicegroup_alerts.__setitem__(name, host_servicegroup_alert)

            self.ensure_host(
                cpuCores=facts.get('ansible_processor_count', None),
                group=host_group,
                hostname=host,
                installedRAM=facts.get('ansible_memtotal_mb', None),
                name=host,
                os={
                    'code': facts.get('ansible_system', '')+' '+facts.get('ansible_distribution', '')+' '+facts.get('ansible_distribution_release', '')+' '+facts.get('ansible_distribution_version', ''),
                    'name': facts.get('ansible_system', ''),
                    },
                # privateIPs=facts[''],
                # privateDNS=facts[''],
                publicIPs=facts.get('ansible_all_ipv4_addresses', '')+facts.get('ansible_all_ipv6_addresses', ''),
                # publicDNS=facts[''],
                swapSpace=facts.get('ansible_swaptotal_mb', None),
                location={
                    'countryCode': location.get('countryCode'),
                    'countryName': location.get('countryName'),
                    'text': location.get('text'),
                    },
                provider=host_vars.get('provider')
            )

            alerts = host_vars.get('sd_alerts')
            if alerts:
                vv('- - Ensure device alerts...')
                for alertname in alerts:
                    vv('- - - ' + alertname)
                    alert = alerts.get(alertname)
                    alert.__setitem__('host', host)
                    self.ensure_alert(alert, 'device')

        vv('Ensure device group alerts...')
        for groupname in devicegroup_alerts:
            vv('- ' + groupname)
            group_alerts = devicegroup_alerts.get(groupname)
            for alertname in group_alerts:
                vv('- - ' + alertname)
                alert = group_alerts.get(alertname)
                self.ensure_alert(alert, 'deviceGroup', groupname)

        vv('Ensure services...')
        for servicename in services:
            vv('- ' + servicename)
            service = services.get(servicename)
            self.ensure_service(servicename, service)
            alerts = service.get('alerts')
            if alerts:
                vv('- - Ensure service alerts...')
                for alertname in alerts:
                    vv('- - - ' + alertname)
                    alert = alerts.get(alertname)
                    alert.__setitem__('service', service.get('name'))
                    self.ensure_alert(alert, 'service')

        vv('Ensure service group alerts...')
        for servicegroupname in servicegroup_alerts:
            vv('- ' + servicegroupname)
            alert = servicegroup_alerts.get(servicegroupname)
            groupname = alert.get('group')
            self.ensure_alert(alert, 'serviceGroup', groupname)

        if cleanup:
            vv('Cleanup unused alerts...')
            self.cleanup_alerts()

        vv('Completed successfully!')

        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #18
0
    def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):

        # the group_by module does not need to pay attention to check mode.
        # it always runs.

        # module_args and complex_args have already been templated for the first host.
        # Use them here only to check that a key argument is provided.
        args = {}
        if complex_args:
            args.update(complex_args)
        args.update(parse_kv(module_args))
        if not 'key' in args:
            raise ae("'key' is a required argument.")

        vv("created 'group_by' ActionModule: key=%s"%(args['key']))

        inventory = self.runner.inventory

        result = {'changed': False}

        ### find all groups
        groups = {}

        for host in self.runner.host_set:
            data = {}
            data.update(inject)
            data.update(inject['hostvars'][host])
            conds = self.runner.conditional
            if type(conds) != list:
                conds = [ conds ]
            next_host = False
            for cond in conds:
                if not check_conditional(cond, self.runner.basedir, data, fail_on_undefined=self.runner.error_on_undefined_vars):
                    next_host = True
                    break
            if next_host:
                continue

            # Template original module_args and complex_args from runner for each host.
            host_module_args = template.template(self.runner.basedir, self.runner.module_args, data)
            host_complex_args = template.template(self.runner.basedir, self.runner.complex_args, data)
            host_args  = {}
            if host_complex_args:
                host_args.update(host_complex_args)
            host_args.update(parse_kv(host_module_args))

            group_name = host_args['key']
            group_name = group_name.replace(' ','-')
            if group_name not in groups:
                groups[group_name] = []
            groups[group_name].append(host)

        result['groups'] = groups

        ### add to inventory
        for group, hosts in groups.items():
            inv_group = inventory.get_group(group)
            if not inv_group:
                inv_group = ansible.inventory.Group(name=group)
                inventory.add_group(inv_group)
                inventory.get_group('all').add_child_group(inv_group)
                inv_group.vars = inventory.get_group_variables(group, update_cached=False, vault_password=inventory._vault_password)
            for host in hosts:
                if host in self.runner.inventory._vars_per_host:
                    del self.runner.inventory._vars_per_host[host]
                inv_host = inventory.get_host(host)
                if not inv_host:
                    inv_host = ansible.inventory.Host(name=host)
                if inv_group not in inv_host.get_groups():
                    result['changed'] = True
                    inv_group.add_host(inv_host)

        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #19
0
    def run(self, conn, tmp, module_name, module_args, inject):
        ''' run the pause actionmodule '''
        args = self.runner.module_args
        hosts = ', '.join(map(lambda x: x[1], self.runner.host_set))

        (self.pause_type, sep, pause_params) = args.partition('=')

        if self.pause_type == '':
            self.pause_type = 'prompt'
        elif not self.pause_type in self.PAUSE_TYPES:
            raise ae("invalid parameter for pause, '%s'. must be one of: %s" % \
                         (self.pause_type, ", ".join(self.PAUSE_TYPES)))

        # error checking
        if self.pause_type in ['minutes', 'seconds']:
            try:
                int(pause_params)
            except ValueError:
                raise ae("value given to %s parameter invalid: '%s', must be an integer" % \
                             self.pause_type, pause_params)

        # The time() command operates in seconds so we need to
        # recalculate for minutes=X values.
        if self.pause_type == 'minutes':
            self.seconds = int(pause_params) * 60
        elif self.pause_type == 'seconds':
            self.seconds = int(pause_params)
            self.duration_unit = 'seconds'
        else:
            # if no args are given we pause with a prompt
            if pause_params == '':
                self.prompt = "[%s]\nPress enter to continue: " % hosts
            else:
                self.prompt = "[%s]\n%s: " % (hosts, pause_params)

        vv("created 'pause' ActionModule: pause_type=%s, duration_unit=%s, calculated_seconds=%s, prompt=%s" % \
                (self.pause_type, self.duration_unit, self.seconds, self.prompt))

        try:
            self._start()
            if not self.pause_type == 'prompt':
                print "[%s]\nPausing for %s seconds" % (hosts, self.seconds)
                time.sleep(self.seconds)
            else:
                # Clear out any unflushed buffered input which would
                # otherwise be consumed by raw_input() prematurely.
                tcflush(sys.stdin, TCIFLUSH)
                raw_input(self.prompt)
        except KeyboardInterrupt:
            while True:
                print '\nAction? (a)bort/(c)ontinue: '
                c = getch()
                if c == 'c':
                    # continue playbook evaluation
                    break
                elif c == 'a':
                    # abort further playbook evaluation
                    raise ae('user requested abort!')
        finally:
            self._stop()

        return ReturnData(conn=conn, result=self.result)
Exemple #20
0
                    self.seconds = int(args['seconds'])
                    self.duration_unit = 'seconds'
            except ValueError, e:
                raise ae("non-integer value given for prompt duration:\n%s" %
                         str(e))
        # Is 'prompt' a key in 'args'?
        elif 'prompt' in args:
            self.pause_type = 'prompt'
            self.prompt = "[%s]\n%s:\n" % (hosts, args['prompt'])
        # Is 'args' empty, then this is the default prompted pause
        elif len(args.keys()) == 0:
            self.pause_type = 'prompt'
            self.prompt = "[%s]\nPress enter to continue:\n" % hosts
        # I have no idea what you're trying to do. But it's so wrong.
        else:
            raise ae("invalid pause type given. must be one of: %s" % \
                         ", ".join(self.PAUSE_TYPES))

        vv("created 'pause' ActionModule: pause_type=%s, duration_unit=%s, calculated_seconds=%s, prompt=%s" % \
                (self.pause_type, self.duration_unit, self.seconds, self.prompt))

        ########################################################################
        # Begin the hard work!
        try:
            self._start()
            if not self.pause_type == 'prompt':
                print "[%s]\nPausing for %s seconds" % (hosts, self.seconds)
                time.sleep(self.seconds)
            else:
                # Clear out any unflushed buffered input which would
                # otherwise be consumed by raw_input() prematurely.
                tcflush(sys.stdin, TCIFLUSH)
Exemple #21
0
    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):

        if self.runner.noop_on_check(inject):
            return ReturnData(
                conn=conn,
                comm_ok=True,
                result=dict(skipped=True,
                            msg='check mode not supported for this module'))

        args = {}
        if complex_args:
            args.update(complex_args)
        args.update(parse_kv(module_args))
        if not 'hostname' in args and not 'name' in args:
            raise ae("'name' is a required argument.")

        result = {}

        # Parse out any hostname:port patterns
        new_name = args.get('name', args.get('hostname', None))
        vv("creating host via 'add_host': hostname=%s" % new_name)

        if ":" in new_name:
            new_name, new_port = new_name.split(":")
            args['ansible_ssh_port'] = new_port

        # redefine inventory and get group "all"
        inventory = self.runner.inventory
        allgroup = inventory.get_group('all')

        # check if host in cache, add if not
        if new_name in inventory._hosts_cache:
            new_host = inventory._hosts_cache[new_name]
        else:
            new_host = Host(new_name)
            # only groups can be added directly to inventory
            inventory._hosts_cache[new_name] = new_host
            allgroup.add_host(new_host)

        # Add any variables to the new_host
        for k in args.keys():
            if not k in ['name', 'hostname', 'groupname', 'groups']:
                new_host.set_variable(k, args[k])

        groupnames = args.get('groupname',
                              args.get('groups', args.get('group', '')))
        # add it to the group if that was specified
        if groupnames != '':
            for group_name in groupnames.split(","):
                group_name = group_name.strip()
                if not inventory.get_group(group_name):
                    new_group = Group(group_name)
                    inventory.add_group(new_group)
                grp = inventory.get_group(group_name)
                grp.add_host(new_host)

                # add this host to the group cache
                if inventory._groups_list is not None:
                    if group_name in inventory._groups_list:
                        if new_host.name not in inventory._groups_list[
                                group_name]:
                            inventory._groups_list[group_name].append(
                                new_host.name)

                vv("added host to group via add_host module: %s" % group_name)
            result['new_groups'] = groupnames.split(",")

        result['new_host'] = new_name

        # clear pattern caching completely since it's unpredictable what
        # patterns may have referenced the group
        inventory.clear_pattern_cache()

        return ReturnData(conn=conn, comm_ok=True, result=result)
Exemple #22
0
    def run(self,
            conn,
            tmp,
            module_name,
            module_args,
            inject,
            complex_args=None,
            **kwargs):

        # the group_by module does not need to pay attention to check mode.
        # it always runs.

        # module_args and complex_args have already been templated for the first host.
        # Use them here only to check that a key argument is provided.
        args = {}
        if complex_args:
            args.update(complex_args)
        args.update(parse_kv(module_args))
        if not 'key' in args:
            raise ae("'key' is a required argument.")

        vv("created 'group_by' ActionModule: key=%s" % (args['key']))

        inventory = self.runner.inventory

        result = {'changed': False}

        ### find all groups
        groups = {}

        for host in self.runner.host_set:
            data = {}
            data.update(inject)
            data.update(inject['hostvars'][host])
            conds = self.runner.conditional
            if type(conds) != list:
                conds = [conds]
            next_host = False
            for cond in conds:
                if not check_conditional(
                        cond,
                        self.runner.basedir,
                        data,
                        fail_on_undefined=self.runner.error_on_undefined_vars):
                    next_host = True
                    break
            if next_host:
                continue

            # Template original module_args and complex_args from runner for each host.
            host_module_args = template.template(self.runner.basedir,
                                                 self.runner.module_args, data)
            host_complex_args = template.template(self.runner.basedir,
                                                  self.runner.complex_args,
                                                  data)
            host_args = {}
            if host_complex_args:
                host_args.update(host_complex_args)
            host_args.update(parse_kv(host_module_args))

            group_name = host_args['key']
            group_name = group_name.replace(' ', '-')
            if group_name not in groups:
                groups[group_name] = []
            groups[group_name].append(host)

        result['groups'] = groups

        ### add to inventory
        for group, hosts in groups.items():
            inv_group = inventory.get_group(group)
            if not inv_group:
                inv_group = ansible.inventory.Group(name=group)
                inventory.add_group(inv_group)
            for host in hosts:
                if host in self.runner.inventory._vars_per_host:
                    del self.runner.inventory._vars_per_host[host]
                inv_host = inventory.get_host(host)
                if not inv_host:
                    inv_host = ansible.inventory.Host(name=host)
                if inv_group not in inv_host.get_groups():
                    result['changed'] = True
                    inv_group.add_host(inv_host)

        return ReturnData(conn=conn, comm_ok=True, result=result)