Return the targets from the ansible inventory_file
    Default: /etc/salt/roster
354262
def targets(tgt, tgt_type='glob', **kwargs):
    '''
    
    '''
    inventory = __runner__['salt.cmd']('cmd.run', 'ansible-inventory -i {0} --list'.format(get_roster_file(__opts__)))
    __context__['inventory'] = __utils__['json.loads'](__utils__['stringutils.to_str'](inventory))

    if tgt_type == 'glob':
        hosts = [host for host in _get_hosts_from_group('all') if fnmatch.fnmatch(host, tgt)]
    elif tgt_type == 'nodegroup':
        hosts = _get_hosts_from_group(tgt)
    return {host: _get_hostvars(host) for host in hosts}
1093060
def targets(tgt, tgt_type='glob', **kwargs):  # pylint: disable=W0613
    '''
    
    '''
    roster_file = os.path.abspath('terraform.tfstate')
    if __opts__.get('roster_file'):
        roster_file = os.path.abspath(__opts__['roster_file'])

    if not os.path.isfile(roster_file):
        log.error("Can't find terraform state file '%s'", roster_file)
        return {}

    log.debug('terraform roster: using %s state file', roster_file)

    if not roster_file.endswith('.tfstate'):
        log.error("Terraform roster can only be used with terraform state files")
        return {}

    raw = _parse_state_file(roster_file)
    log.debug('%s hosts in terraform state file', len(raw))
    return __utils__['roster_matcher.targets'](raw, tgt, tgt_type, 'ipv4')
1030160
def get_targets_by_plugin(plugin_name, conn=None):
    
    targets = RBT
    results = targets.filter({PLUGIN_NAME_KEY: plugin_name}).run(conn)
    for item in results:
        yield item
713553
def handle_ssh(self, mine=False):
        '''
        
        '''
        que = multiprocessing.Queue()
        running = {}
        target_iter = self.targets.__iter__()
        returned = set()
        rets = set()
        init = False
        while True:
            if not self.targets:
                log.error('No matching targets found in roster.')
                break
            if len(running) < self.opts.get('ssh_max_procs', 25) and not init:
                try:
                    host = next(target_iter)
                except StopIteration:
                    init = True
                    continue
                for default in self.defaults:
                    if default not in self.targets[host]:
                        self.targets[host][default] = self.defaults[default]
                if 'host' not in self.targets[host]:
                    self.targets[host]['host'] = host
                if self.targets[host].get('winrm') and not HAS_WINSHELL:
                    returned.add(host)
                    rets.add(host)
                    log_msg = 'Please contact sales@saltstack.com for access to the enterprise saltwinshell module.'
                    log.debug(log_msg)
                    no_ret = {'fun_args': [],
                              'jid': None,
                              'return': log_msg,
                              'retcode': 1,
                              'fun': '',
                              'id': host}
                    yield {host: no_ret}
                    continue
                args = (
                        que,
                        self.opts,
                        host,
                        self.targets[host],
                        mine,
                        )
                routine = MultiprocessingProcess(
                                target=self.handle_routine,
                                args=args)
                routine.start()
                running[host] = {'thread': routine}
                continue
            ret = {}
            try:
                ret = que.get(False)
                if 'id' in ret:
                    returned.add(ret['id'])
                    yield {ret['id']: ret['ret']}
            except Exception:
                # This bare exception is here to catch spurious exceptions
                # thrown by que.get during healthy operation. Please do not
                # worry about this bare exception, it is entirely here to
                # control program flow.
                pass
            for host in running:
                if not running[host]['thread'].is_alive():
                    if host not in returned:
                        # Try to get any returns that came through since we
                        # last checked
                        try:
                            while True:
                                ret = que.get(False)
                                if 'id' in ret:
                                    returned.add(ret['id'])
                                    yield {ret['id']: ret['ret']}
                        except Exception:
                            pass

                        if host not in returned:
                            error = ('Target \'{0}\' did not return any data, '
                                     'probably due to an error.').format(host)
                            ret = {'id': host,
                                   'ret': error}
                            log.error(error)
                            yield {ret['id']: ret['ret']}
                    running[host]['thread'].join()
                    rets.add(host)
            for host in rets:
                if host in running:
                    running.pop(host)
            if len(rets) >= len(self.targets):
                break
            # Sleep when limit or all threads started
            if len(running) >= self.opts.get('ssh_max_procs', 25) or len(self.targets) >= len(running):
                time.sleep(0.1)
