repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
saltstack/salt
salt/utils/minions.py
parse_target
def parse_target(target_expression): '''Parse `target_expressing` splitting it into `engine`, `delimiter`, `pattern` - returns a dict''' match = TARGET_REX.match(target_expression) if not match: log.warning('Unable to parse target "%s"', target_expression) ret = { 'engine': None, 'delimiter': None, 'pattern': target_expression, } else: ret = match.groupdict() return ret
python
def parse_target(target_expression): '''Parse `target_expressing` splitting it into `engine`, `delimiter`, `pattern` - returns a dict''' match = TARGET_REX.match(target_expression) if not match: log.warning('Unable to parse target "%s"', target_expression) ret = { 'engine': None, 'delimiter': None, 'pattern': target_expression, } else: ret = match.groupdict() return ret
[ "def", "parse_target", "(", "target_expression", ")", ":", "match", "=", "TARGET_REX", ".", "match", "(", "target_expression", ")", "if", "not", "match", ":", "log", ".", "warning", "(", "'Unable to parse target \"%s\"'", ",", "target_expression", ")", "ret", "=...
Parse `target_expressing` splitting it into `engine`, `delimiter`, `pattern` - returns a dict
[ "Parse", "target_expressing", "splitting", "it", "into", "engine", "delimiter", "pattern", "-", "returns", "a", "dict" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L50-L64
train
saltstack/salt
salt/utils/minions.py
get_minion_data
def get_minion_data(minion, opts): ''' Get the grains/pillar for a specific minion. If minion is None, it will return the grains/pillar for the first minion it finds. Return value is a tuple of the minion ID, grains, and pillar ''' grains = None pillar = None if opts.get('minion_data_cache', False): cache = salt.cache.factory(opts) if minion is None: for id_ in cache.list('minions'): data = cache.fetch('minions/{0}'.format(id_), 'data') if data is None: continue else: data = cache.fetch('minions/{0}'.format(minion), 'data') if data is not None: grains = data.get('grains', None) pillar = data.get('pillar', None) return minion if minion else None, grains, pillar
python
def get_minion_data(minion, opts): ''' Get the grains/pillar for a specific minion. If minion is None, it will return the grains/pillar for the first minion it finds. Return value is a tuple of the minion ID, grains, and pillar ''' grains = None pillar = None if opts.get('minion_data_cache', False): cache = salt.cache.factory(opts) if minion is None: for id_ in cache.list('minions'): data = cache.fetch('minions/{0}'.format(id_), 'data') if data is None: continue else: data = cache.fetch('minions/{0}'.format(minion), 'data') if data is not None: grains = data.get('grains', None) pillar = data.get('pillar', None) return minion if minion else None, grains, pillar
[ "def", "get_minion_data", "(", "minion", ",", "opts", ")", ":", "grains", "=", "None", "pillar", "=", "None", "if", "opts", ".", "get", "(", "'minion_data_cache'", ",", "False", ")", ":", "cache", "=", "salt", ".", "cache", ".", "factory", "(", "opts",...
Get the grains/pillar for a specific minion. If minion is None, it will return the grains/pillar for the first minion it finds. Return value is a tuple of the minion ID, grains, and pillar
[ "Get", "the", "grains", "/", "pillar", "for", "a", "specific", "minion", ".", "If", "minion", "is", "None", "it", "will", "return", "the", "grains", "/", "pillar", "for", "the", "first", "minion", "it", "finds", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L67-L88
train
saltstack/salt
salt/utils/minions.py
nodegroup_comp
def nodegroup_comp(nodegroup, nodegroups, skip=None, first_call=True): ''' Recursively expand ``nodegroup`` from ``nodegroups``; ignore nodegroups in ``skip`` If a top-level (non-recursive) call finds no nodegroups, return the original nodegroup definition (for backwards compatibility). Keep track of recursive calls via `first_call` argument ''' expanded_nodegroup = False if skip is None: skip = set() elif nodegroup in skip: log.error('Failed nodegroup expansion: illegal nested nodegroup "%s"', nodegroup) return '' if nodegroup not in nodegroups: log.error('Failed nodegroup expansion: unknown nodegroup "%s"', nodegroup) return '' nglookup = nodegroups[nodegroup] if isinstance(nglookup, six.string_types): words = nglookup.split() elif isinstance(nglookup, (list, tuple)): words = nglookup else: log.error('Nodegroup \'%s\' (%s) is neither a string, list nor tuple', nodegroup, nglookup) return '' skip.add(nodegroup) ret = [] opers = ['and', 'or', 'not', '(', ')'] for word in words: if not isinstance(word, six.string_types): word = six.text_type(word) if word in opers: ret.append(word) elif len(word) >= 3 and word.startswith('N@'): expanded_nodegroup = True ret.extend(nodegroup_comp(word[2:], nodegroups, skip=skip, first_call=False)) else: ret.append(word) if ret: ret.insert(0, '(') ret.append(')') skip.remove(nodegroup) log.debug('nodegroup_comp(%s) => %s', nodegroup, ret) # Only return list form if a nodegroup was expanded. Otherwise return # the original string to conserve backwards compat if expanded_nodegroup or not first_call: return ret else: opers_set = set(opers) ret = words if (set(ret) - opers_set) == set(ret): # No compound operators found in nodegroup definition. Check for # group type specifiers group_type_re = re.compile('^[A-Z]@') regex_chars = ['(', '[', '{', '\\', '?', '}', ']', ')'] if not [x for x in ret if '*' in x or group_type_re.match(x)]: # No group type specifiers and no wildcards. # Treat this as an expression. if [x for x in ret if x in [x for y in regex_chars if y in x]]: joined = 'E@' + ','.join(ret) log.debug( 'Nodegroup \'%s\' (%s) detected as an expression. ' 'Assuming compound matching syntax of \'%s\'', nodegroup, ret, joined ) else: # Treat this as a list of nodenames. joined = 'L@' + ','.join(ret) log.debug( 'Nodegroup \'%s\' (%s) detected as list of nodenames. ' 'Assuming compound matching syntax of \'%s\'', nodegroup, ret, joined ) # Return data must be a list of compound matching components # to be fed into compound matcher. Enclose return data in list. return [joined] log.debug( 'No nested nodegroups detected. Using original nodegroup ' 'definition: %s', nodegroups[nodegroup] ) return ret
python
def nodegroup_comp(nodegroup, nodegroups, skip=None, first_call=True): ''' Recursively expand ``nodegroup`` from ``nodegroups``; ignore nodegroups in ``skip`` If a top-level (non-recursive) call finds no nodegroups, return the original nodegroup definition (for backwards compatibility). Keep track of recursive calls via `first_call` argument ''' expanded_nodegroup = False if skip is None: skip = set() elif nodegroup in skip: log.error('Failed nodegroup expansion: illegal nested nodegroup "%s"', nodegroup) return '' if nodegroup not in nodegroups: log.error('Failed nodegroup expansion: unknown nodegroup "%s"', nodegroup) return '' nglookup = nodegroups[nodegroup] if isinstance(nglookup, six.string_types): words = nglookup.split() elif isinstance(nglookup, (list, tuple)): words = nglookup else: log.error('Nodegroup \'%s\' (%s) is neither a string, list nor tuple', nodegroup, nglookup) return '' skip.add(nodegroup) ret = [] opers = ['and', 'or', 'not', '(', ')'] for word in words: if not isinstance(word, six.string_types): word = six.text_type(word) if word in opers: ret.append(word) elif len(word) >= 3 and word.startswith('N@'): expanded_nodegroup = True ret.extend(nodegroup_comp(word[2:], nodegroups, skip=skip, first_call=False)) else: ret.append(word) if ret: ret.insert(0, '(') ret.append(')') skip.remove(nodegroup) log.debug('nodegroup_comp(%s) => %s', nodegroup, ret) # Only return list form if a nodegroup was expanded. Otherwise return # the original string to conserve backwards compat if expanded_nodegroup or not first_call: return ret else: opers_set = set(opers) ret = words if (set(ret) - opers_set) == set(ret): # No compound operators found in nodegroup definition. Check for # group type specifiers group_type_re = re.compile('^[A-Z]@') regex_chars = ['(', '[', '{', '\\', '?', '}', ']', ')'] if not [x for x in ret if '*' in x or group_type_re.match(x)]: # No group type specifiers and no wildcards. # Treat this as an expression. if [x for x in ret if x in [x for y in regex_chars if y in x]]: joined = 'E@' + ','.join(ret) log.debug( 'Nodegroup \'%s\' (%s) detected as an expression. ' 'Assuming compound matching syntax of \'%s\'', nodegroup, ret, joined ) else: # Treat this as a list of nodenames. joined = 'L@' + ','.join(ret) log.debug( 'Nodegroup \'%s\' (%s) detected as list of nodenames. ' 'Assuming compound matching syntax of \'%s\'', nodegroup, ret, joined ) # Return data must be a list of compound matching components # to be fed into compound matcher. Enclose return data in list. return [joined] log.debug( 'No nested nodegroups detected. Using original nodegroup ' 'definition: %s', nodegroups[nodegroup] ) return ret
[ "def", "nodegroup_comp", "(", "nodegroup", ",", "nodegroups", ",", "skip", "=", "None", ",", "first_call", "=", "True", ")", ":", "expanded_nodegroup", "=", "False", "if", "skip", "is", "None", ":", "skip", "=", "set", "(", ")", "elif", "nodegroup", "in"...
Recursively expand ``nodegroup`` from ``nodegroups``; ignore nodegroups in ``skip`` If a top-level (non-recursive) call finds no nodegroups, return the original nodegroup definition (for backwards compatibility). Keep track of recursive calls via `first_call` argument
[ "Recursively", "expand", "nodegroup", "from", "nodegroups", ";", "ignore", "nodegroups", "in", "skip" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L91-L179
train
saltstack/salt
salt/utils/minions.py
mine_get
def mine_get(tgt, fun, tgt_type='glob', opts=None): ''' Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type ''' ret = {} serial = salt.payload.Serial(opts) checker = CkMinions(opts) _res = checker.check_minions( tgt, tgt_type) minions = _res['minions'] cache = salt.cache.factory(opts) if isinstance(fun, six.string_types): functions = list(set(fun.split(','))) _ret_dict = len(functions) > 1 elif isinstance(fun, list): functions = fun _ret_dict = True else: return {} for minion in minions: mdata = cache.fetch('minions/{0}'.format(minion), 'mine') if not isinstance(mdata, dict): continue if not _ret_dict and functions and functions[0] in mdata: ret[minion] = mdata.get(functions) elif _ret_dict: for fun in functions: if fun in mdata: ret.setdefault(fun, {})[minion] = mdata.get(fun) return ret
python
def mine_get(tgt, fun, tgt_type='glob', opts=None): ''' Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type ''' ret = {} serial = salt.payload.Serial(opts) checker = CkMinions(opts) _res = checker.check_minions( tgt, tgt_type) minions = _res['minions'] cache = salt.cache.factory(opts) if isinstance(fun, six.string_types): functions = list(set(fun.split(','))) _ret_dict = len(functions) > 1 elif isinstance(fun, list): functions = fun _ret_dict = True else: return {} for minion in minions: mdata = cache.fetch('minions/{0}'.format(minion), 'mine') if not isinstance(mdata, dict): continue if not _ret_dict and functions and functions[0] in mdata: ret[minion] = mdata.get(functions) elif _ret_dict: for fun in functions: if fun in mdata: ret.setdefault(fun, {})[minion] = mdata.get(fun) return ret
[ "def", "mine_get", "(", "tgt", ",", "fun", ",", "tgt_type", "=", "'glob'", ",", "opts", "=", "None", ")", ":", "ret", "=", "{", "}", "serial", "=", "salt", ".", "payload", ".", "Serial", "(", "opts", ")", "checker", "=", "CkMinions", "(", "opts", ...
Gathers the data from the specified minions' mine, pass in the target, function to look up and the target type
[ "Gathers", "the", "data", "from", "the", "specified", "minions", "mine", "pass", "in", "the", "target", "function", "to", "look", "up", "and", "the", "target", "type" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L1130-L1166
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_nodegroup_minions
def _check_nodegroup_minions(self, expr, greedy): # pylint: disable=unused-argument ''' Return minions found by looking at nodegroups ''' return self._check_compound_minions(nodegroup_comp(expr, self.opts['nodegroups']), DEFAULT_TARGET_DELIM, greedy)
python
def _check_nodegroup_minions(self, expr, greedy): # pylint: disable=unused-argument ''' Return minions found by looking at nodegroups ''' return self._check_compound_minions(nodegroup_comp(expr, self.opts['nodegroups']), DEFAULT_TARGET_DELIM, greedy)
[ "def", "_check_nodegroup_minions", "(", "self", ",", "expr", ",", "greedy", ")", ":", "# pylint: disable=unused-argument", "return", "self", ".", "_check_compound_minions", "(", "nodegroup_comp", "(", "expr", ",", "self", ".", "opts", "[", "'nodegroups'", "]", ")"...
Return minions found by looking at nodegroups
[ "Return", "minions", "found", "by", "looking", "at", "nodegroups" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L201-L207
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_list_minions
def _check_list_minions(self, expr, greedy, ignore_missing=False): # pylint: disable=unused-argument ''' Return the minions found by looking via a list ''' if isinstance(expr, six.string_types): expr = [m for m in expr.split(',') if m] minions = self._pki_minions() return {'minions': [x for x in expr if x in minions], 'missing': [] if ignore_missing else [x for x in expr if x not in minions]}
python
def _check_list_minions(self, expr, greedy, ignore_missing=False): # pylint: disable=unused-argument ''' Return the minions found by looking via a list ''' if isinstance(expr, six.string_types): expr = [m for m in expr.split(',') if m] minions = self._pki_minions() return {'minions': [x for x in expr if x in minions], 'missing': [] if ignore_missing else [x for x in expr if x not in minions]}
[ "def", "_check_list_minions", "(", "self", ",", "expr", ",", "greedy", ",", "ignore_missing", "=", "False", ")", ":", "# pylint: disable=unused-argument", "if", "isinstance", "(", "expr", ",", "six", ".", "string_types", ")", ":", "expr", "=", "[", "m", "for...
Return the minions found by looking via a list
[ "Return", "the", "minions", "found", "by", "looking", "via", "a", "list" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L216-L224
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_pcre_minions
def _check_pcre_minions(self, expr, greedy): # pylint: disable=unused-argument ''' Return the minions found by looking via regular expressions ''' reg = re.compile(expr) return {'minions': [m for m in self._pki_minions() if reg.match(m)], 'missing': []}
python
def _check_pcre_minions(self, expr, greedy): # pylint: disable=unused-argument ''' Return the minions found by looking via regular expressions ''' reg = re.compile(expr) return {'minions': [m for m in self._pki_minions() if reg.match(m)], 'missing': []}
[ "def", "_check_pcre_minions", "(", "self", ",", "expr", ",", "greedy", ")", ":", "# pylint: disable=unused-argument", "reg", "=", "re", ".", "compile", "(", "expr", ")", "return", "{", "'minions'", ":", "[", "m", "for", "m", "in", "self", ".", "_pki_minion...
Return the minions found by looking via regular expressions
[ "Return", "the", "minions", "found", "by", "looking", "via", "regular", "expressions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L226-L232
train
saltstack/salt
salt/utils/minions.py
CkMinions._pki_minions
def _pki_minions(self): ''' Retreive complete minion list from PKI dir. Respects cache if configured ''' minions = [] pki_cache_fn = os.path.join(self.opts['pki_dir'], self.acc, '.key_cache') try: os.makedirs(os.path.dirname(pki_cache_fn)) except OSError: pass try: if self.opts['key_cache'] and os.path.exists(pki_cache_fn): log.debug('Returning cached minion list') if six.PY2: with salt.utils.files.fopen(pki_cache_fn) as fn_: return self.serial.load(fn_) else: with salt.utils.files.fopen(pki_cache_fn, mode='rb') as fn_: return self.serial.load(fn_) else: for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))): if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_)): minions.append(fn_) return minions except OSError as exc: log.error( 'Encountered OSError while evaluating minions in PKI dir: %s', exc ) return minions
python
def _pki_minions(self): ''' Retreive complete minion list from PKI dir. Respects cache if configured ''' minions = [] pki_cache_fn = os.path.join(self.opts['pki_dir'], self.acc, '.key_cache') try: os.makedirs(os.path.dirname(pki_cache_fn)) except OSError: pass try: if self.opts['key_cache'] and os.path.exists(pki_cache_fn): log.debug('Returning cached minion list') if six.PY2: with salt.utils.files.fopen(pki_cache_fn) as fn_: return self.serial.load(fn_) else: with salt.utils.files.fopen(pki_cache_fn, mode='rb') as fn_: return self.serial.load(fn_) else: for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))): if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_)): minions.append(fn_) return minions except OSError as exc: log.error( 'Encountered OSError while evaluating minions in PKI dir: %s', exc ) return minions
[ "def", "_pki_minions", "(", "self", ")", ":", "minions", "=", "[", "]", "pki_cache_fn", "=", "os", ".", "path", ".", "join", "(", "self", ".", "opts", "[", "'pki_dir'", "]", ",", "self", ".", "acc", ",", "'.key_cache'", ")", "try", ":", "os", ".", ...
Retreive complete minion list from PKI dir. Respects cache if configured
[ "Retreive", "complete", "minion", "list", "from", "PKI", "dir", ".", "Respects", "cache", "if", "configured" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L234-L264
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_cache_minions
def _check_cache_minions(self, expr, delimiter, greedy, search_type, regex_match=False, exact_match=False): ''' Helper function to search for minions in master caches If 'greedy', then return accepted minions matched by the condition or those absent from the cache. If not 'greedy' return the only minions have cache data and matched by the condition. ''' cache_enabled = self.opts.get('minion_data_cache', False) def list_cached_minions(): return self.cache.list('minions') if greedy: minions = [] for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))): if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_)): minions.append(fn_) elif cache_enabled: minions = list_cached_minions() else: return {'minions': [], 'missing': []} if cache_enabled: if greedy: cminions = list_cached_minions() else: cminions = minions if not cminions: return {'minions': minions, 'missing': []} minions = set(minions) for id_ in cminions: if greedy and id_ not in minions: continue mdata = self.cache.fetch('minions/{0}'.format(id_), 'data') if mdata is None: if not greedy: minions.remove(id_) continue search_results = mdata.get(search_type) if not salt.utils.data.subdict_match(search_results, expr, delimiter=delimiter, regex_match=regex_match, exact_match=exact_match): minions.remove(id_) minions = list(minions) return {'minions': minions, 'missing': []}
python
def _check_cache_minions(self, expr, delimiter, greedy, search_type, regex_match=False, exact_match=False): ''' Helper function to search for minions in master caches If 'greedy', then return accepted minions matched by the condition or those absent from the cache. If not 'greedy' return the only minions have cache data and matched by the condition. ''' cache_enabled = self.opts.get('minion_data_cache', False) def list_cached_minions(): return self.cache.list('minions') if greedy: minions = [] for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))): if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_)): minions.append(fn_) elif cache_enabled: minions = list_cached_minions() else: return {'minions': [], 'missing': []} if cache_enabled: if greedy: cminions = list_cached_minions() else: cminions = minions if not cminions: return {'minions': minions, 'missing': []} minions = set(minions) for id_ in cminions: if greedy and id_ not in minions: continue mdata = self.cache.fetch('minions/{0}'.format(id_), 'data') if mdata is None: if not greedy: minions.remove(id_) continue search_results = mdata.get(search_type) if not salt.utils.data.subdict_match(search_results, expr, delimiter=delimiter, regex_match=regex_match, exact_match=exact_match): minions.remove(id_) minions = list(minions) return {'minions': minions, 'missing': []}
[ "def", "_check_cache_minions", "(", "self", ",", "expr", ",", "delimiter", ",", "greedy", ",", "search_type", ",", "regex_match", "=", "False", ",", "exact_match", "=", "False", ")", ":", "cache_enabled", "=", "self", ".", "opts", ".", "get", "(", "'minion...
Helper function to search for minions in master caches If 'greedy', then return accepted minions matched by the condition or those absent from the cache. If not 'greedy' return the only minions have cache data and matched by the condition.
[ "Helper", "function", "to", "search", "for", "minions", "in", "master", "caches", "If", "greedy", "then", "return", "accepted", "minions", "matched", "by", "the", "condition", "or", "those", "absent", "from", "the", "cache", ".", "If", "not", "greedy", "retu...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L266-L321
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_grain_minions
def _check_grain_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via grains ''' return self._check_cache_minions(expr, delimiter, greedy, 'grains')
python
def _check_grain_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via grains ''' return self._check_cache_minions(expr, delimiter, greedy, 'grains')
[ "def", "_check_grain_minions", "(", "self", ",", "expr", ",", "delimiter", ",", "greedy", ")", ":", "return", "self", ".", "_check_cache_minions", "(", "expr", ",", "delimiter", ",", "greedy", ",", "'grains'", ")" ]
Return the minions found by looking via grains
[ "Return", "the", "minions", "found", "by", "looking", "via", "grains" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L323-L327
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_grain_pcre_minions
def _check_grain_pcre_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via grains with PCRE ''' return self._check_cache_minions(expr, delimiter, greedy, 'grains', regex_match=True)
python
def _check_grain_pcre_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via grains with PCRE ''' return self._check_cache_minions(expr, delimiter, greedy, 'grains', regex_match=True)
[ "def", "_check_grain_pcre_minions", "(", "self", ",", "expr", ",", "delimiter", ",", "greedy", ")", ":", "return", "self", ".", "_check_cache_minions", "(", "expr", ",", "delimiter", ",", "greedy", ",", "'grains'", ",", "regex_match", "=", "True", ")" ]
Return the minions found by looking via grains with PCRE
[ "Return", "the", "minions", "found", "by", "looking", "via", "grains", "with", "PCRE" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L329-L337
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_pillar_minions
def _check_pillar_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via pillar ''' return self._check_cache_minions(expr, delimiter, greedy, 'pillar')
python
def _check_pillar_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via pillar ''' return self._check_cache_minions(expr, delimiter, greedy, 'pillar')
[ "def", "_check_pillar_minions", "(", "self", ",", "expr", ",", "delimiter", ",", "greedy", ")", ":", "return", "self", ".", "_check_cache_minions", "(", "expr", ",", "delimiter", ",", "greedy", ",", "'pillar'", ")" ]
Return the minions found by looking via pillar
[ "Return", "the", "minions", "found", "by", "looking", "via", "pillar" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L339-L343
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_pillar_pcre_minions
def _check_pillar_pcre_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via pillar with PCRE ''' return self._check_cache_minions(expr, delimiter, greedy, 'pillar', regex_match=True)
python
def _check_pillar_pcre_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via pillar with PCRE ''' return self._check_cache_minions(expr, delimiter, greedy, 'pillar', regex_match=True)
[ "def", "_check_pillar_pcre_minions", "(", "self", ",", "expr", ",", "delimiter", ",", "greedy", ")", ":", "return", "self", ".", "_check_cache_minions", "(", "expr", ",", "delimiter", ",", "greedy", ",", "'pillar'", ",", "regex_match", "=", "True", ")" ]
Return the minions found by looking via pillar with PCRE
[ "Return", "the", "minions", "found", "by", "looking", "via", "pillar", "with", "PCRE" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L345-L353
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_pillar_exact_minions
def _check_pillar_exact_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via pillar ''' return self._check_cache_minions(expr, delimiter, greedy, 'pillar', exact_match=True)
python
def _check_pillar_exact_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via pillar ''' return self._check_cache_minions(expr, delimiter, greedy, 'pillar', exact_match=True)
[ "def", "_check_pillar_exact_minions", "(", "self", ",", "expr", ",", "delimiter", ",", "greedy", ")", ":", "return", "self", ".", "_check_cache_minions", "(", "expr", ",", "delimiter", ",", "greedy", ",", "'pillar'", ",", "exact_match", "=", "True", ")" ]
Return the minions found by looking via pillar
[ "Return", "the", "minions", "found", "by", "looking", "via", "pillar" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L355-L363
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_ipcidr_minions
def _check_ipcidr_minions(self, expr, greedy): ''' Return the minions found by looking via ipcidr ''' cache_enabled = self.opts.get('minion_data_cache', False) if greedy: minions = self._pki_minions() elif cache_enabled: minions = self.cache.list('minions') else: return {'minions': [], 'missing': []} if cache_enabled: if greedy: cminions = self.cache.list('minions') else: cminions = minions if cminions is None: return {'minions': minions, 'missing': []} tgt = expr try: # Target is an address? tgt = ipaddress.ip_address(tgt) except Exception: try: # Target is a network? tgt = ipaddress.ip_network(tgt) except Exception: log.error('Invalid IP/CIDR target: %s', tgt) return {'minions': [], 'missing': []} proto = 'ipv{0}'.format(tgt.version) minions = set(minions) for id_ in cminions: mdata = self.cache.fetch('minions/{0}'.format(id_), 'data') if mdata is None: if not greedy: minions.remove(id_) continue grains = mdata.get('grains') if grains is None or proto not in grains: match = False elif isinstance(tgt, (ipaddress.IPv4Address, ipaddress.IPv6Address)): match = six.text_type(tgt) in grains[proto] else: match = salt.utils.network.in_subnet(tgt, grains[proto]) if not match and id_ in minions: minions.remove(id_) return {'minions': list(minions), 'missing': []}
python
def _check_ipcidr_minions(self, expr, greedy): ''' Return the minions found by looking via ipcidr ''' cache_enabled = self.opts.get('minion_data_cache', False) if greedy: minions = self._pki_minions() elif cache_enabled: minions = self.cache.list('minions') else: return {'minions': [], 'missing': []} if cache_enabled: if greedy: cminions = self.cache.list('minions') else: cminions = minions if cminions is None: return {'minions': minions, 'missing': []} tgt = expr try: # Target is an address? tgt = ipaddress.ip_address(tgt) except Exception: try: # Target is a network? tgt = ipaddress.ip_network(tgt) except Exception: log.error('Invalid IP/CIDR target: %s', tgt) return {'minions': [], 'missing': []} proto = 'ipv{0}'.format(tgt.version) minions = set(minions) for id_ in cminions: mdata = self.cache.fetch('minions/{0}'.format(id_), 'data') if mdata is None: if not greedy: minions.remove(id_) continue grains = mdata.get('grains') if grains is None or proto not in grains: match = False elif isinstance(tgt, (ipaddress.IPv4Address, ipaddress.IPv6Address)): match = six.text_type(tgt) in grains[proto] else: match = salt.utils.network.in_subnet(tgt, grains[proto]) if not match and id_ in minions: minions.remove(id_) return {'minions': list(minions), 'missing': []}
[ "def", "_check_ipcidr_minions", "(", "self", ",", "expr", ",", "greedy", ")", ":", "cache_enabled", "=", "self", ".", "opts", ".", "get", "(", "'minion_data_cache'", ",", "False", ")", "if", "greedy", ":", "minions", "=", "self", ".", "_pki_minions", "(", ...
Return the minions found by looking via ipcidr
[ "Return", "the", "minions", "found", "by", "looking", "via", "ipcidr" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L365-L421
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_range_minions
def _check_range_minions(self, expr, greedy): ''' Return the minions found by looking via range expression ''' if not HAS_RANGE: raise CommandExecutionError( 'Range matcher unavailable (unable to import seco.range, ' 'module most likely not installed)' ) if not hasattr(self, '_range'): self._range = seco.range.Range(self.opts['range_server']) try: return self._range.expand(expr) except seco.range.RangeException as exc: log.error( 'Range exception in compound match: %s', exc ) cache_enabled = self.opts.get('minion_data_cache', False) if greedy: mlist = [] for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))): if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_)): mlist.append(fn_) return {'minions': mlist, 'missing': []} elif cache_enabled: return {'minions': self.cache.list('minions'), 'missing': []} else: return {'minions': [], 'missing': []}
python
def _check_range_minions(self, expr, greedy): ''' Return the minions found by looking via range expression ''' if not HAS_RANGE: raise CommandExecutionError( 'Range matcher unavailable (unable to import seco.range, ' 'module most likely not installed)' ) if not hasattr(self, '_range'): self._range = seco.range.Range(self.opts['range_server']) try: return self._range.expand(expr) except seco.range.RangeException as exc: log.error( 'Range exception in compound match: %s', exc ) cache_enabled = self.opts.get('minion_data_cache', False) if greedy: mlist = [] for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))): if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_)): mlist.append(fn_) return {'minions': mlist, 'missing': []} elif cache_enabled: return {'minions': self.cache.list('minions'), 'missing': []} else: return {'minions': [], 'missing': []}
[ "def", "_check_range_minions", "(", "self", ",", "expr", ",", "greedy", ")", ":", "if", "not", "HAS_RANGE", ":", "raise", "CommandExecutionError", "(", "'Range matcher unavailable (unable to import seco.range, '", "'module most likely not installed)'", ")", "if", "not", "...
Return the minions found by looking via range expression
[ "Return", "the", "minions", "found", "by", "looking", "via", "range", "expression" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L423-L453
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_compound_pillar_exact_minions
def _check_compound_pillar_exact_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via compound matcher Disable pillar glob matching ''' return self._check_compound_minions(expr, delimiter, greedy, pillar_exact=True)
python
def _check_compound_pillar_exact_minions(self, expr, delimiter, greedy): ''' Return the minions found by looking via compound matcher Disable pillar glob matching ''' return self._check_compound_minions(expr, delimiter, greedy, pillar_exact=True)
[ "def", "_check_compound_pillar_exact_minions", "(", "self", ",", "expr", ",", "delimiter", ",", "greedy", ")", ":", "return", "self", ".", "_check_compound_minions", "(", "expr", ",", "delimiter", ",", "greedy", ",", "pillar_exact", "=", "True", ")" ]
Return the minions found by looking via compound matcher Disable pillar glob matching
[ "Return", "the", "minions", "found", "by", "looking", "via", "compound", "matcher" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L455-L464
train
saltstack/salt
salt/utils/minions.py
CkMinions._check_compound_minions
def _check_compound_minions(self, expr, delimiter, greedy, pillar_exact=False): # pylint: disable=unused-argument ''' Return the minions found by looking via compound matcher ''' if not isinstance(expr, six.string_types) and not isinstance(expr, (list, tuple)): log.error('Compound target that is neither string, list nor tuple') return {'minions': [], 'missing': []} minions = set(self._pki_minions()) log.debug('minions: %s', minions) nodegroups = self.opts.get('nodegroups', {}) if self.opts.get('minion_data_cache', False): ref = {'G': self._check_grain_minions, 'P': self._check_grain_pcre_minions, 'I': self._check_pillar_minions, 'J': self._check_pillar_pcre_minions, 'L': self._check_list_minions, 'N': None, # nodegroups should already be expanded 'S': self._check_ipcidr_minions, 'E': self._check_pcre_minions, 'R': self._all_minions} if pillar_exact: ref['I'] = self._check_pillar_exact_minions ref['J'] = self._check_pillar_exact_minions results = [] unmatched = [] opers = ['and', 'or', 'not', '(', ')'] missing = [] if isinstance(expr, six.string_types): words = expr.split() else: # we make a shallow copy in order to not affect the passed in arg words = expr[:] while words: word = words.pop(0) target_info = parse_target(word) # Easy check first if word in opers: if results: if results[-1] == '(' and word in ('and', 'or'): log.error('Invalid beginning operator after "(": %s', word) return {'minions': [], 'missing': []} if word == 'not': if not results[-1] in ('&', '|', '('): results.append('&') results.append('(') results.append(six.text_type(set(minions))) results.append('-') unmatched.append('-') elif word == 'and': results.append('&') elif word == 'or': results.append('|') elif word == '(': results.append(word) unmatched.append(word) elif word == ')': if not unmatched or unmatched[-1] != '(': log.error('Invalid compound expr (unexpected ' 'right parenthesis): %s', expr) return {'minions': [], 'missing': []} results.append(word) unmatched.pop() if unmatched and unmatched[-1] == '-': results.append(')') unmatched.pop() else: # Won't get here, unless oper is added log.error('Unhandled oper in compound expr: %s', expr) return {'minions': [], 'missing': []} else: # seq start with oper, fail if word == 'not': results.append('(') results.append(six.text_type(set(minions))) results.append('-') unmatched.append('-') elif word == '(': results.append(word) unmatched.append(word) else: log.error( 'Expression may begin with' ' binary operator: %s', word ) return {'minions': [], 'missing': []} elif target_info and target_info['engine']: if 'N' == target_info['engine']: # if we encounter a node group, just evaluate it in-place decomposed = nodegroup_comp(target_info['pattern'], nodegroups) if decomposed: words = decomposed + words continue engine = ref.get(target_info['engine']) if not engine: # If an unknown engine is called at any time, fail out log.error( 'Unrecognized target engine "%s" for' ' target expression "%s"', target_info['engine'], word, ) return {'minions': [], 'missing': []} engine_args = [target_info['pattern']] if target_info['engine'] in ('G', 'P', 'I', 'J'): engine_args.append(target_info['delimiter'] or ':') engine_args.append(greedy) # ignore missing minions for lists if we exclude them with # a 'not' if 'L' == target_info['engine']: engine_args.append(results and results[-1] == '-') _results = engine(*engine_args) results.append(six.text_type(set(_results['minions']))) missing.extend(_results['missing']) if unmatched and unmatched[-1] == '-': results.append(')') unmatched.pop() else: # The match is not explicitly defined, evaluate as a glob _results = self._check_glob_minions(word, True) results.append(six.text_type(set(_results['minions']))) if unmatched and unmatched[-1] == '-': results.append(')') unmatched.pop() # Add a closing ')' for each item left in unmatched results.extend([')' for item in unmatched]) results = ' '.join(results) log.debug('Evaluating final compound matching expr: %s', results) try: minions = list(eval(results)) # pylint: disable=W0123 return {'minions': minions, 'missing': missing} except Exception: log.error('Invalid compound target: %s', expr) return {'minions': [], 'missing': []} return {'minions': list(minions), 'missing': []}
python
def _check_compound_minions(self, expr, delimiter, greedy, pillar_exact=False): # pylint: disable=unused-argument ''' Return the minions found by looking via compound matcher ''' if not isinstance(expr, six.string_types) and not isinstance(expr, (list, tuple)): log.error('Compound target that is neither string, list nor tuple') return {'minions': [], 'missing': []} minions = set(self._pki_minions()) log.debug('minions: %s', minions) nodegroups = self.opts.get('nodegroups', {}) if self.opts.get('minion_data_cache', False): ref = {'G': self._check_grain_minions, 'P': self._check_grain_pcre_minions, 'I': self._check_pillar_minions, 'J': self._check_pillar_pcre_minions, 'L': self._check_list_minions, 'N': None, # nodegroups should already be expanded 'S': self._check_ipcidr_minions, 'E': self._check_pcre_minions, 'R': self._all_minions} if pillar_exact: ref['I'] = self._check_pillar_exact_minions ref['J'] = self._check_pillar_exact_minions results = [] unmatched = [] opers = ['and', 'or', 'not', '(', ')'] missing = [] if isinstance(expr, six.string_types): words = expr.split() else: # we make a shallow copy in order to not affect the passed in arg words = expr[:] while words: word = words.pop(0) target_info = parse_target(word) # Easy check first if word in opers: if results: if results[-1] == '(' and word in ('and', 'or'): log.error('Invalid beginning operator after "(": %s', word) return {'minions': [], 'missing': []} if word == 'not': if not results[-1] in ('&', '|', '('): results.append('&') results.append('(') results.append(six.text_type(set(minions))) results.append('-') unmatched.append('-') elif word == 'and': results.append('&') elif word == 'or': results.append('|') elif word == '(': results.append(word) unmatched.append(word) elif word == ')': if not unmatched or unmatched[-1] != '(': log.error('Invalid compound expr (unexpected ' 'right parenthesis): %s', expr) return {'minions': [], 'missing': []} results.append(word) unmatched.pop() if unmatched and unmatched[-1] == '-': results.append(')') unmatched.pop() else: # Won't get here, unless oper is added log.error('Unhandled oper in compound expr: %s', expr) return {'minions': [], 'missing': []} else: # seq start with oper, fail if word == 'not': results.append('(') results.append(six.text_type(set(minions))) results.append('-') unmatched.append('-') elif word == '(': results.append(word) unmatched.append(word) else: log.error( 'Expression may begin with' ' binary operator: %s', word ) return {'minions': [], 'missing': []} elif target_info and target_info['engine']: if 'N' == target_info['engine']: # if we encounter a node group, just evaluate it in-place decomposed = nodegroup_comp(target_info['pattern'], nodegroups) if decomposed: words = decomposed + words continue engine = ref.get(target_info['engine']) if not engine: # If an unknown engine is called at any time, fail out log.error( 'Unrecognized target engine "%s" for' ' target expression "%s"', target_info['engine'], word, ) return {'minions': [], 'missing': []} engine_args = [target_info['pattern']] if target_info['engine'] in ('G', 'P', 'I', 'J'): engine_args.append(target_info['delimiter'] or ':') engine_args.append(greedy) # ignore missing minions for lists if we exclude them with # a 'not' if 'L' == target_info['engine']: engine_args.append(results and results[-1] == '-') _results = engine(*engine_args) results.append(six.text_type(set(_results['minions']))) missing.extend(_results['missing']) if unmatched and unmatched[-1] == '-': results.append(')') unmatched.pop() else: # The match is not explicitly defined, evaluate as a glob _results = self._check_glob_minions(word, True) results.append(six.text_type(set(_results['minions']))) if unmatched and unmatched[-1] == '-': results.append(')') unmatched.pop() # Add a closing ')' for each item left in unmatched results.extend([')' for item in unmatched]) results = ' '.join(results) log.debug('Evaluating final compound matching expr: %s', results) try: minions = list(eval(results)) # pylint: disable=W0123 return {'minions': minions, 'missing': missing} except Exception: log.error('Invalid compound target: %s', expr) return {'minions': [], 'missing': []} return {'minions': list(minions), 'missing': []}
[ "def", "_check_compound_minions", "(", "self", ",", "expr", ",", "delimiter", ",", "greedy", ",", "pillar_exact", "=", "False", ")", ":", "# pylint: disable=unused-argument", "if", "not", "isinstance", "(", "expr", ",", "six", ".", "string_types", ")", "and", ...
Return the minions found by looking via compound matcher
[ "Return", "the", "minions", "found", "by", "looking", "via", "compound", "matcher" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L466-L620
train
saltstack/salt
salt/utils/minions.py
CkMinions.connected_ids
def connected_ids(self, subset=None, show_ip=False, show_ipv4=None, include_localhost=None): ''' Return a set of all connected minion ids, optionally within a subset ''' if include_localhost is not None: salt.utils.versions.warn_until( 'Sodium', 'The \'include_localhost\' argument is no longer required; any' 'connected localhost minion will always be included.' ) if show_ipv4 is not None: salt.utils.versions.warn_until( 'Sodium', 'The \'show_ipv4\' argument has been renamed to \'show_ip\' as' 'it now also includes IPv6 addresses for IPv6-connected' 'minions.' ) minions = set() if self.opts.get('minion_data_cache', False): search = self.cache.list('minions') if search is None: return minions addrs = salt.utils.network.local_port_tcp(int(self.opts['publish_port'])) if '127.0.0.1' in addrs: # Add in the address of a possible locally-connected minion. addrs.discard('127.0.0.1') addrs.update(set(salt.utils.network.ip_addrs(include_loopback=False))) if '::1' in addrs: # Add in the address of a possible locally-connected minion. addrs.discard('::1') addrs.update(set(salt.utils.network.ip_addrs6(include_loopback=False))) if subset: search = subset for id_ in search: try: mdata = self.cache.fetch('minions/{0}'.format(id_), 'data') except SaltCacheError: # If a SaltCacheError is explicitly raised during the fetch operation, # permission was denied to open the cached data.p file. Continue on as # in the releases <= 2016.3. (An explicit error raise was added in PR # #35388. See issue #36867 for more information. continue if mdata is None: continue grains = mdata.get('grains', {}) for ipv4 in grains.get('ipv4', []): if ipv4 in addrs: if show_ip: minions.add((id_, ipv4)) else: minions.add(id_) break for ipv6 in grains.get('ipv6', []): if ipv6 in addrs: if show_ip: minions.add((id_, ipv6)) else: minions.add(id_) break return minions
python
def connected_ids(self, subset=None, show_ip=False, show_ipv4=None, include_localhost=None): ''' Return a set of all connected minion ids, optionally within a subset ''' if include_localhost is not None: salt.utils.versions.warn_until( 'Sodium', 'The \'include_localhost\' argument is no longer required; any' 'connected localhost minion will always be included.' ) if show_ipv4 is not None: salt.utils.versions.warn_until( 'Sodium', 'The \'show_ipv4\' argument has been renamed to \'show_ip\' as' 'it now also includes IPv6 addresses for IPv6-connected' 'minions.' ) minions = set() if self.opts.get('minion_data_cache', False): search = self.cache.list('minions') if search is None: return minions addrs = salt.utils.network.local_port_tcp(int(self.opts['publish_port'])) if '127.0.0.1' in addrs: # Add in the address of a possible locally-connected minion. addrs.discard('127.0.0.1') addrs.update(set(salt.utils.network.ip_addrs(include_loopback=False))) if '::1' in addrs: # Add in the address of a possible locally-connected minion. addrs.discard('::1') addrs.update(set(salt.utils.network.ip_addrs6(include_loopback=False))) if subset: search = subset for id_ in search: try: mdata = self.cache.fetch('minions/{0}'.format(id_), 'data') except SaltCacheError: # If a SaltCacheError is explicitly raised during the fetch operation, # permission was denied to open the cached data.p file. Continue on as # in the releases <= 2016.3. (An explicit error raise was added in PR # #35388. See issue #36867 for more information. continue if mdata is None: continue grains = mdata.get('grains', {}) for ipv4 in grains.get('ipv4', []): if ipv4 in addrs: if show_ip: minions.add((id_, ipv4)) else: minions.add(id_) break for ipv6 in grains.get('ipv6', []): if ipv6 in addrs: if show_ip: minions.add((id_, ipv6)) else: minions.add(id_) break return minions
[ "def", "connected_ids", "(", "self", ",", "subset", "=", "None", ",", "show_ip", "=", "False", ",", "show_ipv4", "=", "None", ",", "include_localhost", "=", "None", ")", ":", "if", "include_localhost", "is", "not", "None", ":", "salt", ".", "utils", ".",...
Return a set of all connected minion ids, optionally within a subset
[ "Return", "a", "set", "of", "all", "connected", "minion", "ids", "optionally", "within", "a", "subset" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L622-L681
train
saltstack/salt
salt/utils/minions.py
CkMinions._all_minions
def _all_minions(self, expr=None): ''' Return a list of all minions that have auth'd ''' mlist = [] for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))): if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_)): mlist.append(fn_) return {'minions': mlist, 'missing': []}
python
def _all_minions(self, expr=None): ''' Return a list of all minions that have auth'd ''' mlist = [] for fn_ in salt.utils.data.sorted_ignorecase(os.listdir(os.path.join(self.opts['pki_dir'], self.acc))): if not fn_.startswith('.') and os.path.isfile(os.path.join(self.opts['pki_dir'], self.acc, fn_)): mlist.append(fn_) return {'minions': mlist, 'missing': []}
[ "def", "_all_minions", "(", "self", ",", "expr", "=", "None", ")", ":", "mlist", "=", "[", "]", "for", "fn_", "in", "salt", ".", "utils", ".", "data", ".", "sorted_ignorecase", "(", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", ...
Return a list of all minions that have auth'd
[ "Return", "a", "list", "of", "all", "minions", "that", "have", "auth", "d" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L683-L691
train
saltstack/salt
salt/utils/minions.py
CkMinions.check_minions
def check_minions(self, expr, tgt_type='glob', delimiter=DEFAULT_TARGET_DELIM, greedy=True): ''' Check the passed regex against the available minions' public keys stored for authentication. This should return a set of ids which match the regex, this will then be used to parse the returns to make sure everyone has checked back in. ''' try: if expr is None: expr = '' check_func = getattr(self, '_check_{0}_minions'.format(tgt_type), None) if tgt_type in ('grain', 'grain_pcre', 'pillar', 'pillar_pcre', 'pillar_exact', 'compound', 'compound_pillar_exact'): _res = check_func(expr, delimiter, greedy) else: _res = check_func(expr, greedy) _res['ssh_minions'] = False if self.opts.get('enable_ssh_minions', False) is True and isinstance('tgt', six.string_types): roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat')) ssh_minions = roster.targets(expr, tgt_type) if ssh_minions: _res['minions'].extend(ssh_minions) _res['ssh_minions'] = True except Exception: log.exception( 'Failed matching available minions with %s pattern: %s', tgt_type, expr) _res = {'minions': [], 'missing': []} return _res
python
def check_minions(self, expr, tgt_type='glob', delimiter=DEFAULT_TARGET_DELIM, greedy=True): ''' Check the passed regex against the available minions' public keys stored for authentication. This should return a set of ids which match the regex, this will then be used to parse the returns to make sure everyone has checked back in. ''' try: if expr is None: expr = '' check_func = getattr(self, '_check_{0}_minions'.format(tgt_type), None) if tgt_type in ('grain', 'grain_pcre', 'pillar', 'pillar_pcre', 'pillar_exact', 'compound', 'compound_pillar_exact'): _res = check_func(expr, delimiter, greedy) else: _res = check_func(expr, greedy) _res['ssh_minions'] = False if self.opts.get('enable_ssh_minions', False) is True and isinstance('tgt', six.string_types): roster = salt.roster.Roster(self.opts, self.opts.get('roster', 'flat')) ssh_minions = roster.targets(expr, tgt_type) if ssh_minions: _res['minions'].extend(ssh_minions) _res['ssh_minions'] = True except Exception: log.exception( 'Failed matching available minions with %s pattern: %s', tgt_type, expr) _res = {'minions': [], 'missing': []} return _res
[ "def", "check_minions", "(", "self", ",", "expr", ",", "tgt_type", "=", "'glob'", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "greedy", "=", "True", ")", ":", "try", ":", "if", "expr", "is", "None", ":", "expr", "=", "''", "check_func", "=", "g...
Check the passed regex against the available minions' public keys stored for authentication. This should return a set of ids which match the regex, this will then be used to parse the returns to make sure everyone has checked back in.
[ "Check", "the", "passed", "regex", "against", "the", "available", "minions", "public", "keys", "stored", "for", "authentication", ".", "This", "should", "return", "a", "set", "of", "ids", "which", "match", "the", "regex", "this", "will", "then", "be", "used"...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L693-L731
train
saltstack/salt
salt/utils/minions.py
CkMinions.validate_tgt
def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None): ''' Return a Bool. This function returns if the expression sent in is within the scope of the valid expression ''' v_minions = set(self.check_minions(valid, 'compound').get('minions', [])) if minions is None: _res = self.check_minions(expr, tgt_type) minions = set(_res['minions']) else: minions = set(minions) d_bool = not bool(minions.difference(v_minions)) if len(v_minions) == len(minions) and d_bool: return True return d_bool
python
def validate_tgt(self, valid, expr, tgt_type, minions=None, expr_form=None): ''' Return a Bool. This function returns if the expression sent in is within the scope of the valid expression ''' v_minions = set(self.check_minions(valid, 'compound').get('minions', [])) if minions is None: _res = self.check_minions(expr, tgt_type) minions = set(_res['minions']) else: minions = set(minions) d_bool = not bool(minions.difference(v_minions)) if len(v_minions) == len(minions) and d_bool: return True return d_bool
[ "def", "validate_tgt", "(", "self", ",", "valid", ",", "expr", ",", "tgt_type", ",", "minions", "=", "None", ",", "expr_form", "=", "None", ")", ":", "v_minions", "=", "set", "(", "self", ".", "check_minions", "(", "valid", ",", "'compound'", ")", ".",...
Return a Bool. This function returns if the expression sent in is within the scope of the valid expression
[ "Return", "a", "Bool", ".", "This", "function", "returns", "if", "the", "expression", "sent", "in", "is", "within", "the", "scope", "of", "the", "valid", "expression" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L733-L748
train
saltstack/salt
salt/utils/minions.py
CkMinions.match_check
def match_check(self, regex, fun): ''' Validate a single regex to function comparison, the function argument can be a list of functions. It is all or nothing for a list of functions ''' vals = [] if isinstance(fun, six.string_types): fun = [fun] for func in fun: try: if re.match(regex, func): vals.append(True) else: vals.append(False) except Exception: log.error('Invalid regular expression: %s', regex) return vals and all(vals)
python
def match_check(self, regex, fun): ''' Validate a single regex to function comparison, the function argument can be a list of functions. It is all or nothing for a list of functions ''' vals = [] if isinstance(fun, six.string_types): fun = [fun] for func in fun: try: if re.match(regex, func): vals.append(True) else: vals.append(False) except Exception: log.error('Invalid regular expression: %s', regex) return vals and all(vals)
[ "def", "match_check", "(", "self", ",", "regex", ",", "fun", ")", ":", "vals", "=", "[", "]", "if", "isinstance", "(", "fun", ",", "six", ".", "string_types", ")", ":", "fun", "=", "[", "fun", "]", "for", "func", "in", "fun", ":", "try", ":", "...
Validate a single regex to function comparison, the function argument can be a list of functions. It is all or nothing for a list of functions
[ "Validate", "a", "single", "regex", "to", "function", "comparison", "the", "function", "argument", "can", "be", "a", "list", "of", "functions", ".", "It", "is", "all", "or", "nothing", "for", "a", "list", "of", "functions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L750-L767
train
saltstack/salt
salt/utils/minions.py
CkMinions.any_auth
def any_auth(self, form, auth_list, fun, arg, tgt=None, tgt_type='glob'): ''' Read in the form and determine which auth check routine to execute ''' # This function is only called from salt.auth.Authorize(), which is also # deprecated and will be removed in Neon. salt.utils.versions.warn_until( 'Neon', 'The \'any_auth\' function has been deprecated. Support for this ' 'function will be removed in Salt {version}.' ) if form == 'publish': return self.auth_check( auth_list, fun, arg, tgt, tgt_type) return self.spec_check( auth_list, fun, arg, form)
python
def any_auth(self, form, auth_list, fun, arg, tgt=None, tgt_type='glob'): ''' Read in the form and determine which auth check routine to execute ''' # This function is only called from salt.auth.Authorize(), which is also # deprecated and will be removed in Neon. salt.utils.versions.warn_until( 'Neon', 'The \'any_auth\' function has been deprecated. Support for this ' 'function will be removed in Salt {version}.' ) if form == 'publish': return self.auth_check( auth_list, fun, arg, tgt, tgt_type) return self.spec_check( auth_list, fun, arg, form)
[ "def", "any_auth", "(", "self", ",", "form", ",", "auth_list", ",", "fun", ",", "arg", ",", "tgt", "=", "None", ",", "tgt_type", "=", "'glob'", ")", ":", "# This function is only called from salt.auth.Authorize(), which is also", "# deprecated and will be removed in Neo...
Read in the form and determine which auth check routine to execute
[ "Read", "in", "the", "form", "and", "determine", "which", "auth", "check", "routine", "to", "execute" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L769-L791
train
saltstack/salt
salt/utils/minions.py
CkMinions.auth_check
def auth_check(self, auth_list, funs, args, tgt, tgt_type='glob', groups=None, publish_validate=False, minions=None, whitelist=None): ''' Returns a bool which defines if the requested function is authorized. Used to evaluate the standard structure under external master authentication interfaces, like eauth, peer, peer_run, etc. ''' if self.opts.get('auth.enable_expanded_auth_matching', False): return self.auth_check_expanded(auth_list, funs, args, tgt, tgt_type, groups, publish_validate) if publish_validate: v_tgt_type = tgt_type if tgt_type.lower() in ('pillar', 'pillar_pcre'): v_tgt_type = 'pillar_exact' elif tgt_type.lower() == 'compound': v_tgt_type = 'compound_pillar_exact' _res = self.check_minions(tgt, v_tgt_type) v_minions = set(_res['minions']) _res = self.check_minions(tgt, tgt_type) minions = set(_res['minions']) mismatch = bool(minions.difference(v_minions)) # If the non-exact match gets more minions than the exact match # then pillar globbing or PCRE is being used, and we have a # problem if mismatch: return False # compound commands will come in a list so treat everything as a list if not isinstance(funs, list): funs = [funs] args = [args] try: for num, fun in enumerate(funs): if whitelist and fun in whitelist: return True for ind in auth_list: if isinstance(ind, six.string_types): # Allowed for all minions if self.match_check(ind, fun): return True elif isinstance(ind, dict): if len(ind) != 1: # Invalid argument continue valid = next(six.iterkeys(ind)) # Check if minions are allowed if self.validate_tgt( valid, tgt, tgt_type, minions=minions): # Minions are allowed, verify function in allowed list fun_args = args[num] fun_kwargs = fun_args[-1] if fun_args else None if isinstance(fun_kwargs, dict) and '__kwarg__' in fun_kwargs: fun_args = list(fun_args) # copy on modify del fun_args[-1] else: fun_kwargs = None if self.__fun_check(ind[valid], fun, fun_args, fun_kwargs): return True except TypeError: return False return False
python
def auth_check(self, auth_list, funs, args, tgt, tgt_type='glob', groups=None, publish_validate=False, minions=None, whitelist=None): ''' Returns a bool which defines if the requested function is authorized. Used to evaluate the standard structure under external master authentication interfaces, like eauth, peer, peer_run, etc. ''' if self.opts.get('auth.enable_expanded_auth_matching', False): return self.auth_check_expanded(auth_list, funs, args, tgt, tgt_type, groups, publish_validate) if publish_validate: v_tgt_type = tgt_type if tgt_type.lower() in ('pillar', 'pillar_pcre'): v_tgt_type = 'pillar_exact' elif tgt_type.lower() == 'compound': v_tgt_type = 'compound_pillar_exact' _res = self.check_minions(tgt, v_tgt_type) v_minions = set(_res['minions']) _res = self.check_minions(tgt, tgt_type) minions = set(_res['minions']) mismatch = bool(minions.difference(v_minions)) # If the non-exact match gets more minions than the exact match # then pillar globbing or PCRE is being used, and we have a # problem if mismatch: return False # compound commands will come in a list so treat everything as a list if not isinstance(funs, list): funs = [funs] args = [args] try: for num, fun in enumerate(funs): if whitelist and fun in whitelist: return True for ind in auth_list: if isinstance(ind, six.string_types): # Allowed for all minions if self.match_check(ind, fun): return True elif isinstance(ind, dict): if len(ind) != 1: # Invalid argument continue valid = next(six.iterkeys(ind)) # Check if minions are allowed if self.validate_tgt( valid, tgt, tgt_type, minions=minions): # Minions are allowed, verify function in allowed list fun_args = args[num] fun_kwargs = fun_args[-1] if fun_args else None if isinstance(fun_kwargs, dict) and '__kwarg__' in fun_kwargs: fun_args = list(fun_args) # copy on modify del fun_args[-1] else: fun_kwargs = None if self.__fun_check(ind[valid], fun, fun_args, fun_kwargs): return True except TypeError: return False return False
[ "def", "auth_check", "(", "self", ",", "auth_list", ",", "funs", ",", "args", ",", "tgt", ",", "tgt_type", "=", "'glob'", ",", "groups", "=", "None", ",", "publish_validate", "=", "False", ",", "minions", "=", "None", ",", "whitelist", "=", "None", ")"...
Returns a bool which defines if the requested function is authorized. Used to evaluate the standard structure under external master authentication interfaces, like eauth, peer, peer_run, etc.
[ "Returns", "a", "bool", "which", "defines", "if", "the", "requested", "function", "is", "authorized", ".", "Used", "to", "evaluate", "the", "standard", "structure", "under", "external", "master", "authentication", "interfaces", "like", "eauth", "peer", "peer_run",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L908-L979
train
saltstack/salt
salt/utils/minions.py
CkMinions.fill_auth_list_from_groups
def fill_auth_list_from_groups(self, auth_provider, user_groups, auth_list): ''' Returns a list of authorisation matchers that a user is eligible for. This list is a combination of the provided personal matchers plus the matchers of any group the user is in. ''' group_names = [item for item in auth_provider if item.endswith('%')] if group_names: for group_name in group_names: if group_name.rstrip("%") in user_groups: for matcher in auth_provider[group_name]: auth_list.append(matcher) return auth_list
python
def fill_auth_list_from_groups(self, auth_provider, user_groups, auth_list): ''' Returns a list of authorisation matchers that a user is eligible for. This list is a combination of the provided personal matchers plus the matchers of any group the user is in. ''' group_names = [item for item in auth_provider if item.endswith('%')] if group_names: for group_name in group_names: if group_name.rstrip("%") in user_groups: for matcher in auth_provider[group_name]: auth_list.append(matcher) return auth_list
[ "def", "fill_auth_list_from_groups", "(", "self", ",", "auth_provider", ",", "user_groups", ",", "auth_list", ")", ":", "group_names", "=", "[", "item", "for", "item", "in", "auth_provider", "if", "item", ".", "endswith", "(", "'%'", ")", "]", "if", "group_n...
Returns a list of authorisation matchers that a user is eligible for. This list is a combination of the provided personal matchers plus the matchers of any group the user is in.
[ "Returns", "a", "list", "of", "authorisation", "matchers", "that", "a", "user", "is", "eligible", "for", ".", "This", "list", "is", "a", "combination", "of", "the", "provided", "personal", "matchers", "plus", "the", "matchers", "of", "any", "group", "the", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L981-L993
train
saltstack/salt
salt/utils/minions.py
CkMinions.fill_auth_list
def fill_auth_list(self, auth_provider, name, groups, auth_list=None, permissive=None): ''' Returns a list of authorisation matchers that a user is eligible for. This list is a combination of the provided personal matchers plus the matchers of any group the user is in. ''' if auth_list is None: auth_list = [] if permissive is None: permissive = self.opts.get('permissive_acl') name_matched = False for match in auth_provider: if match == '*' and not permissive: continue if match.endswith('%'): if match.rstrip('%') in groups: auth_list.extend(auth_provider[match]) else: if salt.utils.stringutils.expr_match(match, name): name_matched = True auth_list.extend(auth_provider[match]) if not permissive and not name_matched and '*' in auth_provider: auth_list.extend(auth_provider['*']) return auth_list
python
def fill_auth_list(self, auth_provider, name, groups, auth_list=None, permissive=None): ''' Returns a list of authorisation matchers that a user is eligible for. This list is a combination of the provided personal matchers plus the matchers of any group the user is in. ''' if auth_list is None: auth_list = [] if permissive is None: permissive = self.opts.get('permissive_acl') name_matched = False for match in auth_provider: if match == '*' and not permissive: continue if match.endswith('%'): if match.rstrip('%') in groups: auth_list.extend(auth_provider[match]) else: if salt.utils.stringutils.expr_match(match, name): name_matched = True auth_list.extend(auth_provider[match]) if not permissive and not name_matched and '*' in auth_provider: auth_list.extend(auth_provider['*']) return auth_list
[ "def", "fill_auth_list", "(", "self", ",", "auth_provider", ",", "name", ",", "groups", ",", "auth_list", "=", "None", ",", "permissive", "=", "None", ")", ":", "if", "auth_list", "is", "None", ":", "auth_list", "=", "[", "]", "if", "permissive", "is", ...
Returns a list of authorisation matchers that a user is eligible for. This list is a combination of the provided personal matchers plus the matchers of any group the user is in.
[ "Returns", "a", "list", "of", "authorisation", "matchers", "that", "a", "user", "is", "eligible", "for", ".", "This", "list", "is", "a", "combination", "of", "the", "provided", "personal", "matchers", "plus", "the", "matchers", "of", "any", "group", "the", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L995-L1018
train
saltstack/salt
salt/utils/minions.py
CkMinions.wheel_check
def wheel_check(self, auth_list, fun, args): ''' Check special API permissions ''' return self.spec_check(auth_list, fun, args, 'wheel')
python
def wheel_check(self, auth_list, fun, args): ''' Check special API permissions ''' return self.spec_check(auth_list, fun, args, 'wheel')
[ "def", "wheel_check", "(", "self", ",", "auth_list", ",", "fun", ",", "args", ")", ":", "return", "self", ".", "spec_check", "(", "auth_list", ",", "fun", ",", "args", ",", "'wheel'", ")" ]
Check special API permissions
[ "Check", "special", "API", "permissions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L1020-L1024
train
saltstack/salt
salt/utils/minions.py
CkMinions.runner_check
def runner_check(self, auth_list, fun, args): ''' Check special API permissions ''' return self.spec_check(auth_list, fun, args, 'runner')
python
def runner_check(self, auth_list, fun, args): ''' Check special API permissions ''' return self.spec_check(auth_list, fun, args, 'runner')
[ "def", "runner_check", "(", "self", ",", "auth_list", ",", "fun", ",", "args", ")", ":", "return", "self", ".", "spec_check", "(", "auth_list", ",", "fun", ",", "args", ",", "'runner'", ")" ]
Check special API permissions
[ "Check", "special", "API", "permissions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L1026-L1030
train
saltstack/salt
salt/utils/minions.py
CkMinions.spec_check
def spec_check(self, auth_list, fun, args, form): ''' Check special API permissions ''' if not auth_list: return False if form != 'cloud': comps = fun.split('.') if len(comps) != 2: # Hint at a syntax error when command is passed improperly, # rather than returning an authentication error of some kind. # See Issue #21969 for more information. return {'error': {'name': 'SaltInvocationError', 'message': 'A command invocation error occurred: Check syntax.'}} mod_name = comps[0] fun_name = comps[1] else: fun_name = mod_name = fun for ind in auth_list: if isinstance(ind, six.string_types): if ind[0] == '@': if ind[1:] == mod_name or ind[1:] == form or ind == '@{0}s'.format(form): return True elif isinstance(ind, dict): if len(ind) != 1: continue valid = next(six.iterkeys(ind)) if valid[0] == '@': if valid[1:] == mod_name: if self.__fun_check(ind[valid], fun_name, args.get('arg'), args.get('kwarg')): return True if valid[1:] == form or valid == '@{0}s'.format(form): if self.__fun_check(ind[valid], fun, args.get('arg'), args.get('kwarg')): return True return False
python
def spec_check(self, auth_list, fun, args, form): ''' Check special API permissions ''' if not auth_list: return False if form != 'cloud': comps = fun.split('.') if len(comps) != 2: # Hint at a syntax error when command is passed improperly, # rather than returning an authentication error of some kind. # See Issue #21969 for more information. return {'error': {'name': 'SaltInvocationError', 'message': 'A command invocation error occurred: Check syntax.'}} mod_name = comps[0] fun_name = comps[1] else: fun_name = mod_name = fun for ind in auth_list: if isinstance(ind, six.string_types): if ind[0] == '@': if ind[1:] == mod_name or ind[1:] == form or ind == '@{0}s'.format(form): return True elif isinstance(ind, dict): if len(ind) != 1: continue valid = next(six.iterkeys(ind)) if valid[0] == '@': if valid[1:] == mod_name: if self.__fun_check(ind[valid], fun_name, args.get('arg'), args.get('kwarg')): return True if valid[1:] == form or valid == '@{0}s'.format(form): if self.__fun_check(ind[valid], fun, args.get('arg'), args.get('kwarg')): return True return False
[ "def", "spec_check", "(", "self", ",", "auth_list", ",", "fun", ",", "args", ",", "form", ")", ":", "if", "not", "auth_list", ":", "return", "False", "if", "form", "!=", "'cloud'", ":", "comps", "=", "fun", ".", "split", "(", "'.'", ")", "if", "len...
Check special API permissions
[ "Check", "special", "API", "permissions" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L1032-L1066
train
saltstack/salt
salt/utils/minions.py
CkMinions.__fun_check
def __fun_check(self, valid, fun, args=None, kwargs=None): ''' Check the given function name (fun) and its arguments (args) against the list of conditions. ''' if not isinstance(valid, list): valid = [valid] for cond in valid: # Function name match if isinstance(cond, six.string_types): if self.match_check(cond, fun): return True # Function and args match elif isinstance(cond, dict): if len(cond) != 1: # Invalid argument continue fname_cond = next(six.iterkeys(cond)) if self.match_check(fname_cond, fun): # check key that is function name match if self.__args_check(cond[fname_cond], args, kwargs): return True return False
python
def __fun_check(self, valid, fun, args=None, kwargs=None): ''' Check the given function name (fun) and its arguments (args) against the list of conditions. ''' if not isinstance(valid, list): valid = [valid] for cond in valid: # Function name match if isinstance(cond, six.string_types): if self.match_check(cond, fun): return True # Function and args match elif isinstance(cond, dict): if len(cond) != 1: # Invalid argument continue fname_cond = next(six.iterkeys(cond)) if self.match_check(fname_cond, fun): # check key that is function name match if self.__args_check(cond[fname_cond], args, kwargs): return True return False
[ "def", "__fun_check", "(", "self", ",", "valid", ",", "fun", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "not", "isinstance", "(", "valid", ",", "list", ")", ":", "valid", "=", "[", "valid", "]", "for", "cond", "in", "va...
Check the given function name (fun) and its arguments (args) against the list of conditions.
[ "Check", "the", "given", "function", "name", "(", "fun", ")", "and", "its", "arguments", "(", "args", ")", "against", "the", "list", "of", "conditions", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L1068-L1088
train
saltstack/salt
salt/utils/minions.py
CkMinions.__args_check
def __args_check(self, valid, args=None, kwargs=None): ''' valid is a dicts: {'args': [...], 'kwargs': {...}} or a list of such dicts. ''' if not isinstance(valid, list): valid = [valid] for cond in valid: if not isinstance(cond, dict): # Invalid argument continue # whitelist args, kwargs cond_args = cond.get('args', []) good = True for i, cond_arg in enumerate(cond_args): if args is None or len(args) <= i: good = False break if cond_arg is None: # None == '.*' i.e. allow any continue if not self.match_check(cond_arg, six.text_type(args[i])): good = False break if not good: continue # Check kwargs cond_kwargs = cond.get('kwargs', {}) for k, v in six.iteritems(cond_kwargs): if kwargs is None or k not in kwargs: good = False break if v is None: # None == '.*' i.e. allow any continue if not self.match_check(v, six.text_type(kwargs[k])): good = False break if good: return True return False
python
def __args_check(self, valid, args=None, kwargs=None): ''' valid is a dicts: {'args': [...], 'kwargs': {...}} or a list of such dicts. ''' if not isinstance(valid, list): valid = [valid] for cond in valid: if not isinstance(cond, dict): # Invalid argument continue # whitelist args, kwargs cond_args = cond.get('args', []) good = True for i, cond_arg in enumerate(cond_args): if args is None or len(args) <= i: good = False break if cond_arg is None: # None == '.*' i.e. allow any continue if not self.match_check(cond_arg, six.text_type(args[i])): good = False break if not good: continue # Check kwargs cond_kwargs = cond.get('kwargs', {}) for k, v in six.iteritems(cond_kwargs): if kwargs is None or k not in kwargs: good = False break if v is None: # None == '.*' i.e. allow any continue if not self.match_check(v, six.text_type(kwargs[k])): good = False break if good: return True return False
[ "def", "__args_check", "(", "self", ",", "valid", ",", "args", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "not", "isinstance", "(", "valid", ",", "list", ")", ":", "valid", "=", "[", "valid", "]", "for", "cond", "in", "valid", ":", ...
valid is a dicts: {'args': [...], 'kwargs': {...}} or a list of such dicts.
[ "valid", "is", "a", "dicts", ":", "{", "args", ":", "[", "...", "]", "kwargs", ":", "{", "...", "}}", "or", "a", "list", "of", "such", "dicts", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/minions.py#L1090-L1127
train
saltstack/salt
salt/cloud/clouds/clc.py
list_nodes_full
def list_nodes_full(call=None, for_output=True): ''' Return a list of the VMs that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) servers_raw = clc.v1.Server.GetServers(location=None) servers_raw = salt.utils.json.dumps(servers_raw) servers = salt.utils.json.loads(servers_raw) return servers
python
def list_nodes_full(call=None, for_output=True): ''' Return a list of the VMs that are on the provider ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) servers_raw = clc.v1.Server.GetServers(location=None) servers_raw = salt.utils.json.dumps(servers_raw) servers = salt.utils.json.loads(servers_raw) return servers
[ "def", "list_nodes_full", "(", "call", "=", "None", ",", "for_output", "=", "True", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes_full function must be called with -f or --function.'", ")", "creds", "=", "get_cred...
Return a list of the VMs that are on the provider
[ "Return", "a", "list", "of", "the", "VMs", "that", "are", "on", "the", "provider" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/clc.py#L150-L163
train
saltstack/salt
salt/cloud/clouds/clc.py
get_monthly_estimate
def get_monthly_estimate(call=None, for_output=True): ''' Return a list of the VMs that are on the provider ''' creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) try: billing_raw = clc.v1.Billing.GetAccountSummary(alias=creds["accountalias"]) billing_raw = salt.utils.json.dumps(billing_raw) billing = salt.utils.json.loads(billing_raw) billing = round(billing["MonthlyEstimate"], 2) return {"Monthly Estimate": billing} except RuntimeError: return {"Monthly Estimate": 0}
python
def get_monthly_estimate(call=None, for_output=True): ''' Return a list of the VMs that are on the provider ''' creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) try: billing_raw = clc.v1.Billing.GetAccountSummary(alias=creds["accountalias"]) billing_raw = salt.utils.json.dumps(billing_raw) billing = salt.utils.json.loads(billing_raw) billing = round(billing["MonthlyEstimate"], 2) return {"Monthly Estimate": billing} except RuntimeError: return {"Monthly Estimate": 0}
[ "def", "get_monthly_estimate", "(", "call", "=", "None", ",", "for_output", "=", "True", ")", ":", "creds", "=", "get_creds", "(", ")", "clc", ".", "v1", ".", "SetCredentials", "(", "creds", "[", "\"token\"", "]", ",", "creds", "[", "\"token_pass\"", "]"...
Return a list of the VMs that are on the provider
[ "Return", "a", "list", "of", "the", "VMs", "that", "are", "on", "the", "provider" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/clc.py#L173-L190
train
saltstack/salt
salt/cloud/clouds/clc.py
get_server_alerts
def get_server_alerts(call=None, for_output=True, **kwargs): ''' Return a list of alerts from CLC as reported by their infra ''' for key, value in kwargs.items(): servername = "" if key == "servername": servername = value creds = get_creds() clc.v2.SetCredentials(creds["user"], creds["password"]) alerts = clc.v2.Server(servername).Alerts() return alerts
python
def get_server_alerts(call=None, for_output=True, **kwargs): ''' Return a list of alerts from CLC as reported by their infra ''' for key, value in kwargs.items(): servername = "" if key == "servername": servername = value creds = get_creds() clc.v2.SetCredentials(creds["user"], creds["password"]) alerts = clc.v2.Server(servername).Alerts() return alerts
[ "def", "get_server_alerts", "(", "call", "=", "None", ",", "for_output", "=", "True", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "servername", "=", "\"\"", "if", "key", "==", "\"servern...
Return a list of alerts from CLC as reported by their infra
[ "Return", "a", "list", "of", "alerts", "from", "CLC", "as", "reported", "by", "their", "infra" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/clc.py#L213-L224
train
saltstack/salt
salt/cloud/clouds/clc.py
get_group_estimate
def get_group_estimate(call=None, for_output=True, **kwargs): ''' Return a list of the VMs that are on the provider usage: "salt-cloud -f get_group_estimate clc group=Dev location=VA1" ''' for key, value in kwargs.items(): group = "" location = "" if key == "group": group = value if key == "location": location = value creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) try: billing_raw = clc.v1.Billing.GetGroupEstimate(group=group, alias=creds["accountalias"], location=location) billing_raw = salt.utils.json.dumps(billing_raw) billing = salt.utils.json.loads(billing_raw) estimate = round(billing["MonthlyEstimate"], 2) month_to_date = round(billing["MonthToDate"], 2) return {"Monthly Estimate": estimate, "Month to Date": month_to_date} except RuntimeError: return 0
python
def get_group_estimate(call=None, for_output=True, **kwargs): ''' Return a list of the VMs that are on the provider usage: "salt-cloud -f get_group_estimate clc group=Dev location=VA1" ''' for key, value in kwargs.items(): group = "" location = "" if key == "group": group = value if key == "location": location = value creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_full function must be called with -f or --function.' ) try: billing_raw = clc.v1.Billing.GetGroupEstimate(group=group, alias=creds["accountalias"], location=location) billing_raw = salt.utils.json.dumps(billing_raw) billing = salt.utils.json.loads(billing_raw) estimate = round(billing["MonthlyEstimate"], 2) month_to_date = round(billing["MonthToDate"], 2) return {"Monthly Estimate": estimate, "Month to Date": month_to_date} except RuntimeError: return 0
[ "def", "get_group_estimate", "(", "call", "=", "None", ",", "for_output", "=", "True", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "group", "=", "\"\"", "location", "=", "\"\"", "if", ...
Return a list of the VMs that are on the provider usage: "salt-cloud -f get_group_estimate clc group=Dev location=VA1"
[ "Return", "a", "list", "of", "the", "VMs", "that", "are", "on", "the", "provider", "usage", ":", "salt", "-", "cloud", "-", "f", "get_group_estimate", "clc", "group", "=", "Dev", "location", "=", "VA1" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/clc.py#L227-L253
train
saltstack/salt
salt/cloud/clouds/clc.py
avail_images
def avail_images(call=None): ''' returns a list of images available to you ''' all_servers = list_nodes_full() templates = {} for server in all_servers: if server["IsTemplate"]: templates.update({"Template Name": server["Name"]}) return templates
python
def avail_images(call=None): ''' returns a list of images available to you ''' all_servers = list_nodes_full() templates = {} for server in all_servers: if server["IsTemplate"]: templates.update({"Template Name": server["Name"]}) return templates
[ "def", "avail_images", "(", "call", "=", "None", ")", ":", "all_servers", "=", "list_nodes_full", "(", ")", "templates", "=", "{", "}", "for", "server", "in", "all_servers", ":", "if", "server", "[", "\"IsTemplate\"", "]", ":", "templates", ".", "update", ...
returns a list of images available to you
[ "returns", "a", "list", "of", "images", "available", "to", "you" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/clc.py#L256-L265
train
saltstack/salt
salt/cloud/clouds/clc.py
avail_locations
def avail_locations(call=None): ''' returns a list of locations available to you ''' creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) locations = clc.v1.Account.GetLocations() return locations
python
def avail_locations(call=None): ''' returns a list of locations available to you ''' creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) locations = clc.v1.Account.GetLocations() return locations
[ "def", "avail_locations", "(", "call", "=", "None", ")", ":", "creds", "=", "get_creds", "(", ")", "clc", ".", "v1", ".", "SetCredentials", "(", "creds", "[", "\"token\"", "]", ",", "creds", "[", "\"token_pass\"", "]", ")", "locations", "=", "clc", "."...
returns a list of locations available to you
[ "returns", "a", "list", "of", "locations", "available", "to", "you" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/clc.py#L268-L275
train
saltstack/salt
salt/cloud/clouds/clc.py
get_build_status
def get_build_status(req_id, nodename): ''' get the build status from CLC to make sure we dont return to early ''' counter = 0 req_id = six.text_type(req_id) while counter < 10: queue = clc.v1.Blueprint.GetStatus(request_id=(req_id)) if queue["PercentComplete"] == 100: server_name = queue["Servers"][0] creds = get_creds() clc.v2.SetCredentials(creds["user"], creds["password"]) ip_addresses = clc.v2.Server(server_name).ip_addresses internal_ip_address = ip_addresses[0]["internal"] return internal_ip_address else: counter = counter + 1 log.info('Creating Cloud VM %s Time out in %s minutes', nodename, six.text_type(10 - counter)) time.sleep(60)
python
def get_build_status(req_id, nodename): ''' get the build status from CLC to make sure we dont return to early ''' counter = 0 req_id = six.text_type(req_id) while counter < 10: queue = clc.v1.Blueprint.GetStatus(request_id=(req_id)) if queue["PercentComplete"] == 100: server_name = queue["Servers"][0] creds = get_creds() clc.v2.SetCredentials(creds["user"], creds["password"]) ip_addresses = clc.v2.Server(server_name).ip_addresses internal_ip_address = ip_addresses[0]["internal"] return internal_ip_address else: counter = counter + 1 log.info('Creating Cloud VM %s Time out in %s minutes', nodename, six.text_type(10 - counter)) time.sleep(60)
[ "def", "get_build_status", "(", "req_id", ",", "nodename", ")", ":", "counter", "=", "0", "req_id", "=", "six", ".", "text_type", "(", "req_id", ")", "while", "counter", "<", "10", ":", "queue", "=", "clc", ".", "v1", ".", "Blueprint", ".", "GetStatus"...
get the build status from CLC to make sure we dont return to early
[ "get", "the", "build", "status", "from", "CLC", "to", "make", "sure", "we", "dont", "return", "to", "early" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/clc.py#L285-L304
train
saltstack/salt
salt/cloud/clouds/clc.py
create
def create(vm_): ''' get the system build going ''' creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) cloud_profile = config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('token',) ) group = config.get_cloud_config_value( 'group', vm_, __opts__, search_global=False, default=None, ) name = vm_['name'] description = config.get_cloud_config_value( 'description', vm_, __opts__, search_global=False, default=None, ) ram = config.get_cloud_config_value( 'ram', vm_, __opts__, search_global=False, default=None, ) backup_level = config.get_cloud_config_value( 'backup_level', vm_, __opts__, search_global=False, default=None, ) template = config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False, default=None, ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False, default=None, ) cpu = config.get_cloud_config_value( 'cpu', vm_, __opts__, search_global=False, default=None, ) network = config.get_cloud_config_value( 'network', vm_, __opts__, search_global=False, default=None, ) location = config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False, default=None, ) if len(name) > 6: name = name[0:6] if len(password) < 9: password = '' clc_return = clc.v1.Server.Create(alias=None, location=(location), name=(name), template=(template), cpu=(cpu), ram=(ram), backup_level=(backup_level), group=(group), network=(network), description=(description), password=(password)) req_id = clc_return["RequestID"] vm_['ssh_host'] = get_build_status(req_id, name) __utils__['cloud.fire_event']( 'event', 'waiting for ssh', 'salt/cloud/{0}/waiting_for_ssh'.format(name), sock_dir=__opts__['sock_dir'], args={'ip_address': vm_['ssh_host']}, transport=__opts__['transport'] ) # Bootstrap! ret = __utils__['cloud.bootstrap'](vm_, __opts__) return_message = {"Server Name": name, "IP Address": vm_['ssh_host']} ret.update(return_message) return return_message
python
def create(vm_): ''' get the system build going ''' creds = get_creds() clc.v1.SetCredentials(creds["token"], creds["token_pass"]) cloud_profile = config.is_provider_configured( __opts__, __active_provider_name__ or __virtualname__, ('token',) ) group = config.get_cloud_config_value( 'group', vm_, __opts__, search_global=False, default=None, ) name = vm_['name'] description = config.get_cloud_config_value( 'description', vm_, __opts__, search_global=False, default=None, ) ram = config.get_cloud_config_value( 'ram', vm_, __opts__, search_global=False, default=None, ) backup_level = config.get_cloud_config_value( 'backup_level', vm_, __opts__, search_global=False, default=None, ) template = config.get_cloud_config_value( 'template', vm_, __opts__, search_global=False, default=None, ) password = config.get_cloud_config_value( 'password', vm_, __opts__, search_global=False, default=None, ) cpu = config.get_cloud_config_value( 'cpu', vm_, __opts__, search_global=False, default=None, ) network = config.get_cloud_config_value( 'network', vm_, __opts__, search_global=False, default=None, ) location = config.get_cloud_config_value( 'location', vm_, __opts__, search_global=False, default=None, ) if len(name) > 6: name = name[0:6] if len(password) < 9: password = '' clc_return = clc.v1.Server.Create(alias=None, location=(location), name=(name), template=(template), cpu=(cpu), ram=(ram), backup_level=(backup_level), group=(group), network=(network), description=(description), password=(password)) req_id = clc_return["RequestID"] vm_['ssh_host'] = get_build_status(req_id, name) __utils__['cloud.fire_event']( 'event', 'waiting for ssh', 'salt/cloud/{0}/waiting_for_ssh'.format(name), sock_dir=__opts__['sock_dir'], args={'ip_address': vm_['ssh_host']}, transport=__opts__['transport'] ) # Bootstrap! ret = __utils__['cloud.bootstrap'](vm_, __opts__) return_message = {"Server Name": name, "IP Address": vm_['ssh_host']} ret.update(return_message) return return_message
[ "def", "create", "(", "vm_", ")", ":", "creds", "=", "get_creds", "(", ")", "clc", ".", "v1", ".", "SetCredentials", "(", "creds", "[", "\"token\"", "]", ",", "creds", "[", "\"token_pass\"", "]", ")", "cloud_profile", "=", "config", ".", "is_provider_con...
get the system build going
[ "get", "the", "system", "build", "going" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/clc.py#L307-L366
train
saltstack/salt
salt/states/lvs_service.py
present
def present(name, protocol=None, service_address=None, scheduler='wlc', ): ''' Ensure that the named service is present. name The LVS service name protocol The service protocol service_address The LVS service address scheduler Algorithm for allocating TCP connections and UDP datagrams to real servers. .. code-block:: yaml lvstest: lvs_service.present: - service_address: 1.1.1.1:80 - protocol: tcp - scheduler: rr ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check service service_check = __salt__['lvs.check_service'](protocol=protocol, service_address=service_address) if service_check is True: service_rule_check = __salt__['lvs.check_service'](protocol=protocol, service_address=service_address, scheduler=scheduler) if service_rule_check is True: ret['comment'] = 'LVS Service {0} is present'.format(name) return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'LVS Service {0} is present but some options should update'.format(name) return ret else: service_edit = __salt__['lvs.edit_service'](protocol=protocol, service_address=service_address, scheduler=scheduler) if service_edit is True: ret['comment'] = 'LVS Service {0} has been updated'.format(name) ret['changes'][name] = 'Update' return ret else: ret['result'] = False ret['comment'] = 'LVS Service {0} update failed'.format(name) return ret else: if __opts__['test']: ret['comment'] = 'LVS Service {0} is not present and needs to be created'.format(name) ret['result'] = None return ret else: service_add = __salt__['lvs.add_service'](protocol=protocol, service_address=service_address, scheduler=scheduler) if service_add is True: ret['comment'] = 'LVS Service {0} has been created'.format(name) ret['changes'][name] = 'Present' return ret else: ret['comment'] = 'LVS Service {0} create failed({1})'.format(name, service_add) ret['result'] = False return ret
python
def present(name, protocol=None, service_address=None, scheduler='wlc', ): ''' Ensure that the named service is present. name The LVS service name protocol The service protocol service_address The LVS service address scheduler Algorithm for allocating TCP connections and UDP datagrams to real servers. .. code-block:: yaml lvstest: lvs_service.present: - service_address: 1.1.1.1:80 - protocol: tcp - scheduler: rr ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check service service_check = __salt__['lvs.check_service'](protocol=protocol, service_address=service_address) if service_check is True: service_rule_check = __salt__['lvs.check_service'](protocol=protocol, service_address=service_address, scheduler=scheduler) if service_rule_check is True: ret['comment'] = 'LVS Service {0} is present'.format(name) return ret else: if __opts__['test']: ret['result'] = None ret['comment'] = 'LVS Service {0} is present but some options should update'.format(name) return ret else: service_edit = __salt__['lvs.edit_service'](protocol=protocol, service_address=service_address, scheduler=scheduler) if service_edit is True: ret['comment'] = 'LVS Service {0} has been updated'.format(name) ret['changes'][name] = 'Update' return ret else: ret['result'] = False ret['comment'] = 'LVS Service {0} update failed'.format(name) return ret else: if __opts__['test']: ret['comment'] = 'LVS Service {0} is not present and needs to be created'.format(name) ret['result'] = None return ret else: service_add = __salt__['lvs.add_service'](protocol=protocol, service_address=service_address, scheduler=scheduler) if service_add is True: ret['comment'] = 'LVS Service {0} has been created'.format(name) ret['changes'][name] = 'Present' return ret else: ret['comment'] = 'LVS Service {0} create failed({1})'.format(name, service_add) ret['result'] = False return ret
[ "def", "present", "(", "name", ",", "protocol", "=", "None", ",", "service_address", "=", "None", ",", "scheduler", "=", "'wlc'", ",", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ...
Ensure that the named service is present. name The LVS service name protocol The service protocol service_address The LVS service address scheduler Algorithm for allocating TCP connections and UDP datagrams to real servers. .. code-block:: yaml lvstest: lvs_service.present: - service_address: 1.1.1.1:80 - protocol: tcp - scheduler: rr
[ "Ensure", "that", "the", "named", "service", "is", "present", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lvs_service.py#L18-L94
train
saltstack/salt
salt/states/lvs_service.py
absent
def absent(name, protocol=None, service_address=None): ''' Ensure the LVS service is absent. name The name of the LVS service protocol The service protocol service_address The LVS service address ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if service exists and remove it service_check = __salt__['lvs.check_service'](protocol=protocol, service_address=service_address) if service_check is True: if __opts__['test']: ret['result'] = None ret['comment'] = 'LVS Service {0} is present and needs to be removed'.format(name) return ret service_delete = __salt__['lvs.delete_service'](protocol=protocol, service_address=service_address) if service_delete is True: ret['comment'] = 'LVS Service {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret else: ret['comment'] = 'LVS Service {0} removed failed({1})'.format(name, service_delete) ret['result'] = False return ret else: ret['comment'] = 'LVS Service {0} is not present, so it cannot be removed'.format(name) return ret
python
def absent(name, protocol=None, service_address=None): ''' Ensure the LVS service is absent. name The name of the LVS service protocol The service protocol service_address The LVS service address ''' ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''} #check if service exists and remove it service_check = __salt__['lvs.check_service'](protocol=protocol, service_address=service_address) if service_check is True: if __opts__['test']: ret['result'] = None ret['comment'] = 'LVS Service {0} is present and needs to be removed'.format(name) return ret service_delete = __salt__['lvs.delete_service'](protocol=protocol, service_address=service_address) if service_delete is True: ret['comment'] = 'LVS Service {0} has been removed'.format(name) ret['changes'][name] = 'Absent' return ret else: ret['comment'] = 'LVS Service {0} removed failed({1})'.format(name, service_delete) ret['result'] = False return ret else: ret['comment'] = 'LVS Service {0} is not present, so it cannot be removed'.format(name) return ret
[ "def", "absent", "(", "name", ",", "protocol", "=", "None", ",", "service_address", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "True", ",", "'comment'", ":", "''", "}", "#ch...
Ensure the LVS service is absent. name The name of the LVS service protocol The service protocol service_address The LVS service address
[ "Ensure", "the", "LVS", "service", "is", "absent", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/lvs_service.py#L97-L136
train
saltstack/salt
salt/matchers/glob_match.py
match
def match(tgt, opts=None): ''' Returns true if the passed glob matches the id ''' if not opts: opts = __opts__ if not isinstance(tgt, six.string_types): return False return fnmatch.fnmatch(opts['id'], tgt)
python
def match(tgt, opts=None): ''' Returns true if the passed glob matches the id ''' if not opts: opts = __opts__ if not isinstance(tgt, six.string_types): return False return fnmatch.fnmatch(opts['id'], tgt)
[ "def", "match", "(", "tgt", ",", "opts", "=", "None", ")", ":", "if", "not", "opts", ":", "opts", "=", "__opts__", "if", "not", "isinstance", "(", "tgt", ",", "six", ".", "string_types", ")", ":", "return", "False", "return", "fnmatch", ".", "fnmatch...
Returns true if the passed glob matches the id
[ "Returns", "true", "if", "the", "passed", "glob", "matches", "the", "id" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/matchers/glob_match.py#L11-L20
train
saltstack/salt
salt/modules/openbsd_sysctl.py
show
def show(config_file=False): ''' Return a list of sysctl parameters for this minion CLI Example: .. code-block:: bash salt '*' sysctl.show ''' cmd = 'sysctl' ret = {} out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace') for line in out.splitlines(): if not line or '=' not in line: continue comps = line.split('=', 1) ret[comps[0]] = comps[1] return ret
python
def show(config_file=False): ''' Return a list of sysctl parameters for this minion CLI Example: .. code-block:: bash salt '*' sysctl.show ''' cmd = 'sysctl' ret = {} out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace') for line in out.splitlines(): if not line or '=' not in line: continue comps = line.split('=', 1) ret[comps[0]] = comps[1] return ret
[ "def", "show", "(", "config_file", "=", "False", ")", ":", "cmd", "=", "'sysctl'", "ret", "=", "{", "}", "out", "=", "__salt__", "[", "'cmd.run_stdout'", "]", "(", "cmd", ",", "output_loglevel", "=", "'trace'", ")", "for", "line", "in", "out", ".", "...
Return a list of sysctl parameters for this minion CLI Example: .. code-block:: bash salt '*' sysctl.show
[ "Return", "a", "list", "of", "sysctl", "parameters", "for", "this", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsd_sysctl.py#L30-L48
train
saltstack/salt
salt/modules/openbsd_sysctl.py
assign
def assign(name, value): ''' Assign a single sysctl parameter for this minion CLI Example: .. code-block:: bash salt '*' sysctl.assign net.inet.ip.forwarding 1 ''' ret = {} cmd = 'sysctl {0}="{1}"'.format(name, value) data = __salt__['cmd.run_all'](cmd) # Certain values cannot be set from this console, at the current # securelevel or there are other restrictions that prevent us # from applying the setting rightaway. if re.match(r'^sysctl:.*: Operation not permitted$', data['stderr']) or \ data['retcode'] != 0: raise CommandExecutionError('sysctl failed: {0}'.format( data['stderr'])) new_name, new_value = data['stdout'].split(':', 1) ret[new_name] = new_value.split(' -> ')[-1] return ret
python
def assign(name, value): ''' Assign a single sysctl parameter for this minion CLI Example: .. code-block:: bash salt '*' sysctl.assign net.inet.ip.forwarding 1 ''' ret = {} cmd = 'sysctl {0}="{1}"'.format(name, value) data = __salt__['cmd.run_all'](cmd) # Certain values cannot be set from this console, at the current # securelevel or there are other restrictions that prevent us # from applying the setting rightaway. if re.match(r'^sysctl:.*: Operation not permitted$', data['stderr']) or \ data['retcode'] != 0: raise CommandExecutionError('sysctl failed: {0}'.format( data['stderr'])) new_name, new_value = data['stdout'].split(':', 1) ret[new_name] = new_value.split(' -> ')[-1] return ret
[ "def", "assign", "(", "name", ",", "value", ")", ":", "ret", "=", "{", "}", "cmd", "=", "'sysctl {0}=\"{1}\"'", ".", "format", "(", "name", ",", "value", ")", "data", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ")", "# Certain values cannot b...
Assign a single sysctl parameter for this minion CLI Example: .. code-block:: bash salt '*' sysctl.assign net.inet.ip.forwarding 1
[ "Assign", "a", "single", "sysctl", "parameter", "for", "this", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/openbsd_sysctl.py#L66-L89
train
saltstack/salt
salt/runners/asam.py
_get_asam_configuration
def _get_asam_configuration(driver_url=''): ''' Return the configuration read from the master configuration file or directory ''' asam_config = __opts__['asam'] if 'asam' in __opts__ else None if asam_config: try: for asam_server, service_config in six.iteritems(asam_config): username = service_config.get('username', None) password = service_config.get('password', None) protocol = service_config.get('protocol', 'https') port = service_config.get('port', 3451) if not username or not password: log.error( 'Username or Password has not been specified in the ' 'master configuration for %s', asam_server ) return False ret = { 'platform_edit_url': "{0}://{1}:{2}/config/PlatformEdit.html".format(protocol, asam_server, port), 'platform_config_url': "{0}://{1}:{2}/config/PlatformConfig.html".format(protocol, asam_server, port), 'platformset_edit_url': "{0}://{1}:{2}/config/PlatformSetEdit.html".format(protocol, asam_server, port), 'platformset_config_url': "{0}://{1}:{2}/config/PlatformSetConfig.html".format(protocol, asam_server, port), 'username': username, 'password': password } if (not driver_url) or (driver_url == asam_server): return ret except Exception as exc: log.error('Exception encountered: %s', exc) return False if driver_url: log.error( 'Configuration for %s has not been specified in the master ' 'configuration', driver_url ) return False return False
python
def _get_asam_configuration(driver_url=''): ''' Return the configuration read from the master configuration file or directory ''' asam_config = __opts__['asam'] if 'asam' in __opts__ else None if asam_config: try: for asam_server, service_config in six.iteritems(asam_config): username = service_config.get('username', None) password = service_config.get('password', None) protocol = service_config.get('protocol', 'https') port = service_config.get('port', 3451) if not username or not password: log.error( 'Username or Password has not been specified in the ' 'master configuration for %s', asam_server ) return False ret = { 'platform_edit_url': "{0}://{1}:{2}/config/PlatformEdit.html".format(protocol, asam_server, port), 'platform_config_url': "{0}://{1}:{2}/config/PlatformConfig.html".format(protocol, asam_server, port), 'platformset_edit_url': "{0}://{1}:{2}/config/PlatformSetEdit.html".format(protocol, asam_server, port), 'platformset_config_url': "{0}://{1}:{2}/config/PlatformSetConfig.html".format(protocol, asam_server, port), 'username': username, 'password': password } if (not driver_url) or (driver_url == asam_server): return ret except Exception as exc: log.error('Exception encountered: %s', exc) return False if driver_url: log.error( 'Configuration for %s has not been specified in the master ' 'configuration', driver_url ) return False return False
[ "def", "_get_asam_configuration", "(", "driver_url", "=", "''", ")", ":", "asam_config", "=", "__opts__", "[", "'asam'", "]", "if", "'asam'", "in", "__opts__", "else", "None", "if", "asam_config", ":", "try", ":", "for", "asam_server", ",", "service_config", ...
Return the configuration read from the master configuration file or directory
[ "Return", "the", "configuration", "read", "from", "the", "master", "configuration", "file", "or", "directory" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/asam.py#L77-L121
train
saltstack/salt
salt/runners/asam.py
remove_platform
def remove_platform(name, server_url): ''' To remove specified ASAM platform from the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.remove_platform my-test-vm prov1.domain.com ''' config = _get_asam_configuration(server_url) if not config: return False url = config['platform_config_url'] data = { 'manual': 'false', } auth = ( config['username'], config['password'] ) try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to look up existing platforms on {0}".format(server_url) log.error('%s:\n%s', err_msg, exc) return {name: err_msg} parser = _parse_html_content(html_content) platformset_name = _get_platformset_name(parser.data, name) if platformset_name: log.debug(platformset_name) data['platformName'] = name data['platformSetName'] = six.text_type(platformset_name) data['postType'] = 'platformRemove' data['Submit'] = 'Yes' try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to delete platform from {1}".format(server_url) log.error('%s:\n%s', err_msg, exc) return {name: err_msg} parser = _parse_html_content(html_content) platformset_name = _get_platformset_name(parser.data, name) if platformset_name: return {name: "Failed to delete platform from {0}".format(server_url)} else: return {name: "Successfully deleted platform from {0}".format(server_url)} else: return {name: "Specified platform name does not exist on {0}".format(server_url)}
python
def remove_platform(name, server_url): ''' To remove specified ASAM platform from the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.remove_platform my-test-vm prov1.domain.com ''' config = _get_asam_configuration(server_url) if not config: return False url = config['platform_config_url'] data = { 'manual': 'false', } auth = ( config['username'], config['password'] ) try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to look up existing platforms on {0}".format(server_url) log.error('%s:\n%s', err_msg, exc) return {name: err_msg} parser = _parse_html_content(html_content) platformset_name = _get_platformset_name(parser.data, name) if platformset_name: log.debug(platformset_name) data['platformName'] = name data['platformSetName'] = six.text_type(platformset_name) data['postType'] = 'platformRemove' data['Submit'] = 'Yes' try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to delete platform from {1}".format(server_url) log.error('%s:\n%s', err_msg, exc) return {name: err_msg} parser = _parse_html_content(html_content) platformset_name = _get_platformset_name(parser.data, name) if platformset_name: return {name: "Failed to delete platform from {0}".format(server_url)} else: return {name: "Successfully deleted platform from {0}".format(server_url)} else: return {name: "Specified platform name does not exist on {0}".format(server_url)}
[ "def", "remove_platform", "(", "name", ",", "server_url", ")", ":", "config", "=", "_get_asam_configuration", "(", "server_url", ")", "if", "not", "config", ":", "return", "False", "url", "=", "config", "[", "'platform_config_url'", "]", "data", "=", "{", "'...
To remove specified ASAM platform from the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.remove_platform my-test-vm prov1.domain.com
[ "To", "remove", "specified", "ASAM", "platform", "from", "the", "Novell", "Fan", "-", "Out", "Driver" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/asam.py#L178-L233
train
saltstack/salt
salt/runners/asam.py
list_platforms
def list_platforms(server_url): ''' To list all ASAM platforms present on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.list_platforms prov1.domain.com ''' config = _get_asam_configuration(server_url) if not config: return False url = config['platform_config_url'] data = { 'manual': 'false', } auth = ( config['username'], config['password'] ) try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to look up existing platforms" log.error('%s:\n%s', err_msg, exc) return {server_url: err_msg} parser = _parse_html_content(html_content) platform_list = _get_platforms(parser.data) if platform_list: return {server_url: platform_list} else: return {server_url: "No existing platforms found"}
python
def list_platforms(server_url): ''' To list all ASAM platforms present on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.list_platforms prov1.domain.com ''' config = _get_asam_configuration(server_url) if not config: return False url = config['platform_config_url'] data = { 'manual': 'false', } auth = ( config['username'], config['password'] ) try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to look up existing platforms" log.error('%s:\n%s', err_msg, exc) return {server_url: err_msg} parser = _parse_html_content(html_content) platform_list = _get_platforms(parser.data) if platform_list: return {server_url: platform_list} else: return {server_url: "No existing platforms found"}
[ "def", "list_platforms", "(", "server_url", ")", ":", "config", "=", "_get_asam_configuration", "(", "server_url", ")", "if", "not", "config", ":", "return", "False", "url", "=", "config", "[", "'platform_config_url'", "]", "data", "=", "{", "'manual'", ":", ...
To list all ASAM platforms present on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.list_platforms prov1.domain.com
[ "To", "list", "all", "ASAM", "platforms", "present", "on", "the", "Novell", "Fan", "-", "Out", "Driver" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/asam.py#L236-L274
train
saltstack/salt
salt/runners/asam.py
list_platform_sets
def list_platform_sets(server_url): ''' To list all ASAM platform sets present on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.list_platform_sets prov1.domain.com ''' config = _get_asam_configuration(server_url) if not config: return False url = config['platformset_config_url'] data = { 'manual': 'false', } auth = ( config['username'], config['password'] ) try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to look up existing platform sets" log.error('%s:\n%s', err_msg, exc) return {server_url: err_msg} parser = _parse_html_content(html_content) platform_set_list = _get_platform_sets(parser.data) if platform_set_list: return {server_url: platform_set_list} else: return {server_url: "No existing platform sets found"}
python
def list_platform_sets(server_url): ''' To list all ASAM platform sets present on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.list_platform_sets prov1.domain.com ''' config = _get_asam_configuration(server_url) if not config: return False url = config['platformset_config_url'] data = { 'manual': 'false', } auth = ( config['username'], config['password'] ) try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to look up existing platform sets" log.error('%s:\n%s', err_msg, exc) return {server_url: err_msg} parser = _parse_html_content(html_content) platform_set_list = _get_platform_sets(parser.data) if platform_set_list: return {server_url: platform_set_list} else: return {server_url: "No existing platform sets found"}
[ "def", "list_platform_sets", "(", "server_url", ")", ":", "config", "=", "_get_asam_configuration", "(", "server_url", ")", "if", "not", "config", ":", "return", "False", "url", "=", "config", "[", "'platformset_config_url'", "]", "data", "=", "{", "'manual'", ...
To list all ASAM platform sets present on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.list_platform_sets prov1.domain.com
[ "To", "list", "all", "ASAM", "platform", "sets", "present", "on", "the", "Novell", "Fan", "-", "Out", "Driver" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/asam.py#L277-L315
train
saltstack/salt
salt/runners/asam.py
add_platform
def add_platform(name, platform_set, server_url): ''' To add an ASAM platform using the specified ASAM platform set on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.add_platform my-test-vm test-platform-set prov1.domain.com ''' config = _get_asam_configuration(server_url) if not config: return False platforms = list_platforms(server_url) if name in platforms[server_url]: return {name: "Specified platform already exists on {0}".format(server_url)} platform_sets = list_platform_sets(server_url) if platform_set not in platform_sets[server_url]: return {name: "Specified platform set does not exist on {0}".format(server_url)} url = config['platform_edit_url'] data = { 'platformName': name, 'platformSetName': platform_set, 'manual': 'false', 'previousURL': '/config/platformAdd.html', 'postType': 'PlatformAdd', 'Submit': 'Apply' } auth = ( config['username'], config['password'] ) try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to add platform on {0}".format(server_url) log.error('%s:\n%s', err_msg, exc) return {name: err_msg} platforms = list_platforms(server_url) if name in platforms[server_url]: return {name: "Successfully added platform on {0}".format(server_url)} else: return {name: "Failed to add platform on {0}".format(server_url)}
python
def add_platform(name, platform_set, server_url): ''' To add an ASAM platform using the specified ASAM platform set on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.add_platform my-test-vm test-platform-set prov1.domain.com ''' config = _get_asam_configuration(server_url) if not config: return False platforms = list_platforms(server_url) if name in platforms[server_url]: return {name: "Specified platform already exists on {0}".format(server_url)} platform_sets = list_platform_sets(server_url) if platform_set not in platform_sets[server_url]: return {name: "Specified platform set does not exist on {0}".format(server_url)} url = config['platform_edit_url'] data = { 'platformName': name, 'platformSetName': platform_set, 'manual': 'false', 'previousURL': '/config/platformAdd.html', 'postType': 'PlatformAdd', 'Submit': 'Apply' } auth = ( config['username'], config['password'] ) try: html_content = _make_post_request(url, data, auth, verify=False) except Exception as exc: err_msg = "Failed to add platform on {0}".format(server_url) log.error('%s:\n%s', err_msg, exc) return {name: err_msg} platforms = list_platforms(server_url) if name in platforms[server_url]: return {name: "Successfully added platform on {0}".format(server_url)} else: return {name: "Failed to add platform on {0}".format(server_url)}
[ "def", "add_platform", "(", "name", ",", "platform_set", ",", "server_url", ")", ":", "config", "=", "_get_asam_configuration", "(", "server_url", ")", "if", "not", "config", ":", "return", "False", "platforms", "=", "list_platforms", "(", "server_url", ")", "...
To add an ASAM platform using the specified ASAM platform set on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.add_platform my-test-vm test-platform-set prov1.domain.com
[ "To", "add", "an", "ASAM", "platform", "using", "the", "specified", "ASAM", "platform", "set", "on", "the", "Novell", "Fan", "-", "Out", "Driver" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/asam.py#L318-L368
train
saltstack/salt
salt/renderers/jinja.py
_split_module_dicts
def _split_module_dicts(): ''' Create a copy of __salt__ dictionary with module.function and module[function] Takes advantage of Jinja's syntactic sugar lookup: .. code-block:: {{ salt.cmd.run('uptime') }} ''' if not isinstance(__salt__, dict): return __salt__ mod_dict = dict(__salt__) for module_func_name, mod_fun in six.iteritems(mod_dict.copy()): mod, fun = module_func_name.split('.', 1) if mod not in mod_dict: # create an empty object that we can add attributes to mod_dict[mod] = lambda: None setattr(mod_dict[mod], fun, mod_fun) return mod_dict
python
def _split_module_dicts(): ''' Create a copy of __salt__ dictionary with module.function and module[function] Takes advantage of Jinja's syntactic sugar lookup: .. code-block:: {{ salt.cmd.run('uptime') }} ''' if not isinstance(__salt__, dict): return __salt__ mod_dict = dict(__salt__) for module_func_name, mod_fun in six.iteritems(mod_dict.copy()): mod, fun = module_func_name.split('.', 1) if mod not in mod_dict: # create an empty object that we can add attributes to mod_dict[mod] = lambda: None setattr(mod_dict[mod], fun, mod_fun) return mod_dict
[ "def", "_split_module_dicts", "(", ")", ":", "if", "not", "isinstance", "(", "__salt__", ",", "dict", ")", ":", "return", "__salt__", "mod_dict", "=", "dict", "(", "__salt__", ")", "for", "module_func_name", ",", "mod_fun", "in", "six", ".", "iteritems", "...
Create a copy of __salt__ dictionary with module.function and module[function] Takes advantage of Jinja's syntactic sugar lookup: .. code-block:: {{ salt.cmd.run('uptime') }}
[ "Create", "a", "copy", "of", "__salt__", "dictionary", "with", "module", ".", "function", "and", "module", "[", "function", "]" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/jinja.py#L23-L42
train
saltstack/salt
salt/renderers/jinja.py
render
def render(template_file, saltenv='base', sls='', argline='', context=None, tmplpath=None, **kws): ''' Render the template_file, passing the functions and grains into the Jinja rendering system. :rtype: string ''' from_str = argline == '-s' if not from_str and argline: raise SaltRenderError( 'Unknown renderer option: {opt}'.format(opt=argline) ) tmp_data = salt.utils.templates.JINJA(template_file, to_str=True, salt=_split_module_dicts(), grains=__grains__, opts=__opts__, pillar=__pillar__, saltenv=saltenv, sls=sls, context=context, tmplpath=tmplpath, proxy=__proxy__, **kws) if not tmp_data.get('result', False): raise SaltRenderError( tmp_data.get('data', 'Unknown render error in jinja renderer') ) if isinstance(tmp_data['data'], bytes): tmp_data['data'] = tmp_data['data'].decode(__salt_system_encoding__) return StringIO(tmp_data['data'])
python
def render(template_file, saltenv='base', sls='', argline='', context=None, tmplpath=None, **kws): ''' Render the template_file, passing the functions and grains into the Jinja rendering system. :rtype: string ''' from_str = argline == '-s' if not from_str and argline: raise SaltRenderError( 'Unknown renderer option: {opt}'.format(opt=argline) ) tmp_data = salt.utils.templates.JINJA(template_file, to_str=True, salt=_split_module_dicts(), grains=__grains__, opts=__opts__, pillar=__pillar__, saltenv=saltenv, sls=sls, context=context, tmplpath=tmplpath, proxy=__proxy__, **kws) if not tmp_data.get('result', False): raise SaltRenderError( tmp_data.get('data', 'Unknown render error in jinja renderer') ) if isinstance(tmp_data['data'], bytes): tmp_data['data'] = tmp_data['data'].decode(__salt_system_encoding__) return StringIO(tmp_data['data'])
[ "def", "render", "(", "template_file", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "argline", "=", "''", ",", "context", "=", "None", ",", "tmplpath", "=", "None", ",", "*", "*", "kws", ")", ":", "from_str", "=", "argline", "==", "'-...
Render the template_file, passing the functions and grains into the Jinja rendering system. :rtype: string
[ "Render", "the", "template_file", "passing", "the", "functions", "and", "grains", "into", "the", "Jinja", "rendering", "system", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/jinja.py#L45-L77
train
saltstack/salt
salt/spm/pkgfiles/local.py
init
def init(**kwargs): ''' Initialize the directories for the files ''' formula_path = __opts__['formula_path'] pillar_path = __opts__['pillar_path'] reactor_path = __opts__['reactor_path'] for dir_ in (formula_path, pillar_path, reactor_path): if not os.path.exists(dir_): os.makedirs(dir_) return { 'formula_path': formula_path, 'pillar_path': pillar_path, 'reactor_path': reactor_path, }
python
def init(**kwargs): ''' Initialize the directories for the files ''' formula_path = __opts__['formula_path'] pillar_path = __opts__['pillar_path'] reactor_path = __opts__['reactor_path'] for dir_ in (formula_path, pillar_path, reactor_path): if not os.path.exists(dir_): os.makedirs(dir_) return { 'formula_path': formula_path, 'pillar_path': pillar_path, 'reactor_path': reactor_path, }
[ "def", "init", "(", "*", "*", "kwargs", ")", ":", "formula_path", "=", "__opts__", "[", "'formula_path'", "]", "pillar_path", "=", "__opts__", "[", "'pillar_path'", "]", "reactor_path", "=", "__opts__", "[", "'reactor_path'", "]", "for", "dir_", "in", "(", ...
Initialize the directories for the files
[ "Initialize", "the", "directories", "for", "the", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgfiles/local.py#L34-L48
train
saltstack/salt
salt/spm/pkgfiles/local.py
check_existing
def check_existing(package, pkg_files, formula_def, conn=None): ''' Check the filesystem for existing files ''' if conn is None: conn = init() node_type = six.text_type(__opts__.get('spm_node_type')) existing_files = [] for member in pkg_files: if member.isdir(): continue tld = formula_def.get('top_level_dir', package) new_name = member.name.replace('{0}/'.format(package), '') if not new_name.startswith(tld): continue if member.name.startswith('{0}/_'.format(package)): if node_type in ('master', 'minion'): # Module files are distributed via extmods directory out_file = os.path.join( salt.syspaths.CACHE_DIR, node_type, 'extmods', new_name.replace('_', ''), ) else: # Module files are distributed via _modules, _states, etc out_file = os.path.join(conn['formula_path'], new_name) elif member.name == '{0}/pillar.example'.format(package): # Pillars are automatically put in the pillar_path new_name = '{0}.sls.orig'.format(package) out_file = os.path.join(conn['pillar_path'], new_name) elif package.endswith('-conf'): # Configuration files go into /etc/salt/ out_file = os.path.join(salt.syspaths.CONFIG_DIR, new_name) elif package.endswith('-reactor'): # Reactor files go into /srv/reactor/ out_file = os.path.join(conn['reactor_path'], member.name) else: out_file = os.path.join(conn['formula_path'], member.name) if os.path.exists(out_file): existing_files.append(out_file) if not __opts__['force']: log.error('%s already exists, not installing', out_file) return existing_files
python
def check_existing(package, pkg_files, formula_def, conn=None): ''' Check the filesystem for existing files ''' if conn is None: conn = init() node_type = six.text_type(__opts__.get('spm_node_type')) existing_files = [] for member in pkg_files: if member.isdir(): continue tld = formula_def.get('top_level_dir', package) new_name = member.name.replace('{0}/'.format(package), '') if not new_name.startswith(tld): continue if member.name.startswith('{0}/_'.format(package)): if node_type in ('master', 'minion'): # Module files are distributed via extmods directory out_file = os.path.join( salt.syspaths.CACHE_DIR, node_type, 'extmods', new_name.replace('_', ''), ) else: # Module files are distributed via _modules, _states, etc out_file = os.path.join(conn['formula_path'], new_name) elif member.name == '{0}/pillar.example'.format(package): # Pillars are automatically put in the pillar_path new_name = '{0}.sls.orig'.format(package) out_file = os.path.join(conn['pillar_path'], new_name) elif package.endswith('-conf'): # Configuration files go into /etc/salt/ out_file = os.path.join(salt.syspaths.CONFIG_DIR, new_name) elif package.endswith('-reactor'): # Reactor files go into /srv/reactor/ out_file = os.path.join(conn['reactor_path'], member.name) else: out_file = os.path.join(conn['formula_path'], member.name) if os.path.exists(out_file): existing_files.append(out_file) if not __opts__['force']: log.error('%s already exists, not installing', out_file) return existing_files
[ "def", "check_existing", "(", "package", ",", "pkg_files", ",", "formula_def", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "init", "(", ")", "node_type", "=", "six", ".", "text_type", "(", "__opts__", ".", "get", ...
Check the filesystem for existing files
[ "Check", "the", "filesystem", "for", "existing", "files" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgfiles/local.py#L51-L100
train
saltstack/salt
salt/spm/pkgfiles/local.py
install_file
def install_file(package, formula_tar, member, formula_def, conn=None): ''' Install a single file to the file system ''' if member.name == package: return False if conn is None: conn = init() node_type = six.text_type(__opts__.get('spm_node_type')) out_path = conn['formula_path'] tld = formula_def.get('top_level_dir', package) new_name = member.name.replace('{0}/'.format(package), '', 1) if not new_name.startswith(tld) and not new_name.startswith('_') and not \ new_name.startswith('pillar.example') and not new_name.startswith('README'): log.debug('%s not in top level directory, not installing', new_name) return False for line in formula_def.get('files', []): tag = '' for ftype in FILE_TYPES: if line.startswith('{0}|'.format(ftype)): tag = line.split('|', 1)[0] line = line.split('|', 1)[1] if tag and new_name == line: if tag in ('c', 'd', 'g', 'l', 'r'): out_path = __opts__['spm_share_dir'] elif tag in ('s', 'm'): pass if member.name.startswith('{0}/_'.format(package)): if node_type in ('master', 'minion'): # Module files are distributed via extmods directory member.name = new_name.name.replace('{0}/_'.format(package), '') out_path = os.path.join( salt.syspaths.CACHE_DIR, node_type, 'extmods', ) else: # Module files are distributed via _modules, _states, etc member.name = new_name.name.replace('{0}/'.format(package), '') elif member.name == '{0}/pillar.example'.format(package): # Pillars are automatically put in the pillar_path member.name = '{0}.sls.orig'.format(package) out_path = conn['pillar_path'] elif package.endswith('-conf'): # Configuration files go into /etc/salt/ member.name = member.name.replace('{0}/'.format(package), '') out_path = salt.syspaths.CONFIG_DIR elif package.endswith('-reactor'): # Reactor files go into /srv/reactor/ out_path = __opts__['reactor_path'] # This ensures that double directories (i.e., apache/apache/) don't # get created comps = member.path.split('/') if len(comps) > 1 and comps[0] == comps[1]: member.path = '/'.join(comps[1:]) log.debug('Installing package file %s to %s', member.name, out_path) formula_tar.extract(member, out_path) return out_path
python
def install_file(package, formula_tar, member, formula_def, conn=None): ''' Install a single file to the file system ''' if member.name == package: return False if conn is None: conn = init() node_type = six.text_type(__opts__.get('spm_node_type')) out_path = conn['formula_path'] tld = formula_def.get('top_level_dir', package) new_name = member.name.replace('{0}/'.format(package), '', 1) if not new_name.startswith(tld) and not new_name.startswith('_') and not \ new_name.startswith('pillar.example') and not new_name.startswith('README'): log.debug('%s not in top level directory, not installing', new_name) return False for line in formula_def.get('files', []): tag = '' for ftype in FILE_TYPES: if line.startswith('{0}|'.format(ftype)): tag = line.split('|', 1)[0] line = line.split('|', 1)[1] if tag and new_name == line: if tag in ('c', 'd', 'g', 'l', 'r'): out_path = __opts__['spm_share_dir'] elif tag in ('s', 'm'): pass if member.name.startswith('{0}/_'.format(package)): if node_type in ('master', 'minion'): # Module files are distributed via extmods directory member.name = new_name.name.replace('{0}/_'.format(package), '') out_path = os.path.join( salt.syspaths.CACHE_DIR, node_type, 'extmods', ) else: # Module files are distributed via _modules, _states, etc member.name = new_name.name.replace('{0}/'.format(package), '') elif member.name == '{0}/pillar.example'.format(package): # Pillars are automatically put in the pillar_path member.name = '{0}.sls.orig'.format(package) out_path = conn['pillar_path'] elif package.endswith('-conf'): # Configuration files go into /etc/salt/ member.name = member.name.replace('{0}/'.format(package), '') out_path = salt.syspaths.CONFIG_DIR elif package.endswith('-reactor'): # Reactor files go into /srv/reactor/ out_path = __opts__['reactor_path'] # This ensures that double directories (i.e., apache/apache/) don't # get created comps = member.path.split('/') if len(comps) > 1 and comps[0] == comps[1]: member.path = '/'.join(comps[1:]) log.debug('Installing package file %s to %s', member.name, out_path) formula_tar.extract(member, out_path) return out_path
[ "def", "install_file", "(", "package", ",", "formula_tar", ",", "member", ",", "formula_def", ",", "conn", "=", "None", ")", ":", "if", "member", ".", "name", "==", "package", ":", "return", "False", "if", "conn", "is", "None", ":", "conn", "=", "init"...
Install a single file to the file system
[ "Install", "a", "single", "file", "to", "the", "file", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgfiles/local.py#L103-L169
train
saltstack/salt
salt/spm/pkgfiles/local.py
remove_file
def remove_file(path, conn=None): ''' Remove a single file from the file system ''' if conn is None: conn = init() log.debug('Removing package file %s', path) os.remove(path)
python
def remove_file(path, conn=None): ''' Remove a single file from the file system ''' if conn is None: conn = init() log.debug('Removing package file %s', path) os.remove(path)
[ "def", "remove_file", "(", "path", ",", "conn", "=", "None", ")", ":", "if", "conn", "is", "None", ":", "conn", "=", "init", "(", ")", "log", ".", "debug", "(", "'Removing package file %s'", ",", "path", ")", "os", ".", "remove", "(", "path", ")" ]
Remove a single file from the file system
[ "Remove", "a", "single", "file", "from", "the", "file", "system" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgfiles/local.py#L172-L180
train
saltstack/salt
salt/spm/pkgfiles/local.py
hash_file
def hash_file(path, hashobj, conn=None): ''' Get the hexdigest hash value of a file ''' if os.path.isdir(path): return '' with salt.utils.files.fopen(path, 'r') as f: hashobj.update(salt.utils.stringutils.to_bytes(f.read())) return hashobj.hexdigest()
python
def hash_file(path, hashobj, conn=None): ''' Get the hexdigest hash value of a file ''' if os.path.isdir(path): return '' with salt.utils.files.fopen(path, 'r') as f: hashobj.update(salt.utils.stringutils.to_bytes(f.read())) return hashobj.hexdigest()
[ "def", "hash_file", "(", "path", ",", "hashobj", ",", "conn", "=", "None", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "''", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "path", ",", "'r'", ...
Get the hexdigest hash value of a file
[ "Get", "the", "hexdigest", "hash", "value", "of", "a", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/spm/pkgfiles/local.py#L183-L192
train
saltstack/salt
salt/states/win_lgpo.py
set_
def set_(name, setting=None, policy_class=None, computer_policy=None, user_policy=None, cumulative_rights_assignments=True, adml_language='en-US'): ''' Ensure the specified policy is set name the name of a single policy to configure setting the configuration setting for the single named policy if this argument is used the computer_policy/user_policy arguments will be ignored policy_class the policy class of the single named policy to configure this can "machine", "user", or "both" computer_policy a dict of policyname: value pairs of a set of computer policies to configure if this argument is used, the name/setting/policy_class arguments will be ignored user_policy a dict of policyname: value pairs of a set of user policies to configure if this argument is used, the name/setting/policy_class arguments will be ignored cumulative_rights_assignments determine if any user right assignment policies specified will be cumulative or explicit adml_language the adml language to use for AMDX policy data/display conversions ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} policy_classes = ['machine', 'computer', 'user', 'both'] if not setting and not computer_policy and not user_policy: msg = 'At least one of the parameters setting, computer_policy, or user_policy' msg = msg + ' must be specified.' ret['result'] = False ret['comment'] = msg return ret if setting and not policy_class: msg = 'A single policy setting was specified but the policy_class was not specified.' ret['result'] = False ret['comment'] = msg return ret if setting and (computer_policy or user_policy): msg = 'The setting and computer_policy/user_policy parameters are mutually exclusive. Please' msg = msg + ' specify either a policy name and setting or a computer_policy and/or user_policy' msg = msg + ' dict' ret['result'] = False ret['comment'] = msg return ret if policy_class and policy_class.lower() not in policy_classes: msg = 'The policy_class parameter must be one of the following: {0}' ret['result'] = False ret['comment'] = msg return ret if not setting: if computer_policy and user_policy: policy_class = 'both' elif computer_policy: policy_class = 'machine' elif user_policy: policy_class = 'user' if computer_policy and not isinstance(computer_policy, dict): msg = 'The computer_policy must be specified as a dict.' ret['result'] = False ret['comment'] = msg return ret if user_policy and not isinstance(user_policy, dict): msg = 'The user_policy must be specified as a dict.' ret['result'] = False ret['comment'] = msg return ret else: user_policy = {} computer_policy = {} if policy_class.lower() == 'both': user_policy[name] = setting computer_policy[name] = setting elif policy_class.lower() == 'user': user_policy[name] = setting elif policy_class.lower() == 'machine' or policy_class.lower() == 'computer': computer_policy[name] = setting pol_data = {} pol_data['user'] = {'output_section': 'User Configuration', 'requested_policy': user_policy, 'policy_lookup': {}} pol_data['machine'] = {'output_section': 'Computer Configuration', 'requested_policy': computer_policy, 'policy_lookup': {}} for p_class, p_data in six.iteritems(pol_data): if p_data['requested_policy']: for policy_name, policy_setting in six.iteritems(p_data['requested_policy']): lookup = __salt__['lgpo.get_policy_info'](policy_name, p_class, adml_language=adml_language) if lookup['policy_found']: pol_data[p_class]['policy_lookup'][policy_name] = lookup else: ret['comment'] = ' '.join([ret['comment'], lookup['message']]) ret['result'] = False if not ret['result']: return ret current_policy = __salt__['lgpo.get'](policy_class=policy_class, adml_language=adml_language, hierarchical_return=False) log.debug('current policy == %s', current_policy) # compare policies policy_changes = [] for policy_section, policy_data in six.iteritems(pol_data): pol_id = None if policy_data and policy_data['output_section'] in current_policy: for policy_name, policy_setting in six.iteritems(policy_data['requested_policy']): currently_set = False # Check Case sensitive first (faster) if policy_name in current_policy[policy_data['output_section']]: currently_set = True pol_id = policy_name # Check case insensitive elif policy_name.lower() in (k.lower() for k in current_policy[policy_data['output_section']]): for p_name in current_policy[policy_data['output_section']]: if policy_name.lower() == p_name.lower(): currently_set = True pol_id = p_name break # Check aliases else: for alias in policy_data['policy_lookup'][policy_name]['policy_aliases']: log.debug('checking alias %s', alias) if alias in current_policy[policy_data['output_section']]: currently_set = True pol_id = alias break if currently_set: # compare log.debug('need to compare %s from ' 'current/requested policy', policy_name) changes = False requested_policy_json = salt.utils.json.dumps(policy_data['requested_policy'][policy_name], sort_keys=True).lower() current_policy_json = salt.utils.json.dumps(current_policy[policy_data['output_section']][pol_id], sort_keys=True).lower() policies_are_equal = False requested_policy_check = salt.utils.json.loads(requested_policy_json) current_policy_check = salt.utils.json.loads(current_policy_json) # Compared dicts, lists, and strings if isinstance(requested_policy_check, six.string_types): policies_are_equal = requested_policy_check == current_policy_check elif isinstance(requested_policy_check, list): policies_are_equal = salt.utils.data.compare_lists( requested_policy_check, current_policy_check ) == {} elif isinstance(requested_policy_check, dict): policies_are_equal = salt.utils.data.compare_dicts( requested_policy_check, current_policy_check ) == {} if not policies_are_equal: additional_policy_comments = [] if policy_data['policy_lookup'][policy_name]['rights_assignment'] and cumulative_rights_assignments: for user in policy_data['requested_policy'][policy_name]: if user not in current_policy[policy_data['output_section']][pol_id]: changes = True else: additional_policy_comments.append('"{0}" is already granted the right'.format(user)) else: changes = True if changes: log.debug('%s current policy != requested policy', policy_name) log.debug( 'we compared %s to %s', requested_policy_json, current_policy_json ) policy_changes.append(policy_name) else: if additional_policy_comments: ret['comment'] = '"{0}" is already set ({1})\n'.format(policy_name, ', '.join(additional_policy_comments)) else: ret['comment'] = '"{0}" is already set\n'.format(policy_name) + ret['comment'] else: log.debug('%s current setting matches ' 'the requested setting', policy_name) ret['comment'] = '"{0}" is already set\n'.format(policy_name) + ret['comment'] else: policy_changes.append(policy_name) log.debug('policy %s is not set, we will configure it', policy_name) if __opts__['test']: if policy_changes: ret['result'] = None ret['comment'] = 'The following policies are set to change:\n{0}'.format( '\n'.join(policy_changes)) else: ret['comment'] = 'All specified policies are properly configured' else: if policy_changes: _ret = __salt__['lgpo.set'](computer_policy=computer_policy, user_policy=user_policy, cumulative_rights_assignments=cumulative_rights_assignments, adml_language=adml_language) if _ret: ret['result'] = _ret ret['changes'] = salt.utils.dictdiffer.deep_diff( current_policy, __salt__['lgpo.get'](policy_class=policy_class, adml_language=adml_language, hierarchical_return=False)) if ret['changes']: ret['comment'] = 'The following policies changed:\n{0}' \ ''.format('\n'.join(policy_changes)) else: ret['comment'] = 'The following policies are in the correct state:\n{0}' \ ''.format('\n'.join(policy_changes)) else: ret['result'] = False ret['comment'] = 'Errors occurred while attempting to configure policies: {0}'.format(_ret) return ret
python
def set_(name, setting=None, policy_class=None, computer_policy=None, user_policy=None, cumulative_rights_assignments=True, adml_language='en-US'): ''' Ensure the specified policy is set name the name of a single policy to configure setting the configuration setting for the single named policy if this argument is used the computer_policy/user_policy arguments will be ignored policy_class the policy class of the single named policy to configure this can "machine", "user", or "both" computer_policy a dict of policyname: value pairs of a set of computer policies to configure if this argument is used, the name/setting/policy_class arguments will be ignored user_policy a dict of policyname: value pairs of a set of user policies to configure if this argument is used, the name/setting/policy_class arguments will be ignored cumulative_rights_assignments determine if any user right assignment policies specified will be cumulative or explicit adml_language the adml language to use for AMDX policy data/display conversions ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} policy_classes = ['machine', 'computer', 'user', 'both'] if not setting and not computer_policy and not user_policy: msg = 'At least one of the parameters setting, computer_policy, or user_policy' msg = msg + ' must be specified.' ret['result'] = False ret['comment'] = msg return ret if setting and not policy_class: msg = 'A single policy setting was specified but the policy_class was not specified.' ret['result'] = False ret['comment'] = msg return ret if setting and (computer_policy or user_policy): msg = 'The setting and computer_policy/user_policy parameters are mutually exclusive. Please' msg = msg + ' specify either a policy name and setting or a computer_policy and/or user_policy' msg = msg + ' dict' ret['result'] = False ret['comment'] = msg return ret if policy_class and policy_class.lower() not in policy_classes: msg = 'The policy_class parameter must be one of the following: {0}' ret['result'] = False ret['comment'] = msg return ret if not setting: if computer_policy and user_policy: policy_class = 'both' elif computer_policy: policy_class = 'machine' elif user_policy: policy_class = 'user' if computer_policy and not isinstance(computer_policy, dict): msg = 'The computer_policy must be specified as a dict.' ret['result'] = False ret['comment'] = msg return ret if user_policy and not isinstance(user_policy, dict): msg = 'The user_policy must be specified as a dict.' ret['result'] = False ret['comment'] = msg return ret else: user_policy = {} computer_policy = {} if policy_class.lower() == 'both': user_policy[name] = setting computer_policy[name] = setting elif policy_class.lower() == 'user': user_policy[name] = setting elif policy_class.lower() == 'machine' or policy_class.lower() == 'computer': computer_policy[name] = setting pol_data = {} pol_data['user'] = {'output_section': 'User Configuration', 'requested_policy': user_policy, 'policy_lookup': {}} pol_data['machine'] = {'output_section': 'Computer Configuration', 'requested_policy': computer_policy, 'policy_lookup': {}} for p_class, p_data in six.iteritems(pol_data): if p_data['requested_policy']: for policy_name, policy_setting in six.iteritems(p_data['requested_policy']): lookup = __salt__['lgpo.get_policy_info'](policy_name, p_class, adml_language=adml_language) if lookup['policy_found']: pol_data[p_class]['policy_lookup'][policy_name] = lookup else: ret['comment'] = ' '.join([ret['comment'], lookup['message']]) ret['result'] = False if not ret['result']: return ret current_policy = __salt__['lgpo.get'](policy_class=policy_class, adml_language=adml_language, hierarchical_return=False) log.debug('current policy == %s', current_policy) # compare policies policy_changes = [] for policy_section, policy_data in six.iteritems(pol_data): pol_id = None if policy_data and policy_data['output_section'] in current_policy: for policy_name, policy_setting in six.iteritems(policy_data['requested_policy']): currently_set = False # Check Case sensitive first (faster) if policy_name in current_policy[policy_data['output_section']]: currently_set = True pol_id = policy_name # Check case insensitive elif policy_name.lower() in (k.lower() for k in current_policy[policy_data['output_section']]): for p_name in current_policy[policy_data['output_section']]: if policy_name.lower() == p_name.lower(): currently_set = True pol_id = p_name break # Check aliases else: for alias in policy_data['policy_lookup'][policy_name]['policy_aliases']: log.debug('checking alias %s', alias) if alias in current_policy[policy_data['output_section']]: currently_set = True pol_id = alias break if currently_set: # compare log.debug('need to compare %s from ' 'current/requested policy', policy_name) changes = False requested_policy_json = salt.utils.json.dumps(policy_data['requested_policy'][policy_name], sort_keys=True).lower() current_policy_json = salt.utils.json.dumps(current_policy[policy_data['output_section']][pol_id], sort_keys=True).lower() policies_are_equal = False requested_policy_check = salt.utils.json.loads(requested_policy_json) current_policy_check = salt.utils.json.loads(current_policy_json) # Compared dicts, lists, and strings if isinstance(requested_policy_check, six.string_types): policies_are_equal = requested_policy_check == current_policy_check elif isinstance(requested_policy_check, list): policies_are_equal = salt.utils.data.compare_lists( requested_policy_check, current_policy_check ) == {} elif isinstance(requested_policy_check, dict): policies_are_equal = salt.utils.data.compare_dicts( requested_policy_check, current_policy_check ) == {} if not policies_are_equal: additional_policy_comments = [] if policy_data['policy_lookup'][policy_name]['rights_assignment'] and cumulative_rights_assignments: for user in policy_data['requested_policy'][policy_name]: if user not in current_policy[policy_data['output_section']][pol_id]: changes = True else: additional_policy_comments.append('"{0}" is already granted the right'.format(user)) else: changes = True if changes: log.debug('%s current policy != requested policy', policy_name) log.debug( 'we compared %s to %s', requested_policy_json, current_policy_json ) policy_changes.append(policy_name) else: if additional_policy_comments: ret['comment'] = '"{0}" is already set ({1})\n'.format(policy_name, ', '.join(additional_policy_comments)) else: ret['comment'] = '"{0}" is already set\n'.format(policy_name) + ret['comment'] else: log.debug('%s current setting matches ' 'the requested setting', policy_name) ret['comment'] = '"{0}" is already set\n'.format(policy_name) + ret['comment'] else: policy_changes.append(policy_name) log.debug('policy %s is not set, we will configure it', policy_name) if __opts__['test']: if policy_changes: ret['result'] = None ret['comment'] = 'The following policies are set to change:\n{0}'.format( '\n'.join(policy_changes)) else: ret['comment'] = 'All specified policies are properly configured' else: if policy_changes: _ret = __salt__['lgpo.set'](computer_policy=computer_policy, user_policy=user_policy, cumulative_rights_assignments=cumulative_rights_assignments, adml_language=adml_language) if _ret: ret['result'] = _ret ret['changes'] = salt.utils.dictdiffer.deep_diff( current_policy, __salt__['lgpo.get'](policy_class=policy_class, adml_language=adml_language, hierarchical_return=False)) if ret['changes']: ret['comment'] = 'The following policies changed:\n{0}' \ ''.format('\n'.join(policy_changes)) else: ret['comment'] = 'The following policies are in the correct state:\n{0}' \ ''.format('\n'.join(policy_changes)) else: ret['result'] = False ret['comment'] = 'Errors occurred while attempting to configure policies: {0}'.format(_ret) return ret
[ "def", "set_", "(", "name", ",", "setting", "=", "None", ",", "policy_class", "=", "None", ",", "computer_policy", "=", "None", ",", "user_policy", "=", "None", ",", "cumulative_rights_assignments", "=", "True", ",", "adml_language", "=", "'en-US'", ")", ":"...
Ensure the specified policy is set name the name of a single policy to configure setting the configuration setting for the single named policy if this argument is used the computer_policy/user_policy arguments will be ignored policy_class the policy class of the single named policy to configure this can "machine", "user", or "both" computer_policy a dict of policyname: value pairs of a set of computer policies to configure if this argument is used, the name/setting/policy_class arguments will be ignored user_policy a dict of policyname: value pairs of a set of user policies to configure if this argument is used, the name/setting/policy_class arguments will be ignored cumulative_rights_assignments determine if any user right assignment policies specified will be cumulative or explicit adml_language the adml language to use for AMDX policy data/display conversions
[ "Ensure", "the", "specified", "policy", "is", "set" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/win_lgpo.py#L130-L361
train
saltstack/salt
salt/utils/value.py
xor
def xor(*variables): ''' XOR definition for multiple variables ''' sum_ = False for value in variables: sum_ = sum_ ^ bool(value) return sum_
python
def xor(*variables): ''' XOR definition for multiple variables ''' sum_ = False for value in variables: sum_ = sum_ ^ bool(value) return sum_
[ "def", "xor", "(", "*", "variables", ")", ":", "sum_", "=", "False", "for", "value", "in", "variables", ":", "sum_", "=", "sum_", "^", "bool", "(", "value", ")", "return", "sum_" ]
XOR definition for multiple variables
[ "XOR", "definition", "for", "multiple", "variables" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/value.py#L12-L19
train
saltstack/salt
salt/modules/win_disk.py
usage
def usage(): ''' Return usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.usage ''' drives = [] ret = {} drive_bitmask = ctypes.windll.kernel32.GetLogicalDrives() for letter in UPPERCASE: if drive_bitmask & 1: drives.append(letter) drive_bitmask >>= 1 for drive in drives: try: (available_bytes, total_bytes, total_free_bytes) = win32api.GetDiskFreeSpaceEx( '{0}:\\'.format(drive) ) used = total_bytes - total_free_bytes capacity = used / float(total_bytes) * 100 ret['{0}:\\'.format(drive)] = { 'filesystem': '{0}:\\'.format(drive), '1K-blocks': total_bytes / 1024, 'used': used / 1024, 'available': total_free_bytes / 1024, 'capacity': '{0:.0f}%'.format(capacity), } except Exception: ret['{0}:\\'.format(drive)] = { 'filesystem': '{0}:\\'.format(drive), '1K-blocks': None, 'used': None, 'available': None, 'capacity': None, } return ret
python
def usage(): ''' Return usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.usage ''' drives = [] ret = {} drive_bitmask = ctypes.windll.kernel32.GetLogicalDrives() for letter in UPPERCASE: if drive_bitmask & 1: drives.append(letter) drive_bitmask >>= 1 for drive in drives: try: (available_bytes, total_bytes, total_free_bytes) = win32api.GetDiskFreeSpaceEx( '{0}:\\'.format(drive) ) used = total_bytes - total_free_bytes capacity = used / float(total_bytes) * 100 ret['{0}:\\'.format(drive)] = { 'filesystem': '{0}:\\'.format(drive), '1K-blocks': total_bytes / 1024, 'used': used / 1024, 'available': total_free_bytes / 1024, 'capacity': '{0:.0f}%'.format(capacity), } except Exception: ret['{0}:\\'.format(drive)] = { 'filesystem': '{0}:\\'.format(drive), '1K-blocks': None, 'used': None, 'available': None, 'capacity': None, } return ret
[ "def", "usage", "(", ")", ":", "drives", "=", "[", "]", "ret", "=", "{", "}", "drive_bitmask", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "GetLogicalDrives", "(", ")", "for", "letter", "in", "UPPERCASE", ":", "if", "drive_bitmask", "&", "1", ...
Return usage information for volumes mounted on this minion CLI Example: .. code-block:: bash salt '*' disk.usage
[ "Return", "usage", "information", "for", "volumes", "mounted", "on", "this", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_disk.py#L43-L84
train
saltstack/salt
salt/modules/boto_apigateway.py
_convert_datetime_str
def _convert_datetime_str(response): ''' modify any key-value pair where value is a datetime object to a string. ''' if response: return dict([(k, '{0}'.format(v)) if isinstance(v, datetime.date) else (k, v) for k, v in six.iteritems(response)]) return None
python
def _convert_datetime_str(response): ''' modify any key-value pair where value is a datetime object to a string. ''' if response: return dict([(k, '{0}'.format(v)) if isinstance(v, datetime.date) else (k, v) for k, v in six.iteritems(response)]) return None
[ "def", "_convert_datetime_str", "(", "response", ")", ":", "if", "response", ":", "return", "dict", "(", "[", "(", "k", ",", "'{0}'", ".", "format", "(", "v", ")", ")", "if", "isinstance", "(", "v", ",", "datetime", ".", "date", ")", "else", "(", "...
modify any key-value pair where value is a datetime object to a string.
[ "modify", "any", "key", "-", "value", "pair", "where", "value", "is", "a", "datetime", "object", "to", "a", "string", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L133-L139
train
saltstack/salt
salt/modules/boto_apigateway.py
_multi_call
def _multi_call(function, contentkey, *args, **kwargs): ''' Retrieve full list of values for the contentkey from a boto3 ApiGateway client function that may be paged via 'position' ''' ret = function(*args, **kwargs) position = ret.get('position') while position: more = function(*args, position=position, **kwargs) ret[contentkey].extend(more[contentkey]) position = more.get('position') return ret.get(contentkey)
python
def _multi_call(function, contentkey, *args, **kwargs): ''' Retrieve full list of values for the contentkey from a boto3 ApiGateway client function that may be paged via 'position' ''' ret = function(*args, **kwargs) position = ret.get('position') while position: more = function(*args, position=position, **kwargs) ret[contentkey].extend(more[contentkey]) position = more.get('position') return ret.get(contentkey)
[ "def", "_multi_call", "(", "function", ",", "contentkey", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "position", "=", "ret", ".", "get", "(", "'position'", ")", "whil...
Retrieve full list of values for the contentkey from a boto3 ApiGateway client function that may be paged via 'position'
[ "Retrieve", "full", "list", "of", "values", "for", "the", "contentkey", "from", "a", "boto3", "ApiGateway", "client", "function", "that", "may", "be", "paged", "via", "position" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L156-L168
train
saltstack/salt
salt/modules/boto_apigateway.py
_find_apis_by_name
def _find_apis_by_name(name, description=None, region=None, key=None, keyid=None, profile=None): ''' get and return list of matching rest api information by the given name and desc. If rest api name evaluates to False, return all apis w/o filtering the name. ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) apis = _multi_call(conn.get_rest_apis, 'items') if name: apis = _filter_apis(name, apis) if description is not None: apis = _filter_apis_desc(description, apis) return {'restapi': [_convert_datetime_str(api) for api in apis]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def _find_apis_by_name(name, description=None, region=None, key=None, keyid=None, profile=None): ''' get and return list of matching rest api information by the given name and desc. If rest api name evaluates to False, return all apis w/o filtering the name. ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) apis = _multi_call(conn.get_rest_apis, 'items') if name: apis = _filter_apis(name, apis) if description is not None: apis = _filter_apis_desc(description, apis) return {'restapi': [_convert_datetime_str(api) for api in apis]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "_find_apis_by_name", "(", "name", ",", "description", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "="...
get and return list of matching rest api information by the given name and desc. If rest api name evaluates to False, return all apis w/o filtering the name.
[ "get", "and", "return", "list", "of", "matching", "rest", "api", "information", "by", "the", "given", "name", "and", "desc", ".", "If", "rest", "api", "name", "evaluates", "to", "False", "return", "all", "apis", "w", "/", "o", "filtering", "the", "name",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L171-L186
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_apis
def describe_apis(name=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Returns all rest apis in the defined region. If optional parameter name is included, returns all rest apis matching the name in the defined region. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_apis salt myminion boto_apigateway.describe_apis name='api name' salt myminion boto_apigateway.describe_apis name='api name' description='desc str' ''' if name: return _find_apis_by_name(name, description=description, region=region, key=key, keyid=keyid, profile=profile) else: return _find_apis_by_name('', description=description, region=region, key=key, keyid=keyid, profile=profile)
python
def describe_apis(name=None, description=None, region=None, key=None, keyid=None, profile=None): ''' Returns all rest apis in the defined region. If optional parameter name is included, returns all rest apis matching the name in the defined region. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_apis salt myminion boto_apigateway.describe_apis name='api name' salt myminion boto_apigateway.describe_apis name='api name' description='desc str' ''' if name: return _find_apis_by_name(name, description=description, region=region, key=key, keyid=keyid, profile=profile) else: return _find_apis_by_name('', description=description, region=region, key=key, keyid=keyid, profile=profile)
[ "def", "describe_apis", "(", "name", "=", "None", ",", "description", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "name", ":", "return", "_find_apis_by_name",...
Returns all rest apis in the defined region. If optional parameter name is included, returns all rest apis matching the name in the defined region. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_apis salt myminion boto_apigateway.describe_apis name='api name' salt myminion boto_apigateway.describe_apis name='api name' description='desc str'
[ "Returns", "all", "rest", "apis", "in", "the", "defined", "region", ".", "If", "optional", "parameter", "name", "is", "included", "returns", "all", "rest", "apis", "matching", "the", "name", "in", "the", "defined", "region", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L189-L211
train
saltstack/salt
salt/modules/boto_apigateway.py
api_exists
def api_exists(name, description=None, region=None, key=None, keyid=None, profile=None): ''' Check to see if the given Rest API Name and optionally description exists. CLI Example: .. code-block:: bash salt myminion boto_apigateway.exists myapi_name ''' apis = _find_apis_by_name(name, description=description, region=region, key=key, keyid=keyid, profile=profile) return {'exists': bool(apis.get('restapi'))}
python
def api_exists(name, description=None, region=None, key=None, keyid=None, profile=None): ''' Check to see if the given Rest API Name and optionally description exists. CLI Example: .. code-block:: bash salt myminion boto_apigateway.exists myapi_name ''' apis = _find_apis_by_name(name, description=description, region=region, key=key, keyid=keyid, profile=profile) return {'exists': bool(apis.get('restapi'))}
[ "def", "api_exists", "(", "name", ",", "description", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "apis", "=", "_find_apis_by_name", "(", "name", ",", "description"...
Check to see if the given Rest API Name and optionally description exists. CLI Example: .. code-block:: bash salt myminion boto_apigateway.exists myapi_name
[ "Check", "to", "see", "if", "the", "given", "Rest", "API", "Name", "and", "optionally", "description", "exists", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L214-L227
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api
def create_api(name, description, cloneFrom=None, region=None, key=None, keyid=None, profile=None): ''' Create a new REST API Service with the given name Returns {created: True} if the rest api was created and returns {created: False} if the rest api was not created. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api myapi_name api_description ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if cloneFrom: api = conn.create_rest_api(name=name, description=description, cloneFrom=cloneFrom) else: api = conn.create_rest_api(name=name, description=description) api = _convert_datetime_str(api) return {'created': True, 'restapi': api} if api else {'created': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api(name, description, cloneFrom=None, region=None, key=None, keyid=None, profile=None): ''' Create a new REST API Service with the given name Returns {created: True} if the rest api was created and returns {created: False} if the rest api was not created. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api myapi_name api_description ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if cloneFrom: api = conn.create_rest_api(name=name, description=description, cloneFrom=cloneFrom) else: api = conn.create_rest_api(name=name, description=description) api = _convert_datetime_str(api) return {'created': True, 'restapi': api} if api else {'created': False} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api", "(", "name", ",", "description", ",", "cloneFrom", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "...
Create a new REST API Service with the given name Returns {created: True} if the rest api was created and returns {created: False} if the rest api was not created. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api myapi_name api_description
[ "Create", "a", "new", "REST", "API", "Service", "with", "the", "given", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L230-L254
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_api
def delete_api(name, description=None, region=None, key=None, keyid=None, profile=None): ''' Delete all REST API Service with the given name and an optional API description Returns {deleted: True, count: deleted_count} if apis were deleted, and returns {deleted: False} if error or not found. CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api myapi_name salt myminion boto_apigateway.delete_api myapi_name description='api description' ''' try: conn_params = dict(region=region, key=key, keyid=keyid, profile=profile) r = _find_apis_by_name(name, description=description, **conn_params) apis = r.get('restapi') if apis: conn = _get_conn(**conn_params) for api in apis: conn.delete_rest_api(restApiId=api['id']) return {'deleted': True, 'count': len(apis)} else: return {'deleted': False} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_api(name, description=None, region=None, key=None, keyid=None, profile=None): ''' Delete all REST API Service with the given name and an optional API description Returns {deleted: True, count: deleted_count} if apis were deleted, and returns {deleted: False} if error or not found. CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api myapi_name salt myminion boto_apigateway.delete_api myapi_name description='api description' ''' try: conn_params = dict(region=region, key=key, keyid=keyid, profile=profile) r = _find_apis_by_name(name, description=description, **conn_params) apis = r.get('restapi') if apis: conn = _get_conn(**conn_params) for api in apis: conn.delete_rest_api(restApiId=api['id']) return {'deleted': True, 'count': len(apis)} else: return {'deleted': False} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_api", "(", "name", ",", "description", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn_params", "=", "dict", "(", "region", "=", "r...
Delete all REST API Service with the given name and an optional API description Returns {deleted: True, count: deleted_count} if apis were deleted, and returns {deleted: False} if error or not found. CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api myapi_name salt myminion boto_apigateway.delete_api myapi_name description='api description'
[ "Delete", "all", "REST", "API", "Service", "with", "the", "given", "name", "and", "an", "optional", "API", "description" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L257-L285
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_resources
def describe_api_resources(restApiId, region=None, key=None, keyid=None, profile=None): ''' Given rest api id, return all resources for this api. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_resources myapi_id ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) resources = sorted(_multi_call(conn.get_resources, 'items', restApiId=restApiId), key=lambda k: k['path']) return {'resources': resources} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_resources(restApiId, region=None, key=None, keyid=None, profile=None): ''' Given rest api id, return all resources for this api. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_resources myapi_id ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) resources = sorted(_multi_call(conn.get_resources, 'items', restApiId=restApiId), key=lambda k: k['path']) return {'resources': resources} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_resources", "(", "restApiId", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", ...
Given rest api id, return all resources for this api. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_resources myapi_id
[ "Given", "rest", "api", "id", "return", "all", "resources", "for", "this", "api", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L288-L306
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_resource
def describe_api_resource(restApiId, path, region=None, key=None, keyid=None, profile=None): ''' Given rest api id, and an absolute resource path, returns the resource id for the given path. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_resource myapi_id resource_path ''' r = describe_api_resources(restApiId, region=region, key=key, keyid=keyid, profile=profile) resources = r.get('resources') if resources is None: return r for resource in resources: if resource['path'] == path: return {'resource': resource} return {'resource': None}
python
def describe_api_resource(restApiId, path, region=None, key=None, keyid=None, profile=None): ''' Given rest api id, and an absolute resource path, returns the resource id for the given path. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_resource myapi_id resource_path ''' r = describe_api_resources(restApiId, region=region, key=key, keyid=keyid, profile=profile) resources = r.get('resources') if resources is None: return r for resource in resources: if resource['path'] == path: return {'resource': resource} return {'resource': None}
[ "def", "describe_api_resource", "(", "restApiId", ",", "path", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "r", "=", "describe_api_resources", "(", "restApiId", ",", "region", "="...
Given rest api id, and an absolute resource path, returns the resource id for the given path. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_resource myapi_id resource_path
[ "Given", "rest", "api", "id", "and", "an", "absolute", "resource", "path", "returns", "the", "resource", "id", "for", "the", "given", "path", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L309-L329
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api_resources
def create_api_resources(restApiId, path, region=None, key=None, keyid=None, profile=None): ''' Given rest api id, and an absolute resource path, create all the resources and return all resources in the resourcepath, returns False on failure. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_resources myapi_id resource_path ''' path_parts = path.split('/') created = [] current_path = '' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for path_part in path_parts: if current_path == '/': current_path = '{0}{1}'.format(current_path, path_part) else: current_path = '{0}/{1}'.format(current_path, path_part) r = describe_api_resource(restApiId, current_path, region=region, key=key, keyid=keyid, profile=profile) resource = r.get('resource') if not resource: resource = conn.create_resource(restApiId=restApiId, parentId=created[-1]['id'], pathPart=path_part) created.append(resource) if created: return {'created': True, 'restApiId': restApiId, 'resources': created} else: return {'created': False, 'error': 'unexpected error.'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api_resources(restApiId, path, region=None, key=None, keyid=None, profile=None): ''' Given rest api id, and an absolute resource path, create all the resources and return all resources in the resourcepath, returns False on failure. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_resources myapi_id resource_path ''' path_parts = path.split('/') created = [] current_path = '' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for path_part in path_parts: if current_path == '/': current_path = '{0}{1}'.format(current_path, path_part) else: current_path = '{0}/{1}'.format(current_path, path_part) r = describe_api_resource(restApiId, current_path, region=region, key=key, keyid=keyid, profile=profile) resource = r.get('resource') if not resource: resource = conn.create_resource(restApiId=restApiId, parentId=created[-1]['id'], pathPart=path_part) created.append(resource) if created: return {'created': True, 'restApiId': restApiId, 'resources': created} else: return {'created': False, 'error': 'unexpected error.'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api_resources", "(", "restApiId", ",", "path", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "path_parts", "=", "path", ".", "split", "(", "'/'", ")", "created", ...
Given rest api id, and an absolute resource path, create all the resources and return all resources in the resourcepath, returns False on failure. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_resources myapi_id resource_path
[ "Given", "rest", "api", "id", "and", "an", "absolute", "resource", "path", "create", "all", "the", "resources", "and", "return", "all", "resources", "in", "the", "resourcepath", "returns", "False", "on", "failure", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L332-L367
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_api_resources
def delete_api_resources(restApiId, path, region=None, key=None, keyid=None, profile=None): ''' Given restApiId and an absolute resource path, delete the resources starting from the absolute resource path. If resourcepath is the root resource '/', the function will return False. Returns False on failure. CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_resources myapi_id, resource_path ''' if path == '/': return {'deleted': False, 'error': 'use delete_api to remove the root resource'} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = describe_api_resource(restApiId, path, region=region, key=key, keyid=keyid, profile=profile) resource = r.get('resource') if resource: conn.delete_resource(restApiId=restApiId, resourceId=resource['id']) return {'deleted': True} else: return {'deleted': False, 'error': 'no resource found by {0}'.format(path)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_api_resources(restApiId, path, region=None, key=None, keyid=None, profile=None): ''' Given restApiId and an absolute resource path, delete the resources starting from the absolute resource path. If resourcepath is the root resource '/', the function will return False. Returns False on failure. CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_resources myapi_id, resource_path ''' if path == '/': return {'deleted': False, 'error': 'use delete_api to remove the root resource'} try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) r = describe_api_resource(restApiId, path, region=region, key=key, keyid=keyid, profile=profile) resource = r.get('resource') if resource: conn.delete_resource(restApiId=restApiId, resourceId=resource['id']) return {'deleted': True} else: return {'deleted': False, 'error': 'no resource found by {0}'.format(path)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_api_resources", "(", "restApiId", ",", "path", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "if", "path", "==", "'/'", ":", "return", "{", "'deleted'", ":", "Fal...
Given restApiId and an absolute resource path, delete the resources starting from the absolute resource path. If resourcepath is the root resource '/', the function will return False. Returns False on failure. CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_resources myapi_id, resource_path
[ "Given", "restApiId", "and", "an", "absolute", "resource", "path", "delete", "the", "resources", "starting", "from", "the", "absolute", "resource", "path", ".", "If", "resourcepath", "is", "the", "root", "resource", "/", "the", "function", "will", "return", "F...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L370-L396
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_key
def describe_api_key(apiKey, region=None, key=None, keyid=None, profile=None): ''' Gets info about the given api key CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_key apigw_api_key ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.get_api_key(apiKey=apiKey) return {'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_key(apiKey, region=None, key=None, keyid=None, profile=None): ''' Gets info about the given api key CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_key apigw_api_key ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.get_api_key(apiKey=apiKey) return {'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_key", "(", "apiKey", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "k...
Gets info about the given api key CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_key apigw_api_key
[ "Gets", "info", "about", "the", "given", "api", "key" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L427-L443
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_keys
def describe_api_keys(region=None, key=None, keyid=None, profile=None): ''' Gets information about the defined API Keys. Return list of apiKeys. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_keys ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) apikeys = _multi_call(conn.get_api_keys, 'items') return {'apiKeys': [_convert_datetime_str(apikey) for apikey in apikeys]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_keys(region=None, key=None, keyid=None, profile=None): ''' Gets information about the defined API Keys. Return list of apiKeys. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_keys ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) apikeys = _multi_call(conn.get_api_keys, 'items') return {'apiKeys': [_convert_datetime_str(apikey) for apikey in apikeys]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_keys", "(", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "key...
Gets information about the defined API Keys. Return list of apiKeys. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_keys
[ "Gets", "information", "about", "the", "defined", "API", "Keys", ".", "Return", "list", "of", "apiKeys", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L446-L463
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api_key
def create_api_key(name, description, enabled=True, stageKeys=None, region=None, key=None, keyid=None, profile=None): ''' Create an API key given name and description. An optional enabled argument can be provided. If provided, the valid values are True|False. This argument defaults to True. An optional stageKeys argument can be provided in the form of list of dictionary with 'restApiId' and 'stageName' as keys. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_key name description salt myminion boto_apigateway.create_api_key name description enabled=False salt myminion boto_apigateway.create_api_key name description \\ stageKeys='[{"restApiId": "id", "stageName": "stagename"}]' ''' try: stageKeys = list() if stageKeys is None else stageKeys conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.create_api_key(name=name, description=description, enabled=enabled, stageKeys=stageKeys) if not response: return {'created': False} return {'created': True, 'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api_key(name, description, enabled=True, stageKeys=None, region=None, key=None, keyid=None, profile=None): ''' Create an API key given name and description. An optional enabled argument can be provided. If provided, the valid values are True|False. This argument defaults to True. An optional stageKeys argument can be provided in the form of list of dictionary with 'restApiId' and 'stageName' as keys. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_key name description salt myminion boto_apigateway.create_api_key name description enabled=False salt myminion boto_apigateway.create_api_key name description \\ stageKeys='[{"restApiId": "id", "stageName": "stagename"}]' ''' try: stageKeys = list() if stageKeys is None else stageKeys conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.create_api_key(name=name, description=description, enabled=enabled, stageKeys=stageKeys) if not response: return {'created': False} return {'created': True, 'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api_key", "(", "name", ",", "description", ",", "enabled", "=", "True", ",", "stageKeys", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", ...
Create an API key given name and description. An optional enabled argument can be provided. If provided, the valid values are True|False. This argument defaults to True. An optional stageKeys argument can be provided in the form of list of dictionary with 'restApiId' and 'stageName' as keys. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_key name description salt myminion boto_apigateway.create_api_key name description enabled=False salt myminion boto_apigateway.create_api_key name description \\ stageKeys='[{"restApiId": "id", "stageName": "stagename"}]'
[ "Create", "an", "API", "key", "given", "name", "and", "description", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L466-L501
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_api_key
def delete_api_key(apiKey, region=None, key=None, keyid=None, profile=None): ''' Deletes a given apiKey CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_key apikeystring ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_api_key(apiKey=apiKey) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_api_key(apiKey, region=None, key=None, keyid=None, profile=None): ''' Deletes a given apiKey CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_key apikeystring ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_api_key(apiKey=apiKey) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_api_key", "(", "apiKey", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key...
Deletes a given apiKey CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_key apikeystring
[ "Deletes", "a", "given", "apiKey" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L504-L520
train
saltstack/salt
salt/modules/boto_apigateway.py
_api_key_patch_replace
def _api_key_patch_replace(conn, apiKey, path, value): ''' the replace patch operation on an ApiKey resource ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
python
def _api_key_patch_replace(conn, apiKey, path, value): ''' the replace patch operation on an ApiKey resource ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=[{'op': 'replace', 'path': path, 'value': value}]) return response
[ "def", "_api_key_patch_replace", "(", "conn", ",", "apiKey", ",", "path", ",", "value", ")", ":", "response", "=", "conn", ".", "update_api_key", "(", "apiKey", "=", "apiKey", ",", "patchOperations", "=", "[", "{", "'op'", ":", "'replace'", ",", "'path'", ...
the replace patch operation on an ApiKey resource
[ "the", "replace", "patch", "operation", "on", "an", "ApiKey", "resource" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L523-L529
train
saltstack/salt
salt/modules/boto_apigateway.py
_api_key_patch_add
def _api_key_patch_add(conn, apiKey, pvlist): ''' the add patch operation for a list of (path, value) tuples on an ApiKey resource list path ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=_api_key_patchops('add', pvlist)) return response
python
def _api_key_patch_add(conn, apiKey, pvlist): ''' the add patch operation for a list of (path, value) tuples on an ApiKey resource list path ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=_api_key_patchops('add', pvlist)) return response
[ "def", "_api_key_patch_add", "(", "conn", ",", "apiKey", ",", "pvlist", ")", ":", "response", "=", "conn", ".", "update_api_key", "(", "apiKey", "=", "apiKey", ",", "patchOperations", "=", "_api_key_patchops", "(", "'add'", ",", "pvlist", ")", ")", "return",...
the add patch operation for a list of (path, value) tuples on an ApiKey resource list path
[ "the", "add", "patch", "operation", "for", "a", "list", "of", "(", "path", "value", ")", "tuples", "on", "an", "ApiKey", "resource", "list", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L539-L545
train
saltstack/salt
salt/modules/boto_apigateway.py
_api_key_patch_remove
def _api_key_patch_remove(conn, apiKey, pvlist): ''' the remove patch operation for a list of (path, value) tuples on an ApiKey resource list path ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=_api_key_patchops('remove', pvlist)) return response
python
def _api_key_patch_remove(conn, apiKey, pvlist): ''' the remove patch operation for a list of (path, value) tuples on an ApiKey resource list path ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=_api_key_patchops('remove', pvlist)) return response
[ "def", "_api_key_patch_remove", "(", "conn", ",", "apiKey", ",", "pvlist", ")", ":", "response", "=", "conn", ".", "update_api_key", "(", "apiKey", "=", "apiKey", ",", "patchOperations", "=", "_api_key_patchops", "(", "'remove'", ",", "pvlist", ")", ")", "re...
the remove patch operation for a list of (path, value) tuples on an ApiKey resource list path
[ "the", "remove", "patch", "operation", "for", "a", "list", "of", "(", "path", "value", ")", "tuples", "on", "an", "ApiKey", "resource", "list", "path" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L548-L554
train
saltstack/salt
salt/modules/boto_apigateway.py
update_api_key_description
def update_api_key_description(apiKey, description, region=None, key=None, keyid=None, profile=None): ''' update the given apiKey with the given description. CLI Example: .. code-block:: bash salt myminion boto_apigateway.update_api_key_description api_key description ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = _api_key_patch_replace(conn, apiKey, '/description', description) return {'updated': True, 'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
python
def update_api_key_description(apiKey, description, region=None, key=None, keyid=None, profile=None): ''' update the given apiKey with the given description. CLI Example: .. code-block:: bash salt myminion boto_apigateway.update_api_key_description api_key description ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = _api_key_patch_replace(conn, apiKey, '/description', description) return {'updated': True, 'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'updated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "update_api_key_description", "(", "apiKey", ",", "description", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "re...
update the given apiKey with the given description. CLI Example: .. code-block:: bash salt myminion boto_apigateway.update_api_key_description api_key description
[ "update", "the", "given", "apiKey", "with", "the", "given", "description", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L557-L573
train
saltstack/salt
salt/modules/boto_apigateway.py
enable_api_key
def enable_api_key(apiKey, region=None, key=None, keyid=None, profile=None): ''' enable the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.enable_api_key api_key ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = _api_key_patch_replace(conn, apiKey, '/enabled', 'True') return {'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def enable_api_key(apiKey, region=None, key=None, keyid=None, profile=None): ''' enable the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.enable_api_key api_key ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = _api_key_patch_replace(conn, apiKey, '/enabled', 'True') return {'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "enable_api_key", "(", "apiKey", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key...
enable the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.enable_api_key api_key
[ "enable", "the", "given", "apiKey", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L576-L592
train
saltstack/salt
salt/modules/boto_apigateway.py
associate_api_key_stagekeys
def associate_api_key_stagekeys(apiKey, stagekeyslist, region=None, key=None, keyid=None, profile=None): ''' associate the given stagekeyslist to the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.associate_stagekeys_api_key \\ api_key '["restapi id/stage name", ...]' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) pvlist = [('/stages', stagekey) for stagekey in stagekeyslist] response = _api_key_patch_add(conn, apiKey, pvlist) return {'associated': True, 'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'associated': False, 'error': __utils__['boto3.get_error'](e)}
python
def associate_api_key_stagekeys(apiKey, stagekeyslist, region=None, key=None, keyid=None, profile=None): ''' associate the given stagekeyslist to the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.associate_stagekeys_api_key \\ api_key '["restapi id/stage name", ...]' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) pvlist = [('/stages', stagekey) for stagekey in stagekeyslist] response = _api_key_patch_add(conn, apiKey, pvlist) return {'associated': True, 'apiKey': _convert_datetime_str(response)} except ClientError as e: return {'associated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "associate_api_key_stagekeys", "(", "apiKey", ",", "stagekeyslist", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", ...
associate the given stagekeyslist to the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.associate_stagekeys_api_key \\ api_key '["restapi id/stage name", ...]'
[ "associate", "the", "given", "stagekeyslist", "to", "the", "given", "apiKey", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L614-L632
train
saltstack/salt
salt/modules/boto_apigateway.py
disassociate_api_key_stagekeys
def disassociate_api_key_stagekeys(apiKey, stagekeyslist, region=None, key=None, keyid=None, profile=None): ''' disassociate the given stagekeyslist to the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.disassociate_stagekeys_api_key \\ api_key '["restapi id/stage name", ...]' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) pvlist = [('/stages', stagekey) for stagekey in stagekeyslist] response = _api_key_patch_remove(conn, apiKey, pvlist) return {'disassociated': True} except ClientError as e: return {'disassociated': False, 'error': __utils__['boto3.get_error'](e)}
python
def disassociate_api_key_stagekeys(apiKey, stagekeyslist, region=None, key=None, keyid=None, profile=None): ''' disassociate the given stagekeyslist to the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.disassociate_stagekeys_api_key \\ api_key '["restapi id/stage name", ...]' ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) pvlist = [('/stages', stagekey) for stagekey in stagekeyslist] response = _api_key_patch_remove(conn, apiKey, pvlist) return {'disassociated': True} except ClientError as e: return {'disassociated': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "disassociate_api_key_stagekeys", "(", "apiKey", ",", "stagekeyslist", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=",...
disassociate the given stagekeyslist to the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.disassociate_stagekeys_api_key \\ api_key '["restapi id/stage name", ...]'
[ "disassociate", "the", "given", "stagekeyslist", "to", "the", "given", "apiKey", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L635-L653
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_deployments
def describe_api_deployments(restApiId, region=None, key=None, keyid=None, profile=None): ''' Gets information about the defined API Deployments. Return list of api deployments. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_deployments restApiId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deployments = [] _deployments = conn.get_deployments(restApiId=restApiId) while True: if _deployments: deployments = deployments + _deployments['items'] if 'position' not in _deployments: break _deployments = conn.get_deployments(restApiId=restApiId, position=_deployments['position']) return {'deployments': [_convert_datetime_str(deployment) for deployment in deployments]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_deployments(restApiId, region=None, key=None, keyid=None, profile=None): ''' Gets information about the defined API Deployments. Return list of api deployments. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_deployments restApiId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deployments = [] _deployments = conn.get_deployments(restApiId=restApiId) while True: if _deployments: deployments = deployments + _deployments['items'] if 'position' not in _deployments: break _deployments = conn.get_deployments(restApiId=restApiId, position=_deployments['position']) return {'deployments': [_convert_datetime_str(deployment) for deployment in deployments]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_deployments", "(", "restApiId", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", ...
Gets information about the defined API Deployments. Return list of api deployments. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_deployments restApiId
[ "Gets", "information", "about", "the", "defined", "API", "Deployments", ".", "Return", "list", "of", "api", "deployments", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L656-L681
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_deployment
def describe_api_deployment(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None): ''' Get API deployment for a given restApiId and deploymentId. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_deployent restApiId deploymentId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deployment = conn.get_deployment(restApiId=restApiId, deploymentId=deploymentId) return {'deployment': _convert_datetime_str(deployment)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_deployment(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None): ''' Get API deployment for a given restApiId and deploymentId. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_deployent restApiId deploymentId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deployment = conn.get_deployment(restApiId=restApiId, deploymentId=deploymentId) return {'deployment': _convert_datetime_str(deployment)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_deployment", "(", "restApiId", ",", "deploymentId", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "r...
Get API deployment for a given restApiId and deploymentId. CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_deployent restApiId deploymentId
[ "Get", "API", "deployment", "for", "a", "given", "restApiId", "and", "deploymentId", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L684-L700
train
saltstack/salt
salt/modules/boto_apigateway.py
activate_api_deployment
def activate_api_deployment(restApiId, stageName, deploymentId, region=None, key=None, keyid=None, profile=None): ''' Activates previously deployed deployment for a given stage CLI Example: .. code-block:: bash salt myminion boto_apigateway.activate_api_deployent restApiId stagename deploymentId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.update_stage(restApiId=restApiId, stageName=stageName, patchOperations=[{'op': 'replace', 'path': '/deploymentId', 'value': deploymentId}]) return {'set': True, 'response': _convert_datetime_str(response)} except ClientError as e: return {'set': False, 'error': __utils__['boto3.get_error'](e)}
python
def activate_api_deployment(restApiId, stageName, deploymentId, region=None, key=None, keyid=None, profile=None): ''' Activates previously deployed deployment for a given stage CLI Example: .. code-block:: bash salt myminion boto_apigateway.activate_api_deployent restApiId stagename deploymentId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.update_stage(restApiId=restApiId, stageName=stageName, patchOperations=[{'op': 'replace', 'path': '/deploymentId', 'value': deploymentId}]) return {'set': True, 'response': _convert_datetime_str(response)} except ClientError as e: return {'set': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "activate_api_deployment", "(", "restApiId", ",", "stageName", ",", "deploymentId", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", ...
Activates previously deployed deployment for a given stage CLI Example: .. code-block:: bash salt myminion boto_apigateway.activate_api_deployent restApiId stagename deploymentId
[ "Activates", "previously", "deployed", "deployment", "for", "a", "given", "stage" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L703-L723
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api_deployment
def create_api_deployment(restApiId, stageName, stageDescription='', description='', cacheClusterEnabled=False, cacheClusterSize='0.5', variables=None, region=None, key=None, keyid=None, profile=None): ''' Creates a new API deployment. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_deployent restApiId stagename stageDescription='' \\ description='' cacheClusterEnabled=True|False cacheClusterSize=0.5 variables='{"name": "value"}' ''' try: variables = dict() if variables is None else variables conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deployment = conn.create_deployment(restApiId=restApiId, stageName=stageName, stageDescription=stageDescription, description=description, cacheClusterEnabled=cacheClusterEnabled, cacheClusterSize=cacheClusterSize, variables=variables) return {'created': True, 'deployment': _convert_datetime_str(deployment)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api_deployment(restApiId, stageName, stageDescription='', description='', cacheClusterEnabled=False, cacheClusterSize='0.5', variables=None, region=None, key=None, keyid=None, profile=None): ''' Creates a new API deployment. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_deployent restApiId stagename stageDescription='' \\ description='' cacheClusterEnabled=True|False cacheClusterSize=0.5 variables='{"name": "value"}' ''' try: variables = dict() if variables is None else variables conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) deployment = conn.create_deployment(restApiId=restApiId, stageName=stageName, stageDescription=stageDescription, description=description, cacheClusterEnabled=cacheClusterEnabled, cacheClusterSize=cacheClusterSize, variables=variables) return {'created': True, 'deployment': _convert_datetime_str(deployment)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api_deployment", "(", "restApiId", ",", "stageName", ",", "stageDescription", "=", "''", ",", "description", "=", "''", ",", "cacheClusterEnabled", "=", "False", ",", "cacheClusterSize", "=", "'0.5'", ",", "variables", "=", "None", ",", "region", ...
Creates a new API deployment. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_deployent restApiId stagename stageDescription='' \\ description='' cacheClusterEnabled=True|False cacheClusterSize=0.5 variables='{"name": "value"}'
[ "Creates", "a", "new", "API", "deployment", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L726-L750
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_api_deployment
def delete_api_deployment(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None): ''' Deletes API deployment for a given restApiId and deploymentID CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_deployent restApiId deploymentId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_deployment(restApiId=restApiId, deploymentId=deploymentId) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_api_deployment(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None): ''' Deletes API deployment for a given restApiId and deploymentID CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_deployent restApiId deploymentId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_deployment(restApiId=restApiId, deploymentId=deploymentId) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_api_deployment", "(", "restApiId", ",", "deploymentId", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "reg...
Deletes API deployment for a given restApiId and deploymentID CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_deployent restApiId deploymentId
[ "Deletes", "API", "deployment", "for", "a", "given", "restApiId", "and", "deploymentID" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L753-L769
train
saltstack/salt
salt/modules/boto_apigateway.py
overwrite_api_stage_variables
def overwrite_api_stage_variables(restApiId, stageName, variables, region=None, key=None, keyid=None, profile=None): ''' Overwrite the stage variables for the given restApiId and stage name with the given variables, variables must be in the form of a dictionary. Overwrite will always remove all the existing stage variables associated with the given restApiId and stage name, follow by the adding of all the variables specified in the variables dictionary CLI Example: .. code-block:: bash salt myminion boto_apigateway.overwrite_api_stage_variables restApiId stageName variables='{"name": "value"}' ''' try: res = describe_api_stage(restApiId, stageName, region=region, key=key, keyid=keyid, profile=profile) if res.get('error'): return {'overwrite': False, 'error': res.get('error')} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # remove all existing variables that are not in the given variables, # followed by adding of the variables stage = res.get('stage') old_vars = stage.get('variables', {}) patch_ops = [] for old_var in old_vars: if old_var not in variables: patch_ops.append(dict(op='remove', path='/variables/{0}'.format(old_var), value='')) for var, val in six.iteritems(variables): if var not in old_vars or old_vars[var] != val: patch_ops.append(dict(op='replace', path='/variables/{0}'.format(var), value=val)) if patch_ops: stage = conn.update_stage(restApiId=restApiId, stageName=stageName, patchOperations=patch_ops) return {'overwrite': True, 'stage': _convert_datetime_str(stage)} except ClientError as e: return {'overwrite': False, 'error': __utils__['boto3.get_error'](e)}
python
def overwrite_api_stage_variables(restApiId, stageName, variables, region=None, key=None, keyid=None, profile=None): ''' Overwrite the stage variables for the given restApiId and stage name with the given variables, variables must be in the form of a dictionary. Overwrite will always remove all the existing stage variables associated with the given restApiId and stage name, follow by the adding of all the variables specified in the variables dictionary CLI Example: .. code-block:: bash salt myminion boto_apigateway.overwrite_api_stage_variables restApiId stageName variables='{"name": "value"}' ''' try: res = describe_api_stage(restApiId, stageName, region=region, key=key, keyid=keyid, profile=profile) if res.get('error'): return {'overwrite': False, 'error': res.get('error')} conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) # remove all existing variables that are not in the given variables, # followed by adding of the variables stage = res.get('stage') old_vars = stage.get('variables', {}) patch_ops = [] for old_var in old_vars: if old_var not in variables: patch_ops.append(dict(op='remove', path='/variables/{0}'.format(old_var), value='')) for var, val in six.iteritems(variables): if var not in old_vars or old_vars[var] != val: patch_ops.append(dict(op='replace', path='/variables/{0}'.format(var), value=val)) if patch_ops: stage = conn.update_stage(restApiId=restApiId, stageName=stageName, patchOperations=patch_ops) return {'overwrite': True, 'stage': _convert_datetime_str(stage)} except ClientError as e: return {'overwrite': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "overwrite_api_stage_variables", "(", "restApiId", ",", "stageName", ",", "variables", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "res", "=", "describe_api_stage...
Overwrite the stage variables for the given restApiId and stage name with the given variables, variables must be in the form of a dictionary. Overwrite will always remove all the existing stage variables associated with the given restApiId and stage name, follow by the adding of all the variables specified in the variables dictionary CLI Example: .. code-block:: bash salt myminion boto_apigateway.overwrite_api_stage_variables restApiId stageName variables='{"name": "value"}'
[ "Overwrite", "the", "stage", "variables", "for", "the", "given", "restApiId", "and", "stage", "name", "with", "the", "given", "variables", "variables", "must", "be", "in", "the", "form", "of", "a", "dictionary", ".", "Overwrite", "will", "always", "remove", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L772-L815
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_stage
def describe_api_stage(restApiId, stageName, region=None, key=None, keyid=None, profile=None): ''' Get API stage for a given apiID and stage name CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_stage restApiId stageName ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) stage = conn.get_stage(restApiId=restApiId, stageName=stageName) return {'stage': _convert_datetime_str(stage)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_stage(restApiId, stageName, region=None, key=None, keyid=None, profile=None): ''' Get API stage for a given apiID and stage name CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_stage restApiId stageName ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) stage = conn.get_stage(restApiId=restApiId, stageName=stageName) return {'stage': _convert_datetime_str(stage)} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_stage", "(", "restApiId", ",", "stageName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ...
Get API stage for a given apiID and stage name CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_stage restApiId stageName
[ "Get", "API", "stage", "for", "a", "given", "apiID", "and", "stage", "name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L818-L834
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_stages
def describe_api_stages(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None): ''' Get all API stages for a given apiID and deploymentID CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_stages restApiId deploymentId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) stages = conn.get_stages(restApiId=restApiId, deploymentId=deploymentId) return {'stages': [_convert_datetime_str(stage) for stage in stages['item']]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_stages(restApiId, deploymentId, region=None, key=None, keyid=None, profile=None): ''' Get all API stages for a given apiID and deploymentID CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_stages restApiId deploymentId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) stages = conn.get_stages(restApiId=restApiId, deploymentId=deploymentId) return {'stages': [_convert_datetime_str(stage) for stage in stages['item']]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_stages", "(", "restApiId", ",", "deploymentId", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "regio...
Get all API stages for a given apiID and deploymentID CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_stages restApiId deploymentId
[ "Get", "all", "API", "stages", "for", "a", "given", "apiID", "and", "deploymentID" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L837-L853
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api_stage
def create_api_stage(restApiId, stageName, deploymentId, description='', cacheClusterEnabled=False, cacheClusterSize='0.5', variables=None, region=None, key=None, keyid=None, profile=None): ''' Creates a new API stage for a given restApiId and deploymentId. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_stage restApiId stagename deploymentId \\ description='' cacheClusterEnabled=True|False cacheClusterSize='0.5' variables='{"name": "value"}' ''' try: variables = dict() if variables is None else variables conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) stage = conn.create_stage(restApiId=restApiId, stageName=stageName, deploymentId=deploymentId, description=description, cacheClusterEnabled=cacheClusterEnabled, cacheClusterSize=cacheClusterSize, variables=variables) return {'created': True, 'stage': _convert_datetime_str(stage)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api_stage(restApiId, stageName, deploymentId, description='', cacheClusterEnabled=False, cacheClusterSize='0.5', variables=None, region=None, key=None, keyid=None, profile=None): ''' Creates a new API stage for a given restApiId and deploymentId. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_stage restApiId stagename deploymentId \\ description='' cacheClusterEnabled=True|False cacheClusterSize='0.5' variables='{"name": "value"}' ''' try: variables = dict() if variables is None else variables conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) stage = conn.create_stage(restApiId=restApiId, stageName=stageName, deploymentId=deploymentId, description=description, cacheClusterEnabled=cacheClusterEnabled, cacheClusterSize=cacheClusterSize, variables=variables) return {'created': True, 'stage': _convert_datetime_str(stage)} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api_stage", "(", "restApiId", ",", "stageName", ",", "deploymentId", ",", "description", "=", "''", ",", "cacheClusterEnabled", "=", "False", ",", "cacheClusterSize", "=", "'0.5'", ",", "variables", "=", "None", ",", "region", "=", "None", ",", ...
Creates a new API stage for a given restApiId and deploymentId. CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_stage restApiId stagename deploymentId \\ description='' cacheClusterEnabled=True|False cacheClusterSize='0.5' variables='{"name": "value"}'
[ "Creates", "a", "new", "API", "stage", "for", "a", "given", "restApiId", "and", "deploymentId", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L856-L879
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_api_stage
def delete_api_stage(restApiId, stageName, region=None, key=None, keyid=None, profile=None): ''' Deletes stage identified by stageName from API identified by restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_stage restApiId stageName ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_stage(restApiId=restApiId, stageName=stageName) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_api_stage(restApiId, stageName, region=None, key=None, keyid=None, profile=None): ''' Deletes stage identified by stageName from API identified by restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_stage restApiId stageName ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_stage(restApiId=restApiId, stageName=stageName) return {'deleted': True} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_api_stage", "(", "restApiId", ",", "stageName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ...
Deletes stage identified by stageName from API identified by restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_stage restApiId stageName
[ "Deletes", "stage", "identified", "by", "stageName", "from", "API", "identified", "by", "restApiId" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L882-L898
train
saltstack/salt
salt/modules/boto_apigateway.py
flush_api_stage_cache
def flush_api_stage_cache(restApiId, stageName, region=None, key=None, keyid=None, profile=None): ''' Flushes cache for the stage identified by stageName from API identified by restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.flush_api_stage_cache restApiId stageName ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.flush_stage_cache(restApiId=restApiId, stageName=stageName) return {'flushed': True} except ClientError as e: return {'flushed': False, 'error': __utils__['boto3.get_error'](e)}
python
def flush_api_stage_cache(restApiId, stageName, region=None, key=None, keyid=None, profile=None): ''' Flushes cache for the stage identified by stageName from API identified by restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.flush_api_stage_cache restApiId stageName ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.flush_stage_cache(restApiId=restApiId, stageName=stageName) return {'flushed': True} except ClientError as e: return {'flushed': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "flush_api_stage_cache", "(", "restApiId", ",", "stageName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region...
Flushes cache for the stage identified by stageName from API identified by restApiId CLI Example: .. code-block:: bash salt myminion boto_apigateway.flush_api_stage_cache restApiId stageName
[ "Flushes", "cache", "for", "the", "stage", "identified", "by", "stageName", "from", "API", "identified", "by", "restApiId" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L901-L917
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api_method
def create_api_method(restApiId, resourcePath, httpMethod, authorizationType, apiKeyRequired=False, requestParameters=None, requestModels=None, region=None, key=None, keyid=None, profile=None): ''' Creates API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_method restApiId resourcePath, httpMethod, authorizationType, \\ apiKeyRequired=False, requestParameters='{"name", "value"}', requestModels='{"content-type", "value"}' ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: requestParameters = dict() if requestParameters is None else requestParameters requestModels = dict() if requestModels is None else requestModels conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) method = conn.put_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, authorizationType=str(authorizationType), apiKeyRequired=apiKeyRequired, # future lint: disable=blacklisted-function requestParameters=requestParameters, requestModels=requestModels) return {'created': True, 'method': method} return {'created': False, 'error': 'Failed to create method'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api_method(restApiId, resourcePath, httpMethod, authorizationType, apiKeyRequired=False, requestParameters=None, requestModels=None, region=None, key=None, keyid=None, profile=None): ''' Creates API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_method restApiId resourcePath, httpMethod, authorizationType, \\ apiKeyRequired=False, requestParameters='{"name", "value"}', requestModels='{"content-type", "value"}' ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: requestParameters = dict() if requestParameters is None else requestParameters requestModels = dict() if requestModels is None else requestModels conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) method = conn.put_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, authorizationType=str(authorizationType), apiKeyRequired=apiKeyRequired, # future lint: disable=blacklisted-function requestParameters=requestParameters, requestModels=requestModels) return {'created': True, 'method': method} return {'created': False, 'error': 'Failed to create method'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api_method", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "authorizationType", ",", "apiKeyRequired", "=", "False", ",", "requestParameters", "=", "None", ",", "requestModels", "=", "None", ",", "region", "=", "None", ",", "key",...
Creates API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_method restApiId resourcePath, httpMethod, authorizationType, \\ apiKeyRequired=False, requestParameters='{"name", "value"}', requestModels='{"content-type", "value"}'
[ "Creates", "API", "method", "for", "a", "resource", "in", "the", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L920-L949
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_method
def describe_api_method(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None): ''' Get API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_method restApiId resourcePath httpMethod ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) method = conn.get_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod) return {'method': _convert_datetime_str(method)} return {'error': 'get API method failed: no such resource'} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_method(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None): ''' Get API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_method restApiId resourcePath httpMethod ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) method = conn.get_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod) return {'method': _convert_datetime_str(method)} return {'error': 'get API method failed: no such resource'} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_method", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "resource", "=", "describe_api_resour...
Get API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_method restApiId resourcePath httpMethod
[ "Get", "API", "method", "for", "a", "resource", "in", "the", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L952-L972
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_api_method
def delete_api_method(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None): ''' Delete API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_method restApiId resourcePath httpMethod ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod) return {'deleted': True} return {'deleted': False, 'error': 'get API method failed: no such resource'} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_api_method(restApiId, resourcePath, httpMethod, region=None, key=None, keyid=None, profile=None): ''' Delete API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_method restApiId resourcePath httpMethod ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_method(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod) return {'deleted': True} return {'deleted': False, 'error': 'get API method failed: no such resource'} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_api_method", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "resource", "=", "describe_api_resource...
Delete API method for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_method restApiId resourcePath httpMethod
[ "Delete", "API", "method", "for", "a", "resource", "in", "the", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L975-L995
train
saltstack/salt
salt/modules/boto_apigateway.py
create_api_method_response
def create_api_method_response(restApiId, resourcePath, httpMethod, statusCode, responseParameters=None, responseModels=None, region=None, key=None, keyid=None, profile=None): ''' Create API method response for a method on a given resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_method_response restApiId resourcePath httpMethod \\ statusCode responseParameters='{"name", "True|False"}' responseModels='{"content-type", "model"}' ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: responseParameters = dict() if responseParameters is None else responseParameters responseModels = dict() if responseModels is None else responseModels conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.put_method_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=str(statusCode), # future lint: disable=blacklisted-function responseParameters=responseParameters, responseModels=responseModels) return {'created': True, 'response': response} return {'created': False, 'error': 'no such resource'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
python
def create_api_method_response(restApiId, resourcePath, httpMethod, statusCode, responseParameters=None, responseModels=None, region=None, key=None, keyid=None, profile=None): ''' Create API method response for a method on a given resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_method_response restApiId resourcePath httpMethod \\ statusCode responseParameters='{"name", "True|False"}' responseModels='{"content-type", "model"}' ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: responseParameters = dict() if responseParameters is None else responseParameters responseModels = dict() if responseModels is None else responseModels conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.put_method_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=str(statusCode), # future lint: disable=blacklisted-function responseParameters=responseParameters, responseModels=responseModels) return {'created': True, 'response': response} return {'created': False, 'error': 'no such resource'} except ClientError as e: return {'created': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "create_api_method_response", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "statusCode", ",", "responseParameters", "=", "None", ",", "responseModels", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "="...
Create API method response for a method on a given resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.create_api_method_response restApiId resourcePath httpMethod \\ statusCode responseParameters='{"name", "True|False"}' responseModels='{"content-type", "model"}'
[ "Create", "API", "method", "response", "for", "a", "method", "on", "a", "given", "resource", "in", "the", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L998-L1025
train
saltstack/salt
salt/modules/boto_apigateway.py
delete_api_method_response
def delete_api_method_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Delete API method response for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_method_response restApiId resourcePath httpMethod statusCode ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_method_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=str(statusCode)) # future lint: disable=blacklisted-function return {'deleted': True} return {'deleted': False, 'error': 'no such resource'} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
python
def delete_api_method_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Delete API method response for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_method_response restApiId resourcePath httpMethod statusCode ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) conn.delete_method_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=str(statusCode)) # future lint: disable=blacklisted-function return {'deleted': True} return {'deleted': False, 'error': 'no such resource'} except ClientError as e: return {'deleted': False, 'error': __utils__['boto3.get_error'](e)}
[ "def", "delete_api_method_response", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "statusCode", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "resource",...
Delete API method response for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.delete_api_method_response restApiId resourcePath httpMethod statusCode
[ "Delete", "API", "method", "response", "for", "a", "resource", "in", "the", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1028-L1050
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_method_response
def describe_api_method_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Get API method response for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_method_response restApiId resourcePath httpMethod statusCode ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.get_method_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=str(statusCode)) # future lint: disable=blacklisted-function return {'response': _convert_datetime_str(response)} return {'error': 'no such resource'} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_method_response(restApiId, resourcePath, httpMethod, statusCode, region=None, key=None, keyid=None, profile=None): ''' Get API method response for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_method_response restApiId resourcePath httpMethod statusCode ''' try: resource = describe_api_resource(restApiId, resourcePath, region=region, key=key, keyid=keyid, profile=profile).get('resource') if resource: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) response = conn.get_method_response(restApiId=restApiId, resourceId=resource['id'], httpMethod=httpMethod, statusCode=str(statusCode)) # future lint: disable=blacklisted-function return {'response': _convert_datetime_str(response)} return {'error': 'no such resource'} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_method_response", "(", "restApiId", ",", "resourcePath", ",", "httpMethod", ",", "statusCode", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "resource...
Get API method response for a resource in the given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_method_response restApiId resourcePath httpMethod statusCode
[ "Get", "API", "method", "response", "for", "a", "resource", "in", "the", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1053-L1075
train
saltstack/salt
salt/modules/boto_apigateway.py
describe_api_models
def describe_api_models(restApiId, region=None, key=None, keyid=None, profile=None): ''' Get all models for a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_models restApiId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) models = _multi_call(conn.get_models, 'items', restApiId=restApiId) return {'models': [_convert_datetime_str(model) for model in models]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
python
def describe_api_models(restApiId, region=None, key=None, keyid=None, profile=None): ''' Get all models for a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_models restApiId ''' try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) models = _multi_call(conn.get_models, 'items', restApiId=restApiId) return {'models': [_convert_datetime_str(model) for model in models]} except ClientError as e: return {'error': __utils__['boto3.get_error'](e)}
[ "def", "describe_api_models", "(", "restApiId", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "="...
Get all models for a given API CLI Example: .. code-block:: bash salt myminion boto_apigateway.describe_api_models restApiId
[ "Get", "all", "models", "for", "a", "given", "API" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_apigateway.py#L1078-L1094
train