76745
def get_targets(self):
        
        if not hasattr(self, "_targets"):
            targets = []
            for target_def in self.config.targets or []:
                target = Target(target_def)
                targets.append(target)
            self._targets = targets
        return self._targets
965433
def determine_target_roots(self, goal_name):
    
    if not self.context.target_roots:
      print('WARNING: No targets were matched in goal `{}`.'.format(goal_name), file=sys.stderr)

    # For the v2 path, e.g. `./pants list` is a functional no-op. This matches the v2 mode behavior
    # of e.g. `./pants --changed-parent=HEAD list` (w/ no changes) returning an empty result.
    return self.context.target_roots
1012938
def symlink_list(self, load):
        '''
        
        '''
        if 'env' in load:
            # "env" is not supported; Use "saltenv".
            load.pop('env')

        ret = {}
        if 'saltenv' not in load:
            return {}
        if not isinstance(load['saltenv'], six.string_types):
            load['saltenv'] = six.text_type(load['saltenv'])

        for fsb in self.backends(load.pop('fsbackend', None)):
            symlstr = '{0}.symlink_list'.format(fsb)
            if symlstr in self.servers:
                ret = self.servers[symlstr](load)
        # some *fs do not handle prefix. Ensure it is filtered
        prefix = load.get('prefix', '').strip('/')
        if prefix != '':
            ret = dict([
                (x, y) for x, y in six.iteritems(ret) if x.startswith(prefix)
            ])
        return ret
151801
def get_jids(returner):
    '''
    
    '''
    returners = salt.loader.returners(__opts__, __salt__)
    return returners['{0}.get_jids'.format(returner)]()
672497
def targets
      @targets ||= Dir.glob(File.join(target_dir, '*.rb'))
                      .collect { |t| t.gsub("#{target_dir}/", '').gsub('.rb', '').intern }
    end
1240583
def collect_ansible_classes():
    """"""
    def trace_calls(frame, event, arg):  # pylint: disable=W0613
        """Trace function calls to collect ansible classes.

        Trace functions and check if they have self as an arg. If so, get their class if the
        class belongs to ansible.
        """
        if event != 'call':
            return
        try:
            _locals = inspect.getargvalues(frame).locals
            if 'self' not in _locals:
                return
            _class = _locals['self'].__class__
            _class_repr = repr(_class)
            if 'ansible' not in _class_repr:
                return
            ANSIBLE_CLASSES[_class] = True
        except (AttributeError, TypeError):
            pass

    print "Gathering classes"
    sys.settrace(trace_calls)
    main()
1286954
def _bulk_state(saltfunc, lbn, workers, profile):
    '''
    
    '''
    ret = {'name': lbn,
           'result': True,
           'changes': {},
           'comment': ''}

    if not isinstance(workers, list):
        ret['result'] = False
        ret['comment'] = 'workers should be a list not a {0}'.format(
            type(workers)
        )
        return ret

    if __opts__['test']:
        ret['result'] = None
        return ret

    log.info('executing %s to modjk workers %s', saltfunc, workers)
    try:
        cmdret = __salt__[saltfunc](workers, lbn, profile=profile)
    except KeyError:
        ret['result'] = False
        ret['comment'] = 'unsupported function {0}'.format(
            saltfunc
        )
        return ret

    errors = []
    for worker, ok in six.iteritems(cmdret):
        if not ok:
            errors.append(worker)

    ret['changes'] = {'status': cmdret}
    if errors:
        ret['result'] = False
        ret['comment'] = '{0} failed on some workers'.format(saltfunc)

    return ret
740513
def targets(self, module):
        

        if module not in self.module_targets:
            raise BuildError("Could not find module in targets()", module=module)

        return [self.find(x, module) for x in self.module_targets[module]]
549414
def list_(bank, cachedir=None):
    '''
    
    '''
    if cachedir is None:
        cachedir = __opts__['cachedir']

    try:
        cache = salt.cache.Cache(__opts__, cachedir=cachedir)
    except TypeError:
        cache = salt.cache.Cache(__opts__)
    return cache.list(bank)
449016
def _file_lists(self, load, form):
        '''
        
        '''
        if 'env' in load:
            # "env" is not supported; Use "saltenv".
            load.pop('env')

        if not os.path.isdir(self.file_list_cachedir):
            try:
                os.makedirs(self.file_list_cachedir)
            except os.error:
                log.error('Unable to make cachedir %s', self.file_list_cachedir)
                return []
        list_cache = salt.utils.path.join(
            self.file_list_cachedir,
            '{0}.p'.format(load['saltenv'].replace(os.path.sep, '_|-'))
        )
        w_lock = salt.utils.path.join(
            self.file_list_cachedir,
            '.{0}.w'.format(load['saltenv'].replace(os.path.sep, '_|-'))
        )
        cache_match, refresh_cache, save_cache = \
            salt.fileserver.check_file_list_cache(
                self.opts, form, list_cache, w_lock
            )
        if cache_match is not None:
            return cache_match
        if refresh_cache:
            ret = {'files': set(), 'symlinks': {}, 'dirs': set()}
            if salt.utils.stringutils.is_hex(load['saltenv']) \
                    or load['saltenv'] in self.envs():
                for repo in self.remotes:
                    repo_files, repo_symlinks = repo.file_list(load['saltenv'])
                    ret['files'].update(repo_files)
                    ret['symlinks'].update(repo_symlinks)
                    ret['dirs'].update(repo.dir_list(load['saltenv']))
            ret['files'] = sorted(ret['files'])
            ret['dirs'] = sorted(ret['dirs'])

            if save_cache:
                salt.fileserver.write_file_list_cache(
                    self.opts, ret, list_cache, w_lock
                )
            # NOTE: symlinks are organized in a dict instead of a list, however
            # the 'symlinks' key will be defined above so it will never get to
            # the default value in the call to ret.get() below.
            return ret.get(form, [])
        # Shouldn't get here, but if we do, this prevents a TypeError
        return {} if form == 'symlinks' else []
588561
def get_managers(self):
        
        if self._single_env:
            return None
        if not hasattr(self, '_managers'):
            self._managers = self.env.get_slave_managers()
        return self._managers
3187
def atlas_get_zonefile_inventory( offset=None, length=None ):
    
    global ZONEFILE_INV, ZONEFILE_INV_LOCK

    with ZONEFILE_INV_LOCK:
        try:
            assert ZONEFILE_INV is not None
        except AssertionError:
            log.error("FATAL: zonefile inventory not loaded")
            os.abort()

        if offset is None:
            offset = 0

        if length is None:
            length = len(ZONEFILE_INV) - offset

        if offset >= len(ZONEFILE_INV):
            return ""

        if offset + length > len(ZONEFILE_INV):
            length = len(ZONEFILE_INV) - offset
            
        ret = ZONEFILE_INV[offset:offset+length]
        return ret
1101736
def get_data(self, minion):
        '''
        
        '''
        ret = copy.deepcopy(__opts__.get('roster_defaults', {}))
        if isinstance(self.raw[minion], six.string_types):
            ret.update({'host': self.raw[minion]})
            return ret
        elif isinstance(self.raw[minion], dict):
            ret.update(self.raw[minion])
            return ret
        return False