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/modules/highstate_doc.py
render
def render(jinja_template_text=None, jinja_template_function='highstate_doc.markdown_default_jinja_template', **kwargs): ''' Render highstate to a text format (default Markdown) if `jinja_template_text` is not set, `jinja_template_function` is used. jinja_template_text: jinja text that the render uses to create the document. jinja_template_function: a salt module call that returns template text. options: highstate_doc.markdown_basic_jinja_template highstate_doc.markdown_default_jinja_template highstate_doc.markdown_full_jinja_template ''' config = _get_config(**kwargs) lowstates = proccess_lowstates(**kwargs) # TODO: __env__, context = { 'saltenv': None, 'config': config, 'lowstates': lowstates, 'salt': __salt__, 'pillar': __pillar__, 'grains': __grains__, 'opts': __opts__, 'kwargs': kwargs, } template_text = jinja_template_text if template_text is None and jinja_template_function: template_text = __salt__[jinja_template_function](**kwargs) if template_text is None: raise Exception('No jinja template text') txt = tpl.render_jinja_tmpl(template_text, context, tmplpath=None) # after proccessing the template replace passwords or other data. rt = config.get('replace_text_regex') for r in rt: txt = re.sub(r, rt[r], txt) return txt
python
def render(jinja_template_text=None, jinja_template_function='highstate_doc.markdown_default_jinja_template', **kwargs): ''' Render highstate to a text format (default Markdown) if `jinja_template_text` is not set, `jinja_template_function` is used. jinja_template_text: jinja text that the render uses to create the document. jinja_template_function: a salt module call that returns template text. options: highstate_doc.markdown_basic_jinja_template highstate_doc.markdown_default_jinja_template highstate_doc.markdown_full_jinja_template ''' config = _get_config(**kwargs) lowstates = proccess_lowstates(**kwargs) # TODO: __env__, context = { 'saltenv': None, 'config': config, 'lowstates': lowstates, 'salt': __salt__, 'pillar': __pillar__, 'grains': __grains__, 'opts': __opts__, 'kwargs': kwargs, } template_text = jinja_template_text if template_text is None and jinja_template_function: template_text = __salt__[jinja_template_function](**kwargs) if template_text is None: raise Exception('No jinja template text') txt = tpl.render_jinja_tmpl(template_text, context, tmplpath=None) # after proccessing the template replace passwords or other data. rt = config.get('replace_text_regex') for r in rt: txt = re.sub(r, rt[r], txt) return txt
[ "def", "render", "(", "jinja_template_text", "=", "None", ",", "jinja_template_function", "=", "'highstate_doc.markdown_default_jinja_template'", ",", "*", "*", "kwargs", ")", ":", "config", "=", "_get_config", "(", "*", "*", "kwargs", ")", "lowstates", "=", "proc...
Render highstate to a text format (default Markdown) if `jinja_template_text` is not set, `jinja_template_function` is used. jinja_template_text: jinja text that the render uses to create the document. jinja_template_function: a salt module call that returns template text. options: highstate_doc.markdown_basic_jinja_template highstate_doc.markdown_default_jinja_template highstate_doc.markdown_full_jinja_template
[ "Render", "highstate", "to", "a", "text", "format", "(", "default", "Markdown", ")" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/highstate_doc.py#L424-L461
train
saltstack/salt
salt/modules/highstate_doc.py
proccess_lowstates
def proccess_lowstates(**kwargs): ''' return proccessed lowstate data that was not blacklisted render_module_function is used to provide your own. defaults to from_lowstate ''' states = [] config = _get_config(**kwargs) proccesser = config.get('proccesser') ls = __salt__['state.show_lowstate']() if not isinstance(ls, list): raise Exception('ERROR: to see details run: [salt-call state.show_lowstate] <-----***-SEE-***') else: if ls: if not isinstance(ls[0], dict): raise Exception('ERROR: to see details run: [salt-call state.show_lowstate] <-----***-SEE-***') for s in ls: if _blacklist_filter(s, config): continue doc = __salt__[proccesser](s, config, **kwargs) states.append(doc) return states
python
def proccess_lowstates(**kwargs): ''' return proccessed lowstate data that was not blacklisted render_module_function is used to provide your own. defaults to from_lowstate ''' states = [] config = _get_config(**kwargs) proccesser = config.get('proccesser') ls = __salt__['state.show_lowstate']() if not isinstance(ls, list): raise Exception('ERROR: to see details run: [salt-call state.show_lowstate] <-----***-SEE-***') else: if ls: if not isinstance(ls[0], dict): raise Exception('ERROR: to see details run: [salt-call state.show_lowstate] <-----***-SEE-***') for s in ls: if _blacklist_filter(s, config): continue doc = __salt__[proccesser](s, config, **kwargs) states.append(doc) return states
[ "def", "proccess_lowstates", "(", "*", "*", "kwargs", ")", ":", "states", "=", "[", "]", "config", "=", "_get_config", "(", "*", "*", "kwargs", ")", "proccesser", "=", "config", ".", "get", "(", "'proccesser'", ")", "ls", "=", "__salt__", "[", "'state....
return proccessed lowstate data that was not blacklisted render_module_function is used to provide your own. defaults to from_lowstate
[ "return", "proccessed", "lowstate", "data", "that", "was", "not", "blacklisted" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/highstate_doc.py#L477-L501
train
saltstack/salt
salt/modules/highstate_doc.py
_state_data_to_yaml_string
def _state_data_to_yaml_string(data, whitelist=None, blacklist=None): ''' return a data dict in yaml string format. ''' y = {} if blacklist is None: # TODO: use salt defined STATE_REQUISITE_IN_KEYWORDS STATE_RUNTIME_KEYWORDS STATE_INTERNAL_KEYWORDS blacklist = ['__env__', '__id__', '__sls__', 'fun', 'name', 'context', 'order', 'state', 'require', 'require_in', 'watch', 'watch_in'] kset = set(data.keys()) if blacklist: kset -= set(blacklist) if whitelist: kset &= set(whitelist) for k in kset: y[k] = data[k] if not y: return None return salt.utils.yaml.safe_dump(y, default_flow_style=False)
python
def _state_data_to_yaml_string(data, whitelist=None, blacklist=None): ''' return a data dict in yaml string format. ''' y = {} if blacklist is None: # TODO: use salt defined STATE_REQUISITE_IN_KEYWORDS STATE_RUNTIME_KEYWORDS STATE_INTERNAL_KEYWORDS blacklist = ['__env__', '__id__', '__sls__', 'fun', 'name', 'context', 'order', 'state', 'require', 'require_in', 'watch', 'watch_in'] kset = set(data.keys()) if blacklist: kset -= set(blacklist) if whitelist: kset &= set(whitelist) for k in kset: y[k] = data[k] if not y: return None return salt.utils.yaml.safe_dump(y, default_flow_style=False)
[ "def", "_state_data_to_yaml_string", "(", "data", ",", "whitelist", "=", "None", ",", "blacklist", "=", "None", ")", ":", "y", "=", "{", "}", "if", "blacklist", "is", "None", ":", "# TODO: use salt defined STATE_REQUISITE_IN_KEYWORDS STATE_RUNTIME_KEYWORDS STATE_INTER...
return a data dict in yaml string format.
[ "return", "a", "data", "dict", "in", "yaml", "string", "format", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/highstate_doc.py#L504-L521
train
saltstack/salt
salt/modules/highstate_doc.py
_format_markdown_requisite
def _format_markdown_requisite(state, stateid, makelink=True): ''' format requisite as a link users can click ''' fmt_id = '{0}: {1}'.format(state, stateid) if makelink: return ' * [{0}](#{1})\n'.format(fmt_id, _format_markdown_link(fmt_id)) else: return ' * `{0}`\n'.format(fmt_id)
python
def _format_markdown_requisite(state, stateid, makelink=True): ''' format requisite as a link users can click ''' fmt_id = '{0}: {1}'.format(state, stateid) if makelink: return ' * [{0}](#{1})\n'.format(fmt_id, _format_markdown_link(fmt_id)) else: return ' * `{0}`\n'.format(fmt_id)
[ "def", "_format_markdown_requisite", "(", "state", ",", "stateid", ",", "makelink", "=", "True", ")", ":", "fmt_id", "=", "'{0}: {1}'", ".", "format", "(", "state", ",", "stateid", ")", "if", "makelink", ":", "return", "' * [{0}](#{1})\\n'", ".", "format", "...
format requisite as a link users can click
[ "format", "requisite", "as", "a", "link", "users", "can", "click" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/highstate_doc.py#L569-L577
train
saltstack/salt
salt/modules/highstate_doc.py
proccesser_markdown
def proccesser_markdown(lowstate_item, config, **kwargs): ''' Takes low state data and returns a dict of proccessed data that is by default used in a jinja template when rendering a markdown highstate_doc. This `lowstate_item_markdown` given a lowstate item, returns a dict like: .. code-block:: yaml vars: # the raw lowstate_item that was proccessed id: # the 'id' of the state. id_full: # combo of the state type and id "state: id" state: # name of the salt state module function: # name of the state function name: # value of 'name:' passed to the salt state module state_function: # the state name and function name markdown: # text data to describe a state requisites: # requisite like [watch_in, require_in] details: # state name, parameters and other details like file contents ''' # TODO: switch or ... ext call. s = lowstate_item state_function = '{0}.{1}'.format(s['state'], s['fun']) id_full = '{0}: {1}'.format(s['state'], s['__id__']) # TODO: use salt defined STATE_REQUISITE_IN_KEYWORDS requisites = '' if s.get('watch'): requisites += 'run or update after changes in:\n' for w in s.get('watch', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) requisites += '\n' if s.get('watch_in'): requisites += 'after changes, run or update:\n' for w in s.get('watch_in', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) requisites += '\n' if s.get('require') and s.get('require'): requisites += 'require:\n' for w in s.get('require', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) requisites += '\n' if s.get('require_in'): requisites += 'required in:\n' for w in s.get('require_in', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) requisites += '\n' details = '' if state_function == 'highstate_doc.note': if 'contents' in s: details += '\n{0}\n'.format(s['contents']) if 'source' in s: text = __salt__['cp.get_file_str'](s['source']) if text: details += '\n{0}\n'.format(text) else: details += '\n{0}\n'.format('ERROR: opening {0}'.format(s['source'])) if state_function == 'pkg.installed': pkgs = s.get('pkgs', s.get('name')) details += '\n```\ninstall: {0}\n```\n'.format(pkgs) if state_function == 'file.recurse': details += '''recurse copy of files\n''' y = _state_data_to_yaml_string(s) if y: details += '```\n{0}\n```\n'.format(y) if '!doc_recurse' in id_full: findfiles = __salt__['file.find'](path=s.get('name'), type='f') if len(findfiles) < 10 or '!doc_recurse_force' in id_full: for f in findfiles: details += _format_markdown_system_file(f, config) else: details += ''' > Skipping because more than 10 files to display.\n''' details += ''' > HINT: to force include !doc_recurse_force in state id.\n''' else: details += ''' > For more details review logs and Salt state files.\n\n''' details += ''' > HINT: for improved docs use multiple file.managed states or file.archive, git.latest. etc.\n''' details += ''' > HINT: to force doc to show all files in path add !doc_recurse .\n''' if state_function == 'file.blockreplace': if s.get('content'): details += 'ensure block of content is in file\n```\n{0}\n```\n'.format(_md_fix(s['content'])) if s.get('source'): text = '** source: ' + s.get('source') details += 'ensure block of content is in file\n```\n{0}\n```\n'.format(_md_fix(text)) if state_function == 'file.managed': details += _format_markdown_system_file(s['name'], config) # if no state doc is created use default state as yaml if not details: y = _state_data_to_yaml_string(s) if y: details += '```\n{0}```\n'.format(y) r = { 'vars': lowstate_item, 'state': s['state'], 'name': s['name'], 'function': s['fun'], 'id': s['__id__'], 'id_full': id_full, 'state_function': state_function, 'markdown': { 'requisites': requisites.decode('utf-8'), 'details': details.decode('utf-8') } } return r
python
def proccesser_markdown(lowstate_item, config, **kwargs): ''' Takes low state data and returns a dict of proccessed data that is by default used in a jinja template when rendering a markdown highstate_doc. This `lowstate_item_markdown` given a lowstate item, returns a dict like: .. code-block:: yaml vars: # the raw lowstate_item that was proccessed id: # the 'id' of the state. id_full: # combo of the state type and id "state: id" state: # name of the salt state module function: # name of the state function name: # value of 'name:' passed to the salt state module state_function: # the state name and function name markdown: # text data to describe a state requisites: # requisite like [watch_in, require_in] details: # state name, parameters and other details like file contents ''' # TODO: switch or ... ext call. s = lowstate_item state_function = '{0}.{1}'.format(s['state'], s['fun']) id_full = '{0}: {1}'.format(s['state'], s['__id__']) # TODO: use salt defined STATE_REQUISITE_IN_KEYWORDS requisites = '' if s.get('watch'): requisites += 'run or update after changes in:\n' for w in s.get('watch', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) requisites += '\n' if s.get('watch_in'): requisites += 'after changes, run or update:\n' for w in s.get('watch_in', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) requisites += '\n' if s.get('require') and s.get('require'): requisites += 'require:\n' for w in s.get('require', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) requisites += '\n' if s.get('require_in'): requisites += 'required in:\n' for w in s.get('require_in', []): requisites += _format_markdown_requisite(w.items()[0][0], w.items()[0][1]) requisites += '\n' details = '' if state_function == 'highstate_doc.note': if 'contents' in s: details += '\n{0}\n'.format(s['contents']) if 'source' in s: text = __salt__['cp.get_file_str'](s['source']) if text: details += '\n{0}\n'.format(text) else: details += '\n{0}\n'.format('ERROR: opening {0}'.format(s['source'])) if state_function == 'pkg.installed': pkgs = s.get('pkgs', s.get('name')) details += '\n```\ninstall: {0}\n```\n'.format(pkgs) if state_function == 'file.recurse': details += '''recurse copy of files\n''' y = _state_data_to_yaml_string(s) if y: details += '```\n{0}\n```\n'.format(y) if '!doc_recurse' in id_full: findfiles = __salt__['file.find'](path=s.get('name'), type='f') if len(findfiles) < 10 or '!doc_recurse_force' in id_full: for f in findfiles: details += _format_markdown_system_file(f, config) else: details += ''' > Skipping because more than 10 files to display.\n''' details += ''' > HINT: to force include !doc_recurse_force in state id.\n''' else: details += ''' > For more details review logs and Salt state files.\n\n''' details += ''' > HINT: for improved docs use multiple file.managed states or file.archive, git.latest. etc.\n''' details += ''' > HINT: to force doc to show all files in path add !doc_recurse .\n''' if state_function == 'file.blockreplace': if s.get('content'): details += 'ensure block of content is in file\n```\n{0}\n```\n'.format(_md_fix(s['content'])) if s.get('source'): text = '** source: ' + s.get('source') details += 'ensure block of content is in file\n```\n{0}\n```\n'.format(_md_fix(text)) if state_function == 'file.managed': details += _format_markdown_system_file(s['name'], config) # if no state doc is created use default state as yaml if not details: y = _state_data_to_yaml_string(s) if y: details += '```\n{0}```\n'.format(y) r = { 'vars': lowstate_item, 'state': s['state'], 'name': s['name'], 'function': s['fun'], 'id': s['__id__'], 'id_full': id_full, 'state_function': state_function, 'markdown': { 'requisites': requisites.decode('utf-8'), 'details': details.decode('utf-8') } } return r
[ "def", "proccesser_markdown", "(", "lowstate_item", ",", "config", ",", "*", "*", "kwargs", ")", ":", "# TODO: switch or ... ext call.", "s", "=", "lowstate_item", "state_function", "=", "'{0}.{1}'", ".", "format", "(", "s", "[", "'state'", "]", ",", "s", "[",...
Takes low state data and returns a dict of proccessed data that is by default used in a jinja template when rendering a markdown highstate_doc. This `lowstate_item_markdown` given a lowstate item, returns a dict like: .. code-block:: yaml vars: # the raw lowstate_item that was proccessed id: # the 'id' of the state. id_full: # combo of the state type and id "state: id" state: # name of the salt state module function: # name of the state function name: # value of 'name:' passed to the salt state module state_function: # the state name and function name markdown: # text data to describe a state requisites: # requisite like [watch_in, require_in] details: # state name, parameters and other details like file contents
[ "Takes", "low", "state", "data", "and", "returns", "a", "dict", "of", "proccessed", "data", "that", "is", "by", "default", "used", "in", "a", "jinja", "template", "when", "rendering", "a", "markdown", "highstate_doc", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/highstate_doc.py#L580-L692
train
saltstack/salt
salt/utils/win_osinfo.py
os_version_info_ex
def os_version_info_ex(): ''' Helper function to return the results of the GetVersionExW Windows API call. It is a ctypes Structure that contains Windows OS Version information. Returns: class: An instance of a class containing version info ''' if not HAS_WIN32: return class OSVersionInfo(ctypes.Structure): _fields_ = (('dwOSVersionInfoSize', DWORD), ('dwMajorVersion', DWORD), ('dwMinorVersion', DWORD), ('dwBuildNumber', DWORD), ('dwPlatformId', DWORD), ('szCSDVersion', WCHAR * 128)) def __init__(self, *args, **kwds): super(OSVersionInfo, self).__init__(*args, **kwds) self.dwOSVersionInfoSize = ctypes.sizeof(self) kernel32.GetVersionExW(ctypes.byref(self)) class OSVersionInfoEx(OSVersionInfo): _fields_ = (('wServicePackMajor', WORD), ('wServicePackMinor', WORD), ('wSuiteMask', WORD), ('wProductType', BYTE), ('wReserved', BYTE)) return OSVersionInfoEx()
python
def os_version_info_ex(): ''' Helper function to return the results of the GetVersionExW Windows API call. It is a ctypes Structure that contains Windows OS Version information. Returns: class: An instance of a class containing version info ''' if not HAS_WIN32: return class OSVersionInfo(ctypes.Structure): _fields_ = (('dwOSVersionInfoSize', DWORD), ('dwMajorVersion', DWORD), ('dwMinorVersion', DWORD), ('dwBuildNumber', DWORD), ('dwPlatformId', DWORD), ('szCSDVersion', WCHAR * 128)) def __init__(self, *args, **kwds): super(OSVersionInfo, self).__init__(*args, **kwds) self.dwOSVersionInfoSize = ctypes.sizeof(self) kernel32.GetVersionExW(ctypes.byref(self)) class OSVersionInfoEx(OSVersionInfo): _fields_ = (('wServicePackMajor', WORD), ('wServicePackMinor', WORD), ('wSuiteMask', WORD), ('wProductType', BYTE), ('wReserved', BYTE)) return OSVersionInfoEx()
[ "def", "os_version_info_ex", "(", ")", ":", "if", "not", "HAS_WIN32", ":", "return", "class", "OSVersionInfo", "(", "ctypes", ".", "Structure", ")", ":", "_fields_", "=", "(", "(", "'dwOSVersionInfoSize'", ",", "DWORD", ")", ",", "(", "'dwMajorVersion'", ","...
Helper function to return the results of the GetVersionExW Windows API call. It is a ctypes Structure that contains Windows OS Version information. Returns: class: An instance of a class containing version info
[ "Helper", "function", "to", "return", "the", "results", "of", "the", "GetVersionExW", "Windows", "API", "call", ".", "It", "is", "a", "ctypes", "Structure", "that", "contains", "Windows", "OS", "Version", "information", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_osinfo.py#L35-L66
train
saltstack/salt
salt/utils/win_osinfo.py
get_join_info
def get_join_info(): ''' Gets information about the domain/workgroup. This will tell you if the system is joined to a domain or a workgroup .. version-added:: 2018.3.4 Returns: dict: A dictionary containing the domain/workgroup and it's status ''' info = win32net.NetGetJoinInformation() status = {win32netcon.NetSetupUnknown: 'Unknown', win32netcon.NetSetupUnjoined: 'Unjoined', win32netcon.NetSetupWorkgroupName: 'Workgroup', win32netcon.NetSetupDomainName: 'Domain'} return {'Domain': info[0], 'DomainType': status[info[1]]}
python
def get_join_info(): ''' Gets information about the domain/workgroup. This will tell you if the system is joined to a domain or a workgroup .. version-added:: 2018.3.4 Returns: dict: A dictionary containing the domain/workgroup and it's status ''' info = win32net.NetGetJoinInformation() status = {win32netcon.NetSetupUnknown: 'Unknown', win32netcon.NetSetupUnjoined: 'Unjoined', win32netcon.NetSetupWorkgroupName: 'Workgroup', win32netcon.NetSetupDomainName: 'Domain'} return {'Domain': info[0], 'DomainType': status[info[1]]}
[ "def", "get_join_info", "(", ")", ":", "info", "=", "win32net", ".", "NetGetJoinInformation", "(", ")", "status", "=", "{", "win32netcon", ".", "NetSetupUnknown", ":", "'Unknown'", ",", "win32netcon", ".", "NetSetupUnjoined", ":", "'Unjoined'", ",", "win32netcon...
Gets information about the domain/workgroup. This will tell you if the system is joined to a domain or a workgroup .. version-added:: 2018.3.4 Returns: dict: A dictionary containing the domain/workgroup and it's status
[ "Gets", "information", "about", "the", "domain", "/", "workgroup", ".", "This", "will", "tell", "you", "if", "the", "system", "is", "joined", "to", "a", "domain", "or", "a", "workgroup" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/win_osinfo.py#L83-L99
train
saltstack/salt
salt/modules/mac_user.py
_dscl
def _dscl(cmd, ctype='create'): ''' Run a dscl -create command ''' if __grains__['osrelease_info'] < (10, 8): source, noderoot = '.', '' else: source, noderoot = 'localhost', '/Local/Default' if noderoot: cmd[0] = noderoot + cmd[0] return __salt__['cmd.run_all']( ['dscl', source, '-' + ctype] + cmd, output_loglevel='quiet' if ctype == 'passwd' else 'debug', python_shell=False )
python
def _dscl(cmd, ctype='create'): ''' Run a dscl -create command ''' if __grains__['osrelease_info'] < (10, 8): source, noderoot = '.', '' else: source, noderoot = 'localhost', '/Local/Default' if noderoot: cmd[0] = noderoot + cmd[0] return __salt__['cmd.run_all']( ['dscl', source, '-' + ctype] + cmd, output_loglevel='quiet' if ctype == 'passwd' else 'debug', python_shell=False )
[ "def", "_dscl", "(", "cmd", ",", "ctype", "=", "'create'", ")", ":", "if", "__grains__", "[", "'osrelease_info'", "]", "<", "(", "10", ",", "8", ")", ":", "source", ",", "noderoot", "=", "'.'", ",", "''", "else", ":", "source", ",", "noderoot", "="...
Run a dscl -create command
[ "Run", "a", "dscl", "-", "create", "command" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L56-L71
train
saltstack/salt
salt/modules/mac_user.py
add
def add(name, uid=None, gid=None, groups=None, home=None, shell=None, fullname=None, createhome=True, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' if info(name): raise CommandExecutionError('User \'{0}\' already exists'.format(name)) if salt.utils.stringutils.contains_whitespace(name): raise SaltInvocationError('Username cannot contain whitespace') if uid is None: uid = _first_avail_uid() if gid is None: gid = 20 # gid 20 == 'staff', the default group if home is None: home = '/Users/{0}'.format(name) if shell is None: shell = '/bin/bash' if fullname is None: fullname = '' if not isinstance(uid, int): raise SaltInvocationError('uid must be an integer') if not isinstance(gid, int): raise SaltInvocationError('gid must be an integer') name_path = '/Users/{0}'.format(name) _dscl([name_path, 'UniqueID', uid]) _dscl([name_path, 'PrimaryGroupID', gid]) _dscl([name_path, 'UserShell', shell]) _dscl([name_path, 'NFSHomeDirectory', home]) _dscl([name_path, 'RealName', fullname]) # Make sure home directory exists if createhome: __salt__['file.mkdir'](home, user=uid, group=gid) # dscl buffers changes, sleep before setting group membership time.sleep(1) if groups: chgroups(name, groups) return True
python
def add(name, uid=None, gid=None, groups=None, home=None, shell=None, fullname=None, createhome=True, **kwargs): ''' Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell> ''' if info(name): raise CommandExecutionError('User \'{0}\' already exists'.format(name)) if salt.utils.stringutils.contains_whitespace(name): raise SaltInvocationError('Username cannot contain whitespace') if uid is None: uid = _first_avail_uid() if gid is None: gid = 20 # gid 20 == 'staff', the default group if home is None: home = '/Users/{0}'.format(name) if shell is None: shell = '/bin/bash' if fullname is None: fullname = '' if not isinstance(uid, int): raise SaltInvocationError('uid must be an integer') if not isinstance(gid, int): raise SaltInvocationError('gid must be an integer') name_path = '/Users/{0}'.format(name) _dscl([name_path, 'UniqueID', uid]) _dscl([name_path, 'PrimaryGroupID', gid]) _dscl([name_path, 'UserShell', shell]) _dscl([name_path, 'NFSHomeDirectory', home]) _dscl([name_path, 'RealName', fullname]) # Make sure home directory exists if createhome: __salt__['file.mkdir'](home, user=uid, group=gid) # dscl buffers changes, sleep before setting group membership time.sleep(1) if groups: chgroups(name, groups) return True
[ "def", "add", "(", "name", ",", "uid", "=", "None", ",", "gid", "=", "None", ",", "groups", "=", "None", ",", "home", "=", "None", ",", "shell", "=", "None", ",", "fullname", "=", "None", ",", "createhome", "=", "True", ",", "*", "*", "kwargs", ...
Add a user to the minion CLI Example: .. code-block:: bash salt '*' user.add name <uid> <gid> <groups> <home> <shell>
[ "Add", "a", "user", "to", "the", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L81-L136
train
saltstack/salt
salt/modules/mac_user.py
delete
def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.stringutils.contains_whitespace(name): raise SaltInvocationError('Username cannot contain whitespace') if not info(name): return True # force is added for compatibility with user.absent state function if force: log.warning('force option is unsupported on MacOS, ignoring') # remove home directory from filesystem if remove: __salt__['file.remove'](info(name)['home']) # Remove from any groups other than primary group. Needs to be done since # group membership is managed separately from users and an entry for the # user will persist even after the user is removed. chgroups(name, ()) return _dscl(['/Users/{0}'.format(name)], ctype='delete')['retcode'] == 0
python
def delete(name, remove=False, force=False): ''' Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True ''' if salt.utils.stringutils.contains_whitespace(name): raise SaltInvocationError('Username cannot contain whitespace') if not info(name): return True # force is added for compatibility with user.absent state function if force: log.warning('force option is unsupported on MacOS, ignoring') # remove home directory from filesystem if remove: __salt__['file.remove'](info(name)['home']) # Remove from any groups other than primary group. Needs to be done since # group membership is managed separately from users and an entry for the # user will persist even after the user is removed. chgroups(name, ()) return _dscl(['/Users/{0}'.format(name)], ctype='delete')['retcode'] == 0
[ "def", "delete", "(", "name", ",", "remove", "=", "False", ",", "force", "=", "False", ")", ":", "if", "salt", ".", "utils", ".", "stringutils", ".", "contains_whitespace", "(", "name", ")", ":", "raise", "SaltInvocationError", "(", "'Username cannot contain...
Remove a user from the minion CLI Example: .. code-block:: bash salt '*' user.delete name remove=True force=True
[ "Remove", "a", "user", "from", "the", "minion" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L139-L166
train
saltstack/salt
salt/modules/mac_user.py
getent
def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(_format_info(data)) __context__['user.getent'] = ret return ret
python
def getent(refresh=False): ''' Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent ''' if 'user.getent' in __context__ and not refresh: return __context__['user.getent'] ret = [] for data in pwd.getpwall(): ret.append(_format_info(data)) __context__['user.getent'] = ret return ret
[ "def", "getent", "(", "refresh", "=", "False", ")", ":", "if", "'user.getent'", "in", "__context__", "and", "not", "refresh", ":", "return", "__context__", "[", "'user.getent'", "]", "ret", "=", "[", "]", "for", "data", "in", "pwd", ".", "getpwall", "(",...
Return the list of all info for all users CLI Example: .. code-block:: bash salt '*' user.getent
[ "Return", "the", "list", "of", "all", "info", "for", "all", "users" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L169-L186
train
saltstack/salt
salt/modules/mac_user.py
chuid
def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' if not isinstance(uid, int): raise SaltInvocationError('uid must be an integer') pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if uid == pre_info['uid']: return True _dscl( ['/Users/{0}'.format(name), 'UniqueID', pre_info['uid'], uid], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(name).get('uid') == uid
python
def chuid(name, uid): ''' Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376 ''' if not isinstance(uid, int): raise SaltInvocationError('uid must be an integer') pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if uid == pre_info['uid']: return True _dscl( ['/Users/{0}'.format(name), 'UniqueID', pre_info['uid'], uid], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(name).get('uid') == uid
[ "def", "chuid", "(", "name", ",", "uid", ")", ":", "if", "not", "isinstance", "(", "uid", ",", "int", ")", ":", "raise", "SaltInvocationError", "(", "'uid must be an integer'", ")", "pre_info", "=", "info", "(", "name", ")", "if", "not", "pre_info", ":",...
Change the uid for a named user CLI Example: .. code-block:: bash salt '*' user.chuid foo 4376
[ "Change", "the", "uid", "for", "a", "named", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L189-L213
train
saltstack/salt
salt/modules/mac_user.py
chgid
def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' if not isinstance(gid, int): raise SaltInvocationError('gid must be an integer') pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if gid == pre_info['gid']: return True _dscl( ['/Users/{0}'.format(name), 'PrimaryGroupID', pre_info['gid'], gid], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(name).get('gid') == gid
python
def chgid(name, gid): ''' Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376 ''' if not isinstance(gid, int): raise SaltInvocationError('gid must be an integer') pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if gid == pre_info['gid']: return True _dscl( ['/Users/{0}'.format(name), 'PrimaryGroupID', pre_info['gid'], gid], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(name).get('gid') == gid
[ "def", "chgid", "(", "name", ",", "gid", ")", ":", "if", "not", "isinstance", "(", "gid", ",", "int", ")", ":", "raise", "SaltInvocationError", "(", "'gid must be an integer'", ")", "pre_info", "=", "info", "(", "name", ")", "if", "not", "pre_info", ":",...
Change the default group of the user CLI Example: .. code-block:: bash salt '*' user.chgid foo 4376
[ "Change", "the", "default", "group", "of", "the", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L216-L240
train
saltstack/salt
salt/modules/mac_user.py
chshell
def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if shell == pre_info['shell']: return True _dscl( ['/Users/{0}'.format(name), 'UserShell', pre_info['shell'], shell], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(name).get('shell') == shell
python
def chshell(name, shell): ''' Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh ''' pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if shell == pre_info['shell']: return True _dscl( ['/Users/{0}'.format(name), 'UserShell', pre_info['shell'], shell], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(name).get('shell') == shell
[ "def", "chshell", "(", "name", ",", "shell", ")", ":", "pre_info", "=", "info", "(", "name", ")", "if", "not", "pre_info", ":", "raise", "CommandExecutionError", "(", "'User \\'{0}\\' does not exist'", ".", "format", "(", "name", ")", ")", "if", "shell", "...
Change the default shell of the user CLI Example: .. code-block:: bash salt '*' user.chshell foo /bin/zsh
[ "Change", "the", "default", "shell", "of", "the", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L243-L265
train
saltstack/salt
salt/modules/mac_user.py
chhome
def chhome(name, home, **kwargs): ''' Change the home directory of the user CLI Example: .. code-block:: bash salt '*' user.chhome foo /Users/foo ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) persist = kwargs.pop('persist', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if persist: log.info('Ignoring unsupported \'persist\' argument to user.chhome') pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if home == pre_info['home']: return True _dscl( ['/Users/{0}'.format(name), 'NFSHomeDirectory', pre_info['home'], home], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(name).get('home') == home
python
def chhome(name, home, **kwargs): ''' Change the home directory of the user CLI Example: .. code-block:: bash salt '*' user.chhome foo /Users/foo ''' kwargs = salt.utils.args.clean_kwargs(**kwargs) persist = kwargs.pop('persist', False) if kwargs: salt.utils.args.invalid_kwargs(kwargs) if persist: log.info('Ignoring unsupported \'persist\' argument to user.chhome') pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if home == pre_info['home']: return True _dscl( ['/Users/{0}'.format(name), 'NFSHomeDirectory', pre_info['home'], home], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(name).get('home') == home
[ "def", "chhome", "(", "name", ",", "home", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "salt", ".", "utils", ".", "args", ".", "clean_kwargs", "(", "*", "*", "kwargs", ")", "persist", "=", "kwargs", ".", "pop", "(", "'persist'", ",", "False",...
Change the home directory of the user CLI Example: .. code-block:: bash salt '*' user.chhome foo /Users/foo
[ "Change", "the", "home", "directory", "of", "the", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L268-L298
train
saltstack/salt
salt/modules/mac_user.py
chfullname
def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo 'Foo Bar' ''' fullname = salt.utils.data.decode(fullname) pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) pre_info['fullname'] = salt.utils.data.decode(pre_info['fullname']) if fullname == pre_info['fullname']: return True _dscl( ['/Users/{0}'.format(name), 'RealName', fullname], # use a 'create' command, because a 'change' command would fail if # current fullname is an empty string. The 'create' will just overwrite # this field. ctype='create' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) current = salt.utils.data.decode(info(name).get('fullname')) return current == fullname
python
def chfullname(name, fullname): ''' Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo 'Foo Bar' ''' fullname = salt.utils.data.decode(fullname) pre_info = info(name) if not pre_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) pre_info['fullname'] = salt.utils.data.decode(pre_info['fullname']) if fullname == pre_info['fullname']: return True _dscl( ['/Users/{0}'.format(name), 'RealName', fullname], # use a 'create' command, because a 'change' command would fail if # current fullname is an empty string. The 'create' will just overwrite # this field. ctype='create' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) current = salt.utils.data.decode(info(name).get('fullname')) return current == fullname
[ "def", "chfullname", "(", "name", ",", "fullname", ")", ":", "fullname", "=", "salt", ".", "utils", ".", "data", ".", "decode", "(", "fullname", ")", "pre_info", "=", "info", "(", "name", ")", "if", "not", "pre_info", ":", "raise", "CommandExecutionError...
Change the user's Full Name CLI Example: .. code-block:: bash salt '*' user.chfullname foo 'Foo Bar'
[ "Change", "the", "user", "s", "Full", "Name" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L301-L330
train
saltstack/salt
salt/modules/mac_user.py
chgroups
def chgroups(name, groups, append=False): ''' Change the groups to which the user belongs. Note that the user's primary group does not have to be one of the groups passed, membership in the user's primary group is automatically assumed. groups Groups to which the user should belong, can be passed either as a python list or a comma-separated string append Instead of removing user from groups not included in the ``groups`` parameter, just add user to any groups for which they are not members CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root ''' ### NOTE: **args isn't used here but needs to be included in this ### function for compatibility with the user.present state uinfo = info(name) if not uinfo: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if isinstance(groups, string_types): groups = groups.split(',') bad_groups = [x for x in groups if salt.utils.stringutils.contains_whitespace(x)] if bad_groups: raise SaltInvocationError( 'Invalid group name(s): {0}'.format(', '.join(bad_groups)) ) ugrps = set(list_groups(name)) desired = set(six.text_type(x) for x in groups if bool(six.text_type(x))) primary_group = __salt__['file.gid_to_group'](uinfo['gid']) if primary_group: desired.add(primary_group) if ugrps == desired: return True # Add groups from which user is missing for group in desired - ugrps: _dscl( ['/Groups/{0}'.format(group), 'GroupMembership', name], ctype='append' ) if not append: # Remove from extra groups for group in ugrps - desired: _dscl( ['/Groups/{0}'.format(group), 'GroupMembership', name], ctype='delete' ) time.sleep(1) return set(list_groups(name)) == desired
python
def chgroups(name, groups, append=False): ''' Change the groups to which the user belongs. Note that the user's primary group does not have to be one of the groups passed, membership in the user's primary group is automatically assumed. groups Groups to which the user should belong, can be passed either as a python list or a comma-separated string append Instead of removing user from groups not included in the ``groups`` parameter, just add user to any groups for which they are not members CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root ''' ### NOTE: **args isn't used here but needs to be included in this ### function for compatibility with the user.present state uinfo = info(name) if not uinfo: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) if isinstance(groups, string_types): groups = groups.split(',') bad_groups = [x for x in groups if salt.utils.stringutils.contains_whitespace(x)] if bad_groups: raise SaltInvocationError( 'Invalid group name(s): {0}'.format(', '.join(bad_groups)) ) ugrps = set(list_groups(name)) desired = set(six.text_type(x) for x in groups if bool(six.text_type(x))) primary_group = __salt__['file.gid_to_group'](uinfo['gid']) if primary_group: desired.add(primary_group) if ugrps == desired: return True # Add groups from which user is missing for group in desired - ugrps: _dscl( ['/Groups/{0}'.format(group), 'GroupMembership', name], ctype='append' ) if not append: # Remove from extra groups for group in ugrps - desired: _dscl( ['/Groups/{0}'.format(group), 'GroupMembership', name], ctype='delete' ) time.sleep(1) return set(list_groups(name)) == desired
[ "def", "chgroups", "(", "name", ",", "groups", ",", "append", "=", "False", ")", ":", "### NOTE: **args isn't used here but needs to be included in this", "### function for compatibility with the user.present state", "uinfo", "=", "info", "(", "name", ")", "if", "not", "u...
Change the groups to which the user belongs. Note that the user's primary group does not have to be one of the groups passed, membership in the user's primary group is automatically assumed. groups Groups to which the user should belong, can be passed either as a python list or a comma-separated string append Instead of removing user from groups not included in the ``groups`` parameter, just add user to any groups for which they are not members CLI Example: .. code-block:: bash salt '*' user.chgroups foo wheel,root
[ "Change", "the", "groups", "to", "which", "the", "user", "belongs", ".", "Note", "that", "the", "user", "s", "primary", "group", "does", "not", "have", "to", "be", "one", "of", "the", "groups", "passed", "membership", "in", "the", "user", "s", "primary",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L333-L387
train
saltstack/salt
salt/modules/mac_user.py
_format_info
def _format_info(data): ''' Return user information in a pretty way ''' return {'gid': data.pw_gid, 'groups': list_groups(data.pw_name), 'home': data.pw_dir, 'name': data.pw_name, 'shell': data.pw_shell, 'uid': data.pw_uid, 'fullname': data.pw_gecos}
python
def _format_info(data): ''' Return user information in a pretty way ''' return {'gid': data.pw_gid, 'groups': list_groups(data.pw_name), 'home': data.pw_dir, 'name': data.pw_name, 'shell': data.pw_shell, 'uid': data.pw_uid, 'fullname': data.pw_gecos}
[ "def", "_format_info", "(", "data", ")", ":", "return", "{", "'gid'", ":", "data", ".", "pw_gid", ",", "'groups'", ":", "list_groups", "(", "data", ".", "pw_name", ")", ",", "'home'", ":", "data", ".", "pw_dir", ",", "'name'", ":", "data", ".", "pw_n...
Return user information in a pretty way
[ "Return", "user", "information", "in", "a", "pretty", "way" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L408-L418
train
saltstack/salt
salt/modules/mac_user.py
list_groups
def list_groups(name): ''' Return a list of groups the named user belongs to. name The name of the user for which to list groups. Starting in Salt 2016.11.0, all groups for the user, including groups beginning with an underscore will be listed. .. versionchanged:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' groups = [group for group in salt.utils.user.get_group_list(name)] return groups
python
def list_groups(name): ''' Return a list of groups the named user belongs to. name The name of the user for which to list groups. Starting in Salt 2016.11.0, all groups for the user, including groups beginning with an underscore will be listed. .. versionchanged:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' user.list_groups foo ''' groups = [group for group in salt.utils.user.get_group_list(name)] return groups
[ "def", "list_groups", "(", "name", ")", ":", "groups", "=", "[", "group", "for", "group", "in", "salt", ".", "utils", ".", "user", ".", "get_group_list", "(", "name", ")", "]", "return", "groups" ]
Return a list of groups the named user belongs to. name The name of the user for which to list groups. Starting in Salt 2016.11.0, all groups for the user, including groups beginning with an underscore will be listed. .. versionchanged:: 2016.11.0 CLI Example: .. code-block:: bash salt '*' user.list_groups foo
[ "Return", "a", "list", "of", "groups", "the", "named", "user", "belongs", "to", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L437-L456
train
saltstack/salt
salt/modules/mac_user.py
rename
def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) _dscl( ['/Users/{0}'.format(name), 'RecordName', name, new_name], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(new_name).get('RecordName') == new_name
python
def rename(name, new_name): ''' Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name ''' current_info = info(name) if not current_info: raise CommandExecutionError('User \'{0}\' does not exist'.format(name)) new_info = info(new_name) if new_info: raise CommandExecutionError( 'User \'{0}\' already exists'.format(new_name) ) _dscl( ['/Users/{0}'.format(name), 'RecordName', name, new_name], ctype='change' ) # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) return info(new_name).get('RecordName') == new_name
[ "def", "rename", "(", "name", ",", "new_name", ")", ":", "current_info", "=", "info", "(", "name", ")", "if", "not", "current_info", ":", "raise", "CommandExecutionError", "(", "'User \\'{0}\\' does not exist'", ".", "format", "(", "name", ")", ")", "new_info"...
Change the username for a named user CLI Example: .. code-block:: bash salt '*' user.rename name new_name
[ "Change", "the", "username", "for", "a", "named", "user" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L473-L498
train
saltstack/salt
salt/modules/mac_user.py
get_auto_login
def get_auto_login(): ''' .. versionadded:: 2016.3.0 Gets the current setting for Auto Login :return: If enabled, returns the user name, otherwise returns False :rtype: str, bool CLI Example: .. code-block:: bash salt '*' user.get_auto_login ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.loginwindow.plist', 'autoLoginUser'] ret = __salt__['cmd.run_all'](cmd, ignore_retcode=True) return False if ret['retcode'] else ret['stdout']
python
def get_auto_login(): ''' .. versionadded:: 2016.3.0 Gets the current setting for Auto Login :return: If enabled, returns the user name, otherwise returns False :rtype: str, bool CLI Example: .. code-block:: bash salt '*' user.get_auto_login ''' cmd = ['defaults', 'read', '/Library/Preferences/com.apple.loginwindow.plist', 'autoLoginUser'] ret = __salt__['cmd.run_all'](cmd, ignore_retcode=True) return False if ret['retcode'] else ret['stdout']
[ "def", "get_auto_login", "(", ")", ":", "cmd", "=", "[", "'defaults'", ",", "'read'", ",", "'/Library/Preferences/com.apple.loginwindow.plist'", ",", "'autoLoginUser'", "]", "ret", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ",", "ignore_retcode", "=",...
.. versionadded:: 2016.3.0 Gets the current setting for Auto Login :return: If enabled, returns the user name, otherwise returns False :rtype: str, bool CLI Example: .. code-block:: bash salt '*' user.get_auto_login
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L501-L521
train
saltstack/salt
salt/modules/mac_user.py
_kcpassword
def _kcpassword(password): ''' Internal function for obfuscating the password used for AutoLogin This is later written as the contents of the ``/etc/kcpassword`` file .. versionadded:: 2017.7.3 Adapted from: https://github.com/timsutton/osx-vm-templates/blob/master/scripts/support/set_kcpassword.py Args: password(str): The password to obfuscate Returns: str: The obfuscated password ''' # The magic 11 bytes - these are just repeated # 0x7D 0x89 0x52 0x23 0xD2 0xBC 0xDD 0xEA 0xA3 0xB9 0x1F key = [125, 137, 82, 35, 210, 188, 221, 234, 163, 185, 31] key_len = len(key) # Convert each character to a byte password = list(map(ord, password)) # pad password length out to an even multiple of key length remainder = len(password) % key_len if remainder > 0: password = password + [0] * (key_len - remainder) # Break the password into chunks the size of len(key) (11) for chunk_index in range(0, len(password), len(key)): # Reset the key_index to 0 for each iteration key_index = 0 # Do an XOR on each character of that chunk of the password with the # corresponding item in the key # The length of the password, or the length of the key, whichever is # smaller for password_index in range(chunk_index, min(chunk_index + len(key), len(password))): password[password_index] = password[password_index] ^ key[key_index] key_index += 1 # Convert each byte back to a character password = list(map(chr, password)) return b''.join(salt.utils.data.encode(password))
python
def _kcpassword(password): ''' Internal function for obfuscating the password used for AutoLogin This is later written as the contents of the ``/etc/kcpassword`` file .. versionadded:: 2017.7.3 Adapted from: https://github.com/timsutton/osx-vm-templates/blob/master/scripts/support/set_kcpassword.py Args: password(str): The password to obfuscate Returns: str: The obfuscated password ''' # The magic 11 bytes - these are just repeated # 0x7D 0x89 0x52 0x23 0xD2 0xBC 0xDD 0xEA 0xA3 0xB9 0x1F key = [125, 137, 82, 35, 210, 188, 221, 234, 163, 185, 31] key_len = len(key) # Convert each character to a byte password = list(map(ord, password)) # pad password length out to an even multiple of key length remainder = len(password) % key_len if remainder > 0: password = password + [0] * (key_len - remainder) # Break the password into chunks the size of len(key) (11) for chunk_index in range(0, len(password), len(key)): # Reset the key_index to 0 for each iteration key_index = 0 # Do an XOR on each character of that chunk of the password with the # corresponding item in the key # The length of the password, or the length of the key, whichever is # smaller for password_index in range(chunk_index, min(chunk_index + len(key), len(password))): password[password_index] = password[password_index] ^ key[key_index] key_index += 1 # Convert each byte back to a character password = list(map(chr, password)) return b''.join(salt.utils.data.encode(password))
[ "def", "_kcpassword", "(", "password", ")", ":", "# The magic 11 bytes - these are just repeated", "# 0x7D 0x89 0x52 0x23 0xD2 0xBC 0xDD 0xEA 0xA3 0xB9 0x1F", "key", "=", "[", "125", ",", "137", ",", "82", ",", "35", ",", "210", ",", "188", ",", "221", ",", "234", ...
Internal function for obfuscating the password used for AutoLogin This is later written as the contents of the ``/etc/kcpassword`` file .. versionadded:: 2017.7.3 Adapted from: https://github.com/timsutton/osx-vm-templates/blob/master/scripts/support/set_kcpassword.py Args: password(str): The password to obfuscate Returns: str: The obfuscated password
[ "Internal", "function", "for", "obfuscating", "the", "password", "used", "for", "AutoLogin", "This", "is", "later", "written", "as", "the", "contents", "of", "the", "/", "etc", "/", "kcpassword", "file" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L524-L571
train
saltstack/salt
salt/modules/mac_user.py
enable_auto_login
def enable_auto_login(name, password): ''' .. versionadded:: 2016.3.0 Configures the machine to auto login with the specified user Args: name (str): The user account use for auto login password (str): The password to user for auto login .. versionadded:: 2017.7.3 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' user.enable_auto_login stevej ''' # Make the entry into the defaults file cmd = ['defaults', 'write', '/Library/Preferences/com.apple.loginwindow.plist', 'autoLoginUser', name] __salt__['cmd.run'](cmd) current = get_auto_login() # Create/Update the kcpassword file with an obfuscated password o_password = _kcpassword(password=password) with salt.utils.files.set_umask(0o077): with salt.utils.files.fopen('/etc/kcpassword', 'w' if six.PY2 else 'wb') as fd: fd.write(o_password) return current if isinstance(current, bool) else current.lower() == name.lower()
python
def enable_auto_login(name, password): ''' .. versionadded:: 2016.3.0 Configures the machine to auto login with the specified user Args: name (str): The user account use for auto login password (str): The password to user for auto login .. versionadded:: 2017.7.3 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' user.enable_auto_login stevej ''' # Make the entry into the defaults file cmd = ['defaults', 'write', '/Library/Preferences/com.apple.loginwindow.plist', 'autoLoginUser', name] __salt__['cmd.run'](cmd) current = get_auto_login() # Create/Update the kcpassword file with an obfuscated password o_password = _kcpassword(password=password) with salt.utils.files.set_umask(0o077): with salt.utils.files.fopen('/etc/kcpassword', 'w' if six.PY2 else 'wb') as fd: fd.write(o_password) return current if isinstance(current, bool) else current.lower() == name.lower()
[ "def", "enable_auto_login", "(", "name", ",", "password", ")", ":", "# Make the entry into the defaults file", "cmd", "=", "[", "'defaults'", ",", "'write'", ",", "'/Library/Preferences/com.apple.loginwindow.plist'", ",", "'autoLoginUser'", ",", "name", "]", "__salt__", ...
.. versionadded:: 2016.3.0 Configures the machine to auto login with the specified user Args: name (str): The user account use for auto login password (str): The password to user for auto login .. versionadded:: 2017.7.3 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' user.enable_auto_login stevej
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L574-L612
train
saltstack/salt
salt/modules/mac_user.py
disable_auto_login
def disable_auto_login(): ''' .. versionadded:: 2016.3.0 Disables auto login on the machine Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' user.disable_auto_login ''' # Remove the kcpassword file cmd = 'rm -f /etc/kcpassword' __salt__['cmd.run'](cmd) # Remove the entry from the defaults file cmd = ['defaults', 'delete', '/Library/Preferences/com.apple.loginwindow.plist', 'autoLoginUser'] __salt__['cmd.run'](cmd) return True if not get_auto_login() else False
python
def disable_auto_login(): ''' .. versionadded:: 2016.3.0 Disables auto login on the machine Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' user.disable_auto_login ''' # Remove the kcpassword file cmd = 'rm -f /etc/kcpassword' __salt__['cmd.run'](cmd) # Remove the entry from the defaults file cmd = ['defaults', 'delete', '/Library/Preferences/com.apple.loginwindow.plist', 'autoLoginUser'] __salt__['cmd.run'](cmd) return True if not get_auto_login() else False
[ "def", "disable_auto_login", "(", ")", ":", "# Remove the kcpassword file", "cmd", "=", "'rm -f /etc/kcpassword'", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", "# Remove the entry from the defaults file", "cmd", "=", "[", "'defaults'", ",", "'delete'", ",", "'/...
.. versionadded:: 2016.3.0 Disables auto login on the machine Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' user.disable_auto_login
[ "..", "versionadded", "::", "2016", ".", "3", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_user.py#L615-L640
train
saltstack/salt
salt/modules/apf.py
__apf_cmd
def __apf_cmd(cmd): ''' Return the apf location ''' apf_cmd = '{0} {1}'.format(salt.utils.path.which('apf'), cmd) out = __salt__['cmd.run_all'](apf_cmd) if out['retcode'] != 0: if not out['stderr']: msg = out['stdout'] else: msg = out['stderr'] raise CommandExecutionError( 'apf failed: {0}'.format(msg) ) return out['stdout']
python
def __apf_cmd(cmd): ''' Return the apf location ''' apf_cmd = '{0} {1}'.format(salt.utils.path.which('apf'), cmd) out = __salt__['cmd.run_all'](apf_cmd) if out['retcode'] != 0: if not out['stderr']: msg = out['stdout'] else: msg = out['stderr'] raise CommandExecutionError( 'apf failed: {0}'.format(msg) ) return out['stdout']
[ "def", "__apf_cmd", "(", "cmd", ")", ":", "apf_cmd", "=", "'{0} {1}'", ".", "format", "(", "salt", ".", "utils", ".", "path", ".", "which", "(", "'apf'", ")", ",", "cmd", ")", "out", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "apf_cmd", ")", ...
Return the apf location
[ "Return", "the", "apf", "location" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apf.py#L39-L54
train
saltstack/salt
salt/modules/apf.py
_status_apf
def _status_apf(): ''' Return True if apf is running otherwise return False ''' status = 0 table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: if 'sanity' in chain.name.lower(): status = 1 return True if status else False
python
def _status_apf(): ''' Return True if apf is running otherwise return False ''' status = 0 table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: if 'sanity' in chain.name.lower(): status = 1 return True if status else False
[ "def", "_status_apf", "(", ")", ":", "status", "=", "0", "table", "=", "iptc", ".", "Table", "(", "iptc", ".", "Table", ".", "FILTER", ")", "for", "chain", "in", "table", ".", "chains", ":", "if", "'sanity'", "in", "chain", ".", "name", ".", "lower...
Return True if apf is running otherwise return False
[ "Return", "True", "if", "apf", "is", "running", "otherwise", "return", "False" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/apf.py#L57-L66
train
saltstack/salt
salt/modules/composer.py
did_composer_install
def did_composer_install(dir): ''' Test to see if the vendor directory exists in this directory dir Directory location of the composer.json file CLI Example: .. code-block:: bash salt '*' composer.did_composer_install /var/www/application ''' lockFile = "{0}/vendor".format(dir) if os.path.exists(lockFile): return True return False
python
def did_composer_install(dir): ''' Test to see if the vendor directory exists in this directory dir Directory location of the composer.json file CLI Example: .. code-block:: bash salt '*' composer.did_composer_install /var/www/application ''' lockFile = "{0}/vendor".format(dir) if os.path.exists(lockFile): return True return False
[ "def", "did_composer_install", "(", "dir", ")", ":", "lockFile", "=", "\"{0}/vendor\"", ".", "format", "(", "dir", ")", "if", "os", ".", "path", ".", "exists", "(", "lockFile", ")", ":", "return", "True", "return", "False" ]
Test to see if the vendor directory exists in this directory dir Directory location of the composer.json file CLI Example: .. code-block:: bash salt '*' composer.did_composer_install /var/www/application
[ "Test", "to", "see", "if", "the", "vendor", "directory", "exists", "in", "this", "directory" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/composer.py#L44-L60
train
saltstack/salt
salt/modules/composer.py
_run_composer
def _run_composer(action, directory=None, composer=None, php=None, runas=None, prefer_source=None, prefer_dist=None, no_scripts=None, no_plugins=None, optimize=None, no_dev=None, quiet=False, composer_home='/root', extra_flags=None, env=None): ''' Run PHP's composer with a specific action. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. action The action to pass to composer ('install', 'update', 'selfupdate', etc). directory Directory location of the composer.json file. Required except when action='selfupdate' composer Location of the composer.phar file. If not set composer will just execute "composer" as if it is installed globally. (i.e. /path/to/composer.phar) php Location of the php executable to use with composer. (i.e. /usr/bin/php) runas Which system user to run composer as. prefer_source --prefer-source option of composer. prefer_dist --prefer-dist option of composer. no_scripts --no-scripts option of composer. no_plugins --no-plugins option of composer. optimize --optimize-autoloader option of composer. Recommended for production. no_dev --no-dev option for composer. Recommended for production. quiet --quiet option for composer. Whether or not to return output from composer. composer_home $COMPOSER_HOME environment variable extra_flags None, or a string containing extra flags to pass to composer. env A list of environment variables to be set prior to execution. ''' if composer is not None: if php is None: php = 'php' else: composer = 'composer' # Validate Composer is there if not _valid_composer(composer): raise CommandNotFoundError( '\'composer.{0}\' is not available. Couldn\'t find \'{1}\'.' .format(action, composer) ) if action is None: raise SaltInvocationError('The \'action\' argument is required') # Don't need a dir for the 'selfupdate' action; all other actions do need a dir if directory is None and action != 'selfupdate': raise SaltInvocationError( 'The \'directory\' argument is required for composer.{0}'.format(action) ) # Base Settings cmd = [composer, action, '--no-interaction', '--no-ansi'] if extra_flags is not None: cmd.extend(salt.utils.args.shlex_split(extra_flags)) # If php is set, prepend it if php is not None: cmd = [php] + cmd # Add Working Dir if directory is not None: cmd.extend(['--working-dir', directory]) # Other Settings if quiet is True: cmd.append('--quiet') if no_dev is True: cmd.append('--no-dev') if prefer_source is True: cmd.append('--prefer-source') if prefer_dist is True: cmd.append('--prefer-dist') if no_scripts is True: cmd.append('--no-scripts') if no_plugins is True: cmd.append('--no-plugins') if optimize is True: cmd.append('--optimize-autoloader') if env is not None: env = salt.utils.data.repack_dictlist(env) env['COMPOSER_HOME'] = composer_home else: env = {'COMPOSER_HOME': composer_home} result = __salt__['cmd.run_all'](cmd, runas=runas, env=env, python_shell=False) if result['retcode'] != 0: raise CommandExecutionError(result['stderr']) if quiet is True: return True return result
python
def _run_composer(action, directory=None, composer=None, php=None, runas=None, prefer_source=None, prefer_dist=None, no_scripts=None, no_plugins=None, optimize=None, no_dev=None, quiet=False, composer_home='/root', extra_flags=None, env=None): ''' Run PHP's composer with a specific action. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. action The action to pass to composer ('install', 'update', 'selfupdate', etc). directory Directory location of the composer.json file. Required except when action='selfupdate' composer Location of the composer.phar file. If not set composer will just execute "composer" as if it is installed globally. (i.e. /path/to/composer.phar) php Location of the php executable to use with composer. (i.e. /usr/bin/php) runas Which system user to run composer as. prefer_source --prefer-source option of composer. prefer_dist --prefer-dist option of composer. no_scripts --no-scripts option of composer. no_plugins --no-plugins option of composer. optimize --optimize-autoloader option of composer. Recommended for production. no_dev --no-dev option for composer. Recommended for production. quiet --quiet option for composer. Whether or not to return output from composer. composer_home $COMPOSER_HOME environment variable extra_flags None, or a string containing extra flags to pass to composer. env A list of environment variables to be set prior to execution. ''' if composer is not None: if php is None: php = 'php' else: composer = 'composer' # Validate Composer is there if not _valid_composer(composer): raise CommandNotFoundError( '\'composer.{0}\' is not available. Couldn\'t find \'{1}\'.' .format(action, composer) ) if action is None: raise SaltInvocationError('The \'action\' argument is required') # Don't need a dir for the 'selfupdate' action; all other actions do need a dir if directory is None and action != 'selfupdate': raise SaltInvocationError( 'The \'directory\' argument is required for composer.{0}'.format(action) ) # Base Settings cmd = [composer, action, '--no-interaction', '--no-ansi'] if extra_flags is not None: cmd.extend(salt.utils.args.shlex_split(extra_flags)) # If php is set, prepend it if php is not None: cmd = [php] + cmd # Add Working Dir if directory is not None: cmd.extend(['--working-dir', directory]) # Other Settings if quiet is True: cmd.append('--quiet') if no_dev is True: cmd.append('--no-dev') if prefer_source is True: cmd.append('--prefer-source') if prefer_dist is True: cmd.append('--prefer-dist') if no_scripts is True: cmd.append('--no-scripts') if no_plugins is True: cmd.append('--no-plugins') if optimize is True: cmd.append('--optimize-autoloader') if env is not None: env = salt.utils.data.repack_dictlist(env) env['COMPOSER_HOME'] = composer_home else: env = {'COMPOSER_HOME': composer_home} result = __salt__['cmd.run_all'](cmd, runas=runas, env=env, python_shell=False) if result['retcode'] != 0: raise CommandExecutionError(result['stderr']) if quiet is True: return True return result
[ "def", "_run_composer", "(", "action", ",", "directory", "=", "None", ",", "composer", "=", "None", ",", "php", "=", "None", ",", "runas", "=", "None", ",", "prefer_source", "=", "None", ",", "prefer_dist", "=", "None", ",", "no_scripts", "=", "None", ...
Run PHP's composer with a specific action. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. action The action to pass to composer ('install', 'update', 'selfupdate', etc). directory Directory location of the composer.json file. Required except when action='selfupdate' composer Location of the composer.phar file. If not set composer will just execute "composer" as if it is installed globally. (i.e. /path/to/composer.phar) php Location of the php executable to use with composer. (i.e. /usr/bin/php) runas Which system user to run composer as. prefer_source --prefer-source option of composer. prefer_dist --prefer-dist option of composer. no_scripts --no-scripts option of composer. no_plugins --no-plugins option of composer. optimize --optimize-autoloader option of composer. Recommended for production. no_dev --no-dev option for composer. Recommended for production. quiet --quiet option for composer. Whether or not to return output from composer. composer_home $COMPOSER_HOME environment variable extra_flags None, or a string containing extra flags to pass to composer. env A list of environment variables to be set prior to execution.
[ "Run", "PHP", "s", "composer", "with", "a", "specific", "action", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/composer.py#L63-L209
train
saltstack/salt
salt/modules/composer.py
install
def install(directory, composer=None, php=None, runas=None, prefer_source=None, prefer_dist=None, no_scripts=None, no_plugins=None, optimize=None, no_dev=None, quiet=False, composer_home='/root', env=None): ''' Install composer dependencies for a directory. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. directory Directory location of the composer.json file. composer Location of the composer.phar file. If not set composer will just execute "composer" as if it is installed globally. (i.e. /path/to/composer.phar) php Location of the php executable to use with composer. (i.e. /usr/bin/php) runas Which system user to run composer as. prefer_source --prefer-source option of composer. prefer_dist --prefer-dist option of composer. no_scripts --no-scripts option of composer. no_plugins --no-plugins option of composer. optimize --optimize-autoloader option of composer. Recommended for production. no_dev --no-dev option for composer. Recommended for production. quiet --quiet option for composer. Whether or not to return output from composer. composer_home $COMPOSER_HOME environment variable env A list of environment variables to be set prior to execution. CLI Example: .. code-block:: bash salt '*' composer.install /var/www/application salt '*' composer.install /var/www/application \ no_dev=True optimize=True ''' result = _run_composer('install', directory=directory, composer=composer, php=php, runas=runas, prefer_source=prefer_source, prefer_dist=prefer_dist, no_scripts=no_scripts, no_plugins=no_plugins, optimize=optimize, no_dev=no_dev, quiet=quiet, composer_home=composer_home, env=env) return result
python
def install(directory, composer=None, php=None, runas=None, prefer_source=None, prefer_dist=None, no_scripts=None, no_plugins=None, optimize=None, no_dev=None, quiet=False, composer_home='/root', env=None): ''' Install composer dependencies for a directory. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. directory Directory location of the composer.json file. composer Location of the composer.phar file. If not set composer will just execute "composer" as if it is installed globally. (i.e. /path/to/composer.phar) php Location of the php executable to use with composer. (i.e. /usr/bin/php) runas Which system user to run composer as. prefer_source --prefer-source option of composer. prefer_dist --prefer-dist option of composer. no_scripts --no-scripts option of composer. no_plugins --no-plugins option of composer. optimize --optimize-autoloader option of composer. Recommended for production. no_dev --no-dev option for composer. Recommended for production. quiet --quiet option for composer. Whether or not to return output from composer. composer_home $COMPOSER_HOME environment variable env A list of environment variables to be set prior to execution. CLI Example: .. code-block:: bash salt '*' composer.install /var/www/application salt '*' composer.install /var/www/application \ no_dev=True optimize=True ''' result = _run_composer('install', directory=directory, composer=composer, php=php, runas=runas, prefer_source=prefer_source, prefer_dist=prefer_dist, no_scripts=no_scripts, no_plugins=no_plugins, optimize=optimize, no_dev=no_dev, quiet=quiet, composer_home=composer_home, env=env) return result
[ "def", "install", "(", "directory", ",", "composer", "=", "None", ",", "php", "=", "None", ",", "runas", "=", "None", ",", "prefer_source", "=", "None", ",", "prefer_dist", "=", "None", ",", "no_scripts", "=", "None", ",", "no_plugins", "=", "None", ",...
Install composer dependencies for a directory. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. directory Directory location of the composer.json file. composer Location of the composer.phar file. If not set composer will just execute "composer" as if it is installed globally. (i.e. /path/to/composer.phar) php Location of the php executable to use with composer. (i.e. /usr/bin/php) runas Which system user to run composer as. prefer_source --prefer-source option of composer. prefer_dist --prefer-dist option of composer. no_scripts --no-scripts option of composer. no_plugins --no-plugins option of composer. optimize --optimize-autoloader option of composer. Recommended for production. no_dev --no-dev option for composer. Recommended for production. quiet --quiet option for composer. Whether or not to return output from composer. composer_home $COMPOSER_HOME environment variable env A list of environment variables to be set prior to execution. CLI Example: .. code-block:: bash salt '*' composer.install /var/www/application salt '*' composer.install /var/www/application \ no_dev=True optimize=True
[ "Install", "composer", "dependencies", "for", "a", "directory", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/composer.py#L212-L297
train
saltstack/salt
salt/modules/composer.py
selfupdate
def selfupdate(composer=None, php=None, runas=None, quiet=False, composer_home='/root'): ''' Update composer itself. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. composer Location of the composer.phar file. If not set composer will just execute "composer" as if it is installed globally. (i.e. /path/to/composer.phar) php Location of the php executable to use with composer. (i.e. /usr/bin/php) runas Which system user to run composer as. quiet --quiet option for composer. Whether or not to return output from composer. composer_home $COMPOSER_HOME environment variable CLI Example: .. code-block:: bash salt '*' composer.selfupdate ''' result = _run_composer('selfupdate', extra_flags='--no-progress', composer=composer, php=php, runas=runas, quiet=quiet, composer_home=composer_home) return result
python
def selfupdate(composer=None, php=None, runas=None, quiet=False, composer_home='/root'): ''' Update composer itself. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. composer Location of the composer.phar file. If not set composer will just execute "composer" as if it is installed globally. (i.e. /path/to/composer.phar) php Location of the php executable to use with composer. (i.e. /usr/bin/php) runas Which system user to run composer as. quiet --quiet option for composer. Whether or not to return output from composer. composer_home $COMPOSER_HOME environment variable CLI Example: .. code-block:: bash salt '*' composer.selfupdate ''' result = _run_composer('selfupdate', extra_flags='--no-progress', composer=composer, php=php, runas=runas, quiet=quiet, composer_home=composer_home) return result
[ "def", "selfupdate", "(", "composer", "=", "None", ",", "php", "=", "None", ",", "runas", "=", "None", ",", "quiet", "=", "False", ",", "composer_home", "=", "'/root'", ")", ":", "result", "=", "_run_composer", "(", "'selfupdate'", ",", "extra_flags", "=...
Update composer itself. If composer has not been installed globally making it available in the system PATH & making it executable, the ``composer`` and ``php`` parameters will need to be set to the location of the executables. composer Location of the composer.phar file. If not set composer will just execute "composer" as if it is installed globally. (i.e. /path/to/composer.phar) php Location of the php executable to use with composer. (i.e. /usr/bin/php) runas Which system user to run composer as. quiet --quiet option for composer. Whether or not to return output from composer. composer_home $COMPOSER_HOME environment variable CLI Example: .. code-block:: bash salt '*' composer.selfupdate
[ "Update", "composer", "itself", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/composer.py#L392-L435
train
saltstack/salt
salt/runners/saltutil.py
sync_all
def sync_all(saltenv='base', extmod_whitelist=None, extmod_blacklist=None): ''' Sync all custom types saltenv : base The fileserver environment from which to sync. To sync from more than one environment, pass a comma-separated list. extmod_whitelist : None dictionary of modules to sync based on type extmod_blacklist : None dictionary of modules to blacklist based on type CLI Example: .. code-block:: bash salt-run saltutil.sync_all salt-run saltutil.sync_all extmod_whitelist={'runners': ['custom_runner'], 'grains': []} ''' log.debug('Syncing all') ret = {} ret['clouds'] = sync_clouds(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['modules'] = sync_modules(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['states'] = sync_states(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['grains'] = sync_grains(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['renderers'] = sync_renderers(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['returners'] = sync_returners(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['output'] = sync_output(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['proxymodules'] = sync_proxymodules(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['runners'] = sync_runners(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['wheel'] = sync_wheel(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['engines'] = sync_engines(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['thorium'] = sync_thorium(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['queues'] = sync_queues(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['pillar'] = sync_pillar(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['utils'] = sync_utils(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['sdb'] = sync_sdb(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['cache'] = sync_cache(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['fileserver'] = sync_fileserver(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['tops'] = sync_tops(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['tokens'] = sync_eauth_tokens(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['serializers'] = sync_serializers(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['auth'] = sync_auth(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) return ret
python
def sync_all(saltenv='base', extmod_whitelist=None, extmod_blacklist=None): ''' Sync all custom types saltenv : base The fileserver environment from which to sync. To sync from more than one environment, pass a comma-separated list. extmod_whitelist : None dictionary of modules to sync based on type extmod_blacklist : None dictionary of modules to blacklist based on type CLI Example: .. code-block:: bash salt-run saltutil.sync_all salt-run saltutil.sync_all extmod_whitelist={'runners': ['custom_runner'], 'grains': []} ''' log.debug('Syncing all') ret = {} ret['clouds'] = sync_clouds(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['modules'] = sync_modules(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['states'] = sync_states(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['grains'] = sync_grains(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['renderers'] = sync_renderers(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['returners'] = sync_returners(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['output'] = sync_output(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['proxymodules'] = sync_proxymodules(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['runners'] = sync_runners(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['wheel'] = sync_wheel(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['engines'] = sync_engines(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['thorium'] = sync_thorium(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['queues'] = sync_queues(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['pillar'] = sync_pillar(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['utils'] = sync_utils(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['sdb'] = sync_sdb(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['cache'] = sync_cache(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['fileserver'] = sync_fileserver(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['tops'] = sync_tops(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['tokens'] = sync_eauth_tokens(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['serializers'] = sync_serializers(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) ret['auth'] = sync_auth(saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist) return ret
[ "def", "sync_all", "(", "saltenv", "=", "'base'", ",", "extmod_whitelist", "=", "None", ",", "extmod_blacklist", "=", "None", ")", ":", "log", ".", "debug", "(", "'Syncing all'", ")", "ret", "=", "{", "}", "ret", "[", "'clouds'", "]", "=", "sync_clouds",...
Sync all custom types saltenv : base The fileserver environment from which to sync. To sync from more than one environment, pass a comma-separated list. extmod_whitelist : None dictionary of modules to sync based on type extmod_blacklist : None dictionary of modules to blacklist based on type CLI Example: .. code-block:: bash salt-run saltutil.sync_all salt-run saltutil.sync_all extmod_whitelist={'runners': ['custom_runner'], 'grains': []}
[ "Sync", "all", "custom", "types" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/saltutil.py#L20-L68
train
saltstack/salt
salt/runners/saltutil.py
sync_auth
def sync_auth(saltenv='base', extmod_whitelist=None, extmod_blacklist=None): ''' Sync execution modules from ``salt://_auth`` to the master saltenv : base The fileserver environment from which to sync. To sync from more than one environment, pass a comma-separated list. extmod_whitelist : None comma-separated list of modules to sync extmod_blacklist : None comma-separated list of modules to blacklist based on type CLI Example: .. code-block:: bash salt-run saltutil.sync_auth ''' return salt.utils.extmods.sync(__opts__, 'auth', saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist)[0]
python
def sync_auth(saltenv='base', extmod_whitelist=None, extmod_blacklist=None): ''' Sync execution modules from ``salt://_auth`` to the master saltenv : base The fileserver environment from which to sync. To sync from more than one environment, pass a comma-separated list. extmod_whitelist : None comma-separated list of modules to sync extmod_blacklist : None comma-separated list of modules to blacklist based on type CLI Example: .. code-block:: bash salt-run saltutil.sync_auth ''' return salt.utils.extmods.sync(__opts__, 'auth', saltenv=saltenv, extmod_whitelist=extmod_whitelist, extmod_blacklist=extmod_blacklist)[0]
[ "def", "sync_auth", "(", "saltenv", "=", "'base'", ",", "extmod_whitelist", "=", "None", ",", "extmod_blacklist", "=", "None", ")", ":", "return", "salt", ".", "utils", ".", "extmods", ".", "sync", "(", "__opts__", ",", "'auth'", ",", "saltenv", "=", "sa...
Sync execution modules from ``salt://_auth`` to the master saltenv : base The fileserver environment from which to sync. To sync from more than one environment, pass a comma-separated list. extmod_whitelist : None comma-separated list of modules to sync extmod_blacklist : None comma-separated list of modules to blacklist based on type CLI Example: .. code-block:: bash salt-run saltutil.sync_auth
[ "Sync", "execution", "modules", "from", "salt", ":", "//", "_auth", "to", "the", "master" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/runners/saltutil.py#L71-L92
train
saltstack/salt
salt/cloud/clouds/packet.py
avail_images
def avail_images(call=None): ''' Return available Packet os images. CLI Example: .. code-block:: bash salt-cloud --list-images packet-provider salt-cloud -f avail_images packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_images function must be called with -f or --function.' ) ret = {} vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) ret = {} for os_system in manager.list_operating_systems(): ret[os_system.name] = os_system.__dict__ return ret
python
def avail_images(call=None): ''' Return available Packet os images. CLI Example: .. code-block:: bash salt-cloud --list-images packet-provider salt-cloud -f avail_images packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_images function must be called with -f or --function.' ) ret = {} vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) ret = {} for os_system in manager.list_operating_systems(): ret[os_system.name] = os_system.__dict__ return ret
[ "def", "avail_images", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudException", "(", "'The avail_images function must be called with -f or --function.'", ")", "ret", "=", "{", "}", "vm_", "=", "get_configured_provider", ...
Return available Packet os images. CLI Example: .. code-block:: bash salt-cloud --list-images packet-provider salt-cloud -f avail_images packet-provider
[ "Return", "available", "Packet", "os", "images", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L117-L143
train
saltstack/salt
salt/cloud/clouds/packet.py
avail_locations
def avail_locations(call=None): ''' Return available Packet datacenter locations. CLI Example: .. code-block:: bash salt-cloud --list-locations packet-provider salt-cloud -f avail_locations packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_locations function must be called with -f or --function.' ) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) ret = {} for facility in manager.list_facilities(): ret[facility.name] = facility.__dict__ return ret
python
def avail_locations(call=None): ''' Return available Packet datacenter locations. CLI Example: .. code-block:: bash salt-cloud --list-locations packet-provider salt-cloud -f avail_locations packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_locations function must be called with -f or --function.' ) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) ret = {} for facility in manager.list_facilities(): ret[facility.name] = facility.__dict__ return ret
[ "def", "avail_locations", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudException", "(", "'The avail_locations function must be called with -f or --function.'", ")", "vm_", "=", "get_configured_provider", "(", ")", "manager"...
Return available Packet datacenter locations. CLI Example: .. code-block:: bash salt-cloud --list-locations packet-provider salt-cloud -f avail_locations packet-provider
[ "Return", "available", "Packet", "datacenter", "locations", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L146-L170
train
saltstack/salt
salt/cloud/clouds/packet.py
avail_sizes
def avail_sizes(call=None): ''' Return available Packet sizes. CLI Example: .. code-block:: bash salt-cloud --list-sizes packet-provider salt-cloud -f avail_sizes packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_locations function must be called with -f or --function.' ) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) ret = {} for plan in manager.list_plans(): ret[plan.name] = plan.__dict__ return ret
python
def avail_sizes(call=None): ''' Return available Packet sizes. CLI Example: .. code-block:: bash salt-cloud --list-sizes packet-provider salt-cloud -f avail_sizes packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_locations function must be called with -f or --function.' ) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) ret = {} for plan in manager.list_plans(): ret[plan.name] = plan.__dict__ return ret
[ "def", "avail_sizes", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudException", "(", "'The avail_locations function must be called with -f or --function.'", ")", "vm_", "=", "get_configured_provider", "(", ")", "manager", ...
Return available Packet sizes. CLI Example: .. code-block:: bash salt-cloud --list-sizes packet-provider salt-cloud -f avail_sizes packet-provider
[ "Return", "available", "Packet", "sizes", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L173-L198
train
saltstack/salt
salt/cloud/clouds/packet.py
avail_projects
def avail_projects(call=None): ''' Return available Packet projects. CLI Example: .. code-block:: bash salt-cloud -f avail_projects packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_projects function must be called with -f or --function.' ) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) ret = {} for project in manager.list_projects(): ret[project.name] = project.__dict__ return ret
python
def avail_projects(call=None): ''' Return available Packet projects. CLI Example: .. code-block:: bash salt-cloud -f avail_projects packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_projects function must be called with -f or --function.' ) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) ret = {} for project in manager.list_projects(): ret[project.name] = project.__dict__ return ret
[ "def", "avail_projects", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudException", "(", "'The avail_projects function must be called with -f or --function.'", ")", "vm_", "=", "get_configured_provider", "(", ")", "manager", ...
Return available Packet projects. CLI Example: .. code-block:: bash salt-cloud -f avail_projects packet-provider
[ "Return", "available", "Packet", "projects", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L201-L224
train
saltstack/salt
salt/cloud/clouds/packet.py
_wait_for_status
def _wait_for_status(status_type, object_id, status=None, timeout=500, quiet=True): ''' Wait for a certain status from Packet. status_type device or volume object_id The ID of the Packet device or volume to wait on. Required. status The status to wait for. timeout The amount of time to wait for a status to update. quiet Log status updates to debug logs when False. Otherwise, logs to info. ''' if status is None: status = "ok" interval = 5 iterations = int(timeout / interval) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) for i in range(0, iterations): get_object = getattr(manager, "get_{status_type}".format(status_type=status_type)) obj = get_object(object_id) if obj.state == status: return obj time.sleep(interval) log.log( logging.INFO if not quiet else logging.DEBUG, 'Status for Packet %s is \'%s\', waiting for \'%s\'.', object_id, obj.state, status ) return obj
python
def _wait_for_status(status_type, object_id, status=None, timeout=500, quiet=True): ''' Wait for a certain status from Packet. status_type device or volume object_id The ID of the Packet device or volume to wait on. Required. status The status to wait for. timeout The amount of time to wait for a status to update. quiet Log status updates to debug logs when False. Otherwise, logs to info. ''' if status is None: status = "ok" interval = 5 iterations = int(timeout / interval) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) for i in range(0, iterations): get_object = getattr(manager, "get_{status_type}".format(status_type=status_type)) obj = get_object(object_id) if obj.state == status: return obj time.sleep(interval) log.log( logging.INFO if not quiet else logging.DEBUG, 'Status for Packet %s is \'%s\', waiting for \'%s\'.', object_id, obj.state, status ) return obj
[ "def", "_wait_for_status", "(", "status_type", ",", "object_id", ",", "status", "=", "None", ",", "timeout", "=", "500", ",", "quiet", "=", "True", ")", ":", "if", "status", "is", "None", ":", "status", "=", "\"ok\"", "interval", "=", "5", "iterations", ...
Wait for a certain status from Packet. status_type device or volume object_id The ID of the Packet device or volume to wait on. Required. status The status to wait for. timeout The amount of time to wait for a status to update. quiet Log status updates to debug logs when False. Otherwise, logs to info.
[ "Wait", "for", "a", "certain", "status", "from", "Packet", ".", "status_type", "device", "or", "volume", "object_id", "The", "ID", "of", "the", "Packet", "device", "or", "volume", "to", "wait", "on", ".", "Required", ".", "status", "The", "status", "to", ...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L227-L264
train
saltstack/salt
salt/cloud/clouds/packet.py
create
def create(vm_): ''' Create a single Packet VM. ''' name = vm_['name'] if not is_profile_configured(vm_): return False __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(name), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Packet VM %s', name) manager = packet.Manager(auth_token=vm_['token']) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) device = manager.create_device(project_id=vm_['project_id'], hostname=name, plan=vm_['size'], facility=vm_['location'], operating_system=vm_['image']) device = _wait_for_status('device', device.id, status="active") if device.state != "active": log.error( 'Error creating %s on PACKET\n\n' 'while waiting for initial ready status', name, exc_info_on_loglevel=logging.DEBUG ) # Define which ssh_interface to use ssh_interface = _get_ssh_interface(vm_) # Pass the correct IP address to the bootstrap ssh_host key if ssh_interface == 'private_ips': for ip in device.ip_addresses: if ip['public'] is False: vm_['ssh_host'] = ip['address'] break else: for ip in device.ip_addresses: if ip['public'] is True: vm_['ssh_host'] = ip['address'] break key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) vm_['key_filename'] = key_filename vm_['private_key'] = key_filename # Bootstrap! ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update({'device': device.__dict__}) if vm_.get('storage_tier') and vm_.get('storage_size'): # create storage and attach it to device volume = manager.create_volume( vm_['project_id'], "{0}_storage".format(name), vm_.get('storage_tier'), vm_.get('storage_size'), vm_.get('location'), snapshot_count=vm_.get('storage_snapshot_count', 0), snapshot_frequency=vm_.get('storage_snapshot_frequency')) volume.attach(device.id) volume = _wait_for_status('volume', volume.id, status="active") if volume.state != "active": log.error( 'Error creating %s on PACKET\n\n' 'while waiting for initial ready status', name, exc_info_on_loglevel=logging.DEBUG ) ret.update({'volume': volume.__dict__}) log.info('Created Cloud VM \'%s\'', name) log.debug( '\'%s\' VM creation details:\n%s', name, pprint.pformat(device.__dict__) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(name), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret
python
def create(vm_): ''' Create a single Packet VM. ''' name = vm_['name'] if not is_profile_configured(vm_): return False __utils__['cloud.fire_event']( 'event', 'starting create', 'salt/cloud/{0}/creating'.format(name), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) log.info('Creating Packet VM %s', name) manager = packet.Manager(auth_token=vm_['token']) __utils__['cloud.fire_event']( 'event', 'requesting instance', 'salt/cloud/{0}/requesting'.format(vm_['name']), args=__utils__['cloud.filter_event']('requesting', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) device = manager.create_device(project_id=vm_['project_id'], hostname=name, plan=vm_['size'], facility=vm_['location'], operating_system=vm_['image']) device = _wait_for_status('device', device.id, status="active") if device.state != "active": log.error( 'Error creating %s on PACKET\n\n' 'while waiting for initial ready status', name, exc_info_on_loglevel=logging.DEBUG ) # Define which ssh_interface to use ssh_interface = _get_ssh_interface(vm_) # Pass the correct IP address to the bootstrap ssh_host key if ssh_interface == 'private_ips': for ip in device.ip_addresses: if ip['public'] is False: vm_['ssh_host'] = ip['address'] break else: for ip in device.ip_addresses: if ip['public'] is True: vm_['ssh_host'] = ip['address'] break key_filename = config.get_cloud_config_value( 'private_key', vm_, __opts__, search_global=False, default=None ) vm_['key_filename'] = key_filename vm_['private_key'] = key_filename # Bootstrap! ret = __utils__['cloud.bootstrap'](vm_, __opts__) ret.update({'device': device.__dict__}) if vm_.get('storage_tier') and vm_.get('storage_size'): # create storage and attach it to device volume = manager.create_volume( vm_['project_id'], "{0}_storage".format(name), vm_.get('storage_tier'), vm_.get('storage_size'), vm_.get('location'), snapshot_count=vm_.get('storage_snapshot_count', 0), snapshot_frequency=vm_.get('storage_snapshot_frequency')) volume.attach(device.id) volume = _wait_for_status('volume', volume.id, status="active") if volume.state != "active": log.error( 'Error creating %s on PACKET\n\n' 'while waiting for initial ready status', name, exc_info_on_loglevel=logging.DEBUG ) ret.update({'volume': volume.__dict__}) log.info('Created Cloud VM \'%s\'', name) log.debug( '\'%s\' VM creation details:\n%s', name, pprint.pformat(device.__dict__) ) __utils__['cloud.fire_event']( 'event', 'created instance', 'salt/cloud/{0}/created'.format(name), args=__utils__['cloud.filter_event']('created', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return ret
[ "def", "create", "(", "vm_", ")", ":", "name", "=", "vm_", "[", "'name'", "]", "if", "not", "is_profile_configured", "(", "vm_", ")", ":", "return", "False", "__utils__", "[", "'cloud.fire_event'", "]", "(", "'event'", ",", "'starting create'", ",", "'salt...
Create a single Packet VM.
[ "Create", "a", "single", "Packet", "VM", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L324-L434
train
saltstack/salt
salt/cloud/clouds/packet.py
list_nodes_full
def list_nodes_full(call=None): ''' List devices, with all available information. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud -f list_nodes_full packet-provider .. ''' if call == 'action': raise SaltCloudException( 'The list_nodes_full function must be called with -f or --function.' ) ret = {} for device in get_devices_by_token(): ret[device.hostname] = device.__dict__ return ret
python
def list_nodes_full(call=None): ''' List devices, with all available information. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud -f list_nodes_full packet-provider .. ''' if call == 'action': raise SaltCloudException( 'The list_nodes_full function must be called with -f or --function.' ) ret = {} for device in get_devices_by_token(): ret[device.hostname] = device.__dict__ return ret
[ "def", "list_nodes_full", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudException", "(", "'The list_nodes_full function must be called with -f or --function.'", ")", "ret", "=", "{", "}", "for", "device", "in", "get_devi...
List devices, with all available information. CLI Example: .. code-block:: bash salt-cloud -F salt-cloud --full-query salt-cloud -f list_nodes_full packet-provider ..
[ "List", "devices", "with", "all", "available", "information", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L437-L461
train
saltstack/salt
salt/cloud/clouds/packet.py
list_nodes_min
def list_nodes_min(call=None): ''' Return a list of the VMs that are on the provider. Only a list of VM names and their state is returned. This is the minimum amount of information needed to check for existing VMs. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt-cloud -f list_nodes_min packet-provider salt-cloud --function list_nodes_min packet-provider ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_min function must be called with -f or --function.' ) ret = {} for device in get_devices_by_token(): ret[device.hostname] = {'id': device.id, 'state': device.state} return ret
python
def list_nodes_min(call=None): ''' Return a list of the VMs that are on the provider. Only a list of VM names and their state is returned. This is the minimum amount of information needed to check for existing VMs. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt-cloud -f list_nodes_min packet-provider salt-cloud --function list_nodes_min packet-provider ''' if call == 'action': raise SaltCloudSystemExit( 'The list_nodes_min function must be called with -f or --function.' ) ret = {} for device in get_devices_by_token(): ret[device.hostname] = {'id': device.id, 'state': device.state} return ret
[ "def", "list_nodes_min", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes_min function must be called with -f or --function.'", ")", "ret", "=", "{", "}", "for", "device", "in", "get_devic...
Return a list of the VMs that are on the provider. Only a list of VM names and their state is returned. This is the minimum amount of information needed to check for existing VMs. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt-cloud -f list_nodes_min packet-provider salt-cloud --function list_nodes_min packet-provider
[ "Return", "a", "list", "of", "the", "VMs", "that", "are", "on", "the", "provider", ".", "Only", "a", "list", "of", "VM", "names", "and", "their", "state", "is", "returned", ".", "This", "is", "the", "minimum", "amount", "of", "information", "needed", "...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L464-L489
train
saltstack/salt
salt/cloud/clouds/packet.py
list_nodes
def list_nodes(call=None): ''' Returns a list of devices, keeping only a brief listing. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud -f list_nodes packet-provider .. ''' if call == 'action': raise SaltCloudException( 'The list_nodes function must be called with -f or --function.' ) ret = {} for device in get_devices_by_token(): ret[device.hostname] = device.__dict__ return ret
python
def list_nodes(call=None): ''' Returns a list of devices, keeping only a brief listing. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud -f list_nodes packet-provider .. ''' if call == 'action': raise SaltCloudException( 'The list_nodes function must be called with -f or --function.' ) ret = {} for device in get_devices_by_token(): ret[device.hostname] = device.__dict__ return ret
[ "def", "list_nodes", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudException", "(", "'The list_nodes function must be called with -f or --function.'", ")", "ret", "=", "{", "}", "for", "device", "in", "get_devices_by_tok...
Returns a list of devices, keeping only a brief listing. CLI Example: .. code-block:: bash salt-cloud -Q salt-cloud --query salt-cloud -f list_nodes packet-provider ..
[ "Returns", "a", "list", "of", "devices", "keeping", "only", "a", "brief", "listing", ".", "CLI", "Example", ":", "..", "code", "-", "block", "::", "bash", "salt", "-", "cloud", "-", "Q", "salt", "-", "cloud", "--", "query", "salt", "-", "cloud", "-",...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L515-L536
train
saltstack/salt
salt/cloud/clouds/packet.py
destroy
def destroy(name, call=None): ''' Destroys a Packet device by name. name The hostname of VM to be be destroyed. CLI Example: .. code-block:: bash salt-cloud -d name ''' if call == 'function': raise SaltCloudException( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) nodes = list_nodes_min() node = nodes[name] for project in manager.list_projects(): for volume in manager.list_volumes(project.id): if volume.attached_to == node['id']: volume.detach() volume.delete() break manager.call_api("devices/{id}".format(id=node['id']), type='DELETE') __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return {}
python
def destroy(name, call=None): ''' Destroys a Packet device by name. name The hostname of VM to be be destroyed. CLI Example: .. code-block:: bash salt-cloud -d name ''' if call == 'function': raise SaltCloudException( 'The destroy action must be called with -d, --destroy, ' '-a or --action.' ) __utils__['cloud.fire_event']( 'event', 'destroying instance', 'salt/cloud/{0}/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) vm_ = get_configured_provider() manager = packet.Manager(auth_token=vm_['token']) nodes = list_nodes_min() node = nodes[name] for project in manager.list_projects(): for volume in manager.list_volumes(project.id): if volume.attached_to == node['id']: volume.detach() volume.delete() break manager.call_api("devices/{id}".format(id=node['id']), type='DELETE') __utils__['cloud.fire_event']( 'event', 'destroyed instance', 'salt/cloud/{0}/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'] ) return {}
[ "def", "destroy", "(", "name", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'function'", ":", "raise", "SaltCloudException", "(", "'The destroy action must be called with -d, --destroy, '", "'-a or --action.'", ")", "__utils__", "[", "'cloud.fire_event'", ...
Destroys a Packet device by name. name The hostname of VM to be be destroyed. CLI Example: .. code-block:: bash salt-cloud -d name
[ "Destroys", "a", "Packet", "device", "by", "name", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/packet.py#L539-L593
train
saltstack/salt
salt/beacons/smartos_imgadm.py
beacon
def beacon(config): ''' Poll imgadm and compare available images ''' ret = [] # NOTE: lookup current images current_images = __salt__['imgadm.list'](verbose=True) # NOTE: apply configuration if IMGADM_STATE['first_run']: log.info('Applying configuration for imgadm beacon') _config = {} list(map(_config.update, config)) if 'startup_import_event' not in _config or not _config['startup_import_event']: IMGADM_STATE['images'] = current_images # NOTE: import events for uuid in current_images: event = {} if uuid not in IMGADM_STATE['images']: event['tag'] = "imported/{}".format(uuid) for label in current_images[uuid]: event[label] = current_images[uuid][label] if event: ret.append(event) # NOTE: delete events for uuid in IMGADM_STATE['images']: event = {} if uuid not in current_images: event['tag'] = "deleted/{}".format(uuid) for label in IMGADM_STATE['images'][uuid]: event[label] = IMGADM_STATE['images'][uuid][label] if event: ret.append(event) # NOTE: update stored state IMGADM_STATE['images'] = current_images # NOTE: disable first_run if IMGADM_STATE['first_run']: IMGADM_STATE['first_run'] = False return ret
python
def beacon(config): ''' Poll imgadm and compare available images ''' ret = [] # NOTE: lookup current images current_images = __salt__['imgadm.list'](verbose=True) # NOTE: apply configuration if IMGADM_STATE['first_run']: log.info('Applying configuration for imgadm beacon') _config = {} list(map(_config.update, config)) if 'startup_import_event' not in _config or not _config['startup_import_event']: IMGADM_STATE['images'] = current_images # NOTE: import events for uuid in current_images: event = {} if uuid not in IMGADM_STATE['images']: event['tag'] = "imported/{}".format(uuid) for label in current_images[uuid]: event[label] = current_images[uuid][label] if event: ret.append(event) # NOTE: delete events for uuid in IMGADM_STATE['images']: event = {} if uuid not in current_images: event['tag'] = "deleted/{}".format(uuid) for label in IMGADM_STATE['images'][uuid]: event[label] = IMGADM_STATE['images'][uuid][label] if event: ret.append(event) # NOTE: update stored state IMGADM_STATE['images'] = current_images # NOTE: disable first_run if IMGADM_STATE['first_run']: IMGADM_STATE['first_run'] = False return ret
[ "def", "beacon", "(", "config", ")", ":", "ret", "=", "[", "]", "# NOTE: lookup current images", "current_images", "=", "__salt__", "[", "'imgadm.list'", "]", "(", "verbose", "=", "True", ")", "# NOTE: apply configuration", "if", "IMGADM_STATE", "[", "'first_run'"...
Poll imgadm and compare available images
[ "Poll", "imgadm", "and", "compare", "available", "images" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/beacons/smartos_imgadm.py#L69-L117
train
saltstack/salt
doc/conf.py
mock_decorator_with_params
def mock_decorator_with_params(*oargs, **okwargs): # pylint: disable=unused-argument ''' Optionally mock a decorator that takes parameters E.g.: @blah(stuff=True) def things(): pass ''' def inner(fn, *iargs, **ikwargs): # pylint: disable=unused-argument if hasattr(fn, '__call__'): return fn return Mock() return inner
python
def mock_decorator_with_params(*oargs, **okwargs): # pylint: disable=unused-argument ''' Optionally mock a decorator that takes parameters E.g.: @blah(stuff=True) def things(): pass ''' def inner(fn, *iargs, **ikwargs): # pylint: disable=unused-argument if hasattr(fn, '__call__'): return fn return Mock() return inner
[ "def", "mock_decorator_with_params", "(", "*", "oargs", ",", "*", "*", "okwargs", ")", ":", "# pylint: disable=unused-argument", "def", "inner", "(", "fn", ",", "*", "iargs", ",", "*", "*", "ikwargs", ")", ":", "# pylint: disable=unused-argument", "if", "hasattr...
Optionally mock a decorator that takes parameters E.g.: @blah(stuff=True) def things(): pass
[ "Optionally", "mock", "a", "decorator", "that", "takes", "parameters" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/doc/conf.py#L63-L77
train
saltstack/salt
salt/states/process.py
absent
def absent(name, user=None, signal=None): ''' Ensures that the named command is not running. name The pattern to match. user The user to which the process belongs signal Signal to send to the process(es). ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: running = __salt__['ps.pgrep'](name, user=user) ret['result'] = None if running: ret['comment'] = ('{0} processes will ' 'be killed').format(len(running)) else: ret['comment'] = 'No matching processes running' return ret if signal: status = __salt__['ps.pkill'](name, user=user, signal=signal, full=True) else: status = __salt__['ps.pkill'](name, user=user, full=True) ret['result'] = True if status: ret['comment'] = 'Killed {0} processes'.format(len(status['killed'])) ret['changes'] = status else: ret['comment'] = 'No matching processes running' return ret
python
def absent(name, user=None, signal=None): ''' Ensures that the named command is not running. name The pattern to match. user The user to which the process belongs signal Signal to send to the process(es). ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''} if __opts__['test']: running = __salt__['ps.pgrep'](name, user=user) ret['result'] = None if running: ret['comment'] = ('{0} processes will ' 'be killed').format(len(running)) else: ret['comment'] = 'No matching processes running' return ret if signal: status = __salt__['ps.pkill'](name, user=user, signal=signal, full=True) else: status = __salt__['ps.pkill'](name, user=user, full=True) ret['result'] = True if status: ret['comment'] = 'Killed {0} processes'.format(len(status['killed'])) ret['changes'] = status else: ret['comment'] = 'No matching processes running' return ret
[ "def", "absent", "(", "name", ",", "user", "=", "None", ",", "signal", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "if", "__opts_...
Ensures that the named command is not running. name The pattern to match. user The user to which the process belongs signal Signal to send to the process(es).
[ "Ensures", "that", "the", "named", "command", "is", "not", "running", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/process.py#L21-L61
train
saltstack/salt
salt/pillar/netbox.py
ext_pillar
def ext_pillar(minion_id, pillar, *args, **kwargs): ''' Query NetBox API for minion data ''' if minion_id == '*': log.info('There\'s no data to collect from NetBox for the Master') return {} # Pull settings from kwargs api_url = kwargs['api_url'].rstrip('/') api_token = kwargs.get('api_token') site_details = kwargs.get('site_details', True) site_prefixes = kwargs.get('site_prefixes', True) proxy_username = kwargs.get('proxy_username', None) proxy_return = kwargs.get('proxy_return', True) ret = {} # Fetch device from API headers = {} if api_token: headers = { 'Authorization': 'Token {}'.format(api_token) } device_url = '{api_url}/{app}/{endpoint}'.format(api_url=api_url, app='dcim', endpoint='devices') device_results = salt.utils.http.query(device_url, params={'name': minion_id}, header_dict=headers, decode=True) # Check status code for API call if 'error' in device_results: log.error('API query failed for "%s", status code: %d', minion_id, device_results['status']) log.error(device_results['error']) return ret # Assign results from API call to "netbox" key devices = device_results['dict']['results'] if len(devices) == 1: ret['netbox'] = devices[0] elif len(devices) > 1: log.error('More than one device found for "%s"', minion_id) return ret else: log.error('Unable to pull NetBox data for "%s"', minion_id) return ret site_id = ret['netbox']['site']['id'] site_name = ret['netbox']['site']['name'] if site_details: log.debug('Retrieving site details for "%s" - site %s (ID %d)', minion_id, site_name, site_id) site_url = '{api_url}/{app}/{endpoint}/{site_id}/'.format(api_url=api_url, app='dcim', endpoint='sites', site_id=site_id) site_details_ret = salt.utils.http.query(site_url, header_dict=headers, decode=True) if 'error' in site_details_ret: log.error('Unable to retrieve site details for %s (ID %d)', site_name, site_id) log.error('Status code: %d, error: %s', site_details_ret['status'], site_details_ret['error']) else: ret['netbox']['site'] = site_details_ret['dict'] if site_prefixes: log.debug('Retrieving site prefixes for "%s" - site %s (ID %d)', minion_id, site_name, site_id) prefixes_url = '{api_url}/{app}/{endpoint}'.format(api_url=api_url, app='ipam', endpoint='prefixes') site_prefixes_ret = salt.utils.http.query(prefixes_url, params={'site_id': site_id}, header_dict=headers, decode=True) if 'error' in site_prefixes_ret: log.error('Unable to retrieve site prefixes for %s (ID %d)', site_name, site_id) log.error('Status code: %d, error: %s', site_prefixes_ret['status'], site_prefixes_ret['error']) else: ret['netbox']['site']['prefixes'] = site_prefixes_ret['dict']['results'] if proxy_return: # Attempt to add "proxy" key, based on platform API call try: # Fetch device from API platform_results = salt.utils.http.query(ret['netbox']['platform']['url'], header_dict=headers, decode=True) # Check status code for API call if 'error' in platform_results: log.info('API query failed for "%s": %s', minion_id, platform_results['error']) # Assign results from API call to "proxy" key if the platform has a # napalm_driver defined. napalm_driver = platform_results['dict'].get('napalm_driver') if napalm_driver: ret['proxy'] = { 'host': str(ipaddress.IPv4Interface( ret['netbox']['primary_ip4']['address']).ip), 'driver': napalm_driver, 'proxytype': 'napalm', } if proxy_username: ret['proxy']['username'] = proxy_username except Exception: log.debug( 'Could not create proxy config data for "%s"', minion_id) return ret
python
def ext_pillar(minion_id, pillar, *args, **kwargs): ''' Query NetBox API for minion data ''' if minion_id == '*': log.info('There\'s no data to collect from NetBox for the Master') return {} # Pull settings from kwargs api_url = kwargs['api_url'].rstrip('/') api_token = kwargs.get('api_token') site_details = kwargs.get('site_details', True) site_prefixes = kwargs.get('site_prefixes', True) proxy_username = kwargs.get('proxy_username', None) proxy_return = kwargs.get('proxy_return', True) ret = {} # Fetch device from API headers = {} if api_token: headers = { 'Authorization': 'Token {}'.format(api_token) } device_url = '{api_url}/{app}/{endpoint}'.format(api_url=api_url, app='dcim', endpoint='devices') device_results = salt.utils.http.query(device_url, params={'name': minion_id}, header_dict=headers, decode=True) # Check status code for API call if 'error' in device_results: log.error('API query failed for "%s", status code: %d', minion_id, device_results['status']) log.error(device_results['error']) return ret # Assign results from API call to "netbox" key devices = device_results['dict']['results'] if len(devices) == 1: ret['netbox'] = devices[0] elif len(devices) > 1: log.error('More than one device found for "%s"', minion_id) return ret else: log.error('Unable to pull NetBox data for "%s"', minion_id) return ret site_id = ret['netbox']['site']['id'] site_name = ret['netbox']['site']['name'] if site_details: log.debug('Retrieving site details for "%s" - site %s (ID %d)', minion_id, site_name, site_id) site_url = '{api_url}/{app}/{endpoint}/{site_id}/'.format(api_url=api_url, app='dcim', endpoint='sites', site_id=site_id) site_details_ret = salt.utils.http.query(site_url, header_dict=headers, decode=True) if 'error' in site_details_ret: log.error('Unable to retrieve site details for %s (ID %d)', site_name, site_id) log.error('Status code: %d, error: %s', site_details_ret['status'], site_details_ret['error']) else: ret['netbox']['site'] = site_details_ret['dict'] if site_prefixes: log.debug('Retrieving site prefixes for "%s" - site %s (ID %d)', minion_id, site_name, site_id) prefixes_url = '{api_url}/{app}/{endpoint}'.format(api_url=api_url, app='ipam', endpoint='prefixes') site_prefixes_ret = salt.utils.http.query(prefixes_url, params={'site_id': site_id}, header_dict=headers, decode=True) if 'error' in site_prefixes_ret: log.error('Unable to retrieve site prefixes for %s (ID %d)', site_name, site_id) log.error('Status code: %d, error: %s', site_prefixes_ret['status'], site_prefixes_ret['error']) else: ret['netbox']['site']['prefixes'] = site_prefixes_ret['dict']['results'] if proxy_return: # Attempt to add "proxy" key, based on platform API call try: # Fetch device from API platform_results = salt.utils.http.query(ret['netbox']['platform']['url'], header_dict=headers, decode=True) # Check status code for API call if 'error' in platform_results: log.info('API query failed for "%s": %s', minion_id, platform_results['error']) # Assign results from API call to "proxy" key if the platform has a # napalm_driver defined. napalm_driver = platform_results['dict'].get('napalm_driver') if napalm_driver: ret['proxy'] = { 'host': str(ipaddress.IPv4Interface( ret['netbox']['primary_ip4']['address']).ip), 'driver': napalm_driver, 'proxytype': 'napalm', } if proxy_username: ret['proxy']['username'] = proxy_username except Exception: log.debug( 'Could not create proxy config data for "%s"', minion_id) return ret
[ "def", "ext_pillar", "(", "minion_id", ",", "pillar", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "minion_id", "==", "'*'", ":", "log", ".", "info", "(", "'There\\'s no data to collect from NetBox for the Master'", ")", "return", "{", "}", "# ...
Query NetBox API for minion data
[ "Query", "NetBox", "API", "for", "minion", "data" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/netbox.py#L61-L172
train
saltstack/salt
salt/tops/ext_nodes.py
top
def top(**kwargs): ''' Run the command configured ''' if 'id' not in kwargs['opts']: return {} cmd = '{0} {1}'.format( __opts__['master_tops']['ext_nodes'], kwargs['opts']['id'] ) ndata = salt.utils.yaml.safe_load( subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] ) if not ndata: log.info('master_tops ext_nodes call did not return any data') ret = {} if 'environment' in ndata: env = ndata['environment'] else: env = 'base' if 'classes' in ndata: if isinstance(ndata['classes'], dict): ret[env] = list(ndata['classes']) elif isinstance(ndata['classes'], list): ret[env] = ndata['classes'] else: return ret else: log.info('master_tops ext_nodes call did not have a dictionary with a "classes" key.') return ret
python
def top(**kwargs): ''' Run the command configured ''' if 'id' not in kwargs['opts']: return {} cmd = '{0} {1}'.format( __opts__['master_tops']['ext_nodes'], kwargs['opts']['id'] ) ndata = salt.utils.yaml.safe_load( subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE).communicate()[0] ) if not ndata: log.info('master_tops ext_nodes call did not return any data') ret = {} if 'environment' in ndata: env = ndata['environment'] else: env = 'base' if 'classes' in ndata: if isinstance(ndata['classes'], dict): ret[env] = list(ndata['classes']) elif isinstance(ndata['classes'], list): ret[env] = ndata['classes'] else: return ret else: log.info('master_tops ext_nodes call did not have a dictionary with a "classes" key.') return ret
[ "def", "top", "(", "*", "*", "kwargs", ")", ":", "if", "'id'", "not", "in", "kwargs", "[", "'opts'", "]", ":", "return", "{", "}", "cmd", "=", "'{0} {1}'", ".", "format", "(", "__opts__", "[", "'master_tops'", "]", "[", "'ext_nodes'", "]", ",", "kw...
Run the command configured
[ "Run", "the", "command", "configured" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/tops/ext_nodes.py#L69-L103
train
saltstack/salt
salt/states/gnomedesktop.py
_check_current_value
def _check_current_value(gnome_kwargs, value): ''' Check the current value with the passed value ''' current_value = __salt__['gnome.get'](**gnome_kwargs) return six.text_type(current_value) == six.text_type(value)
python
def _check_current_value(gnome_kwargs, value): ''' Check the current value with the passed value ''' current_value = __salt__['gnome.get'](**gnome_kwargs) return six.text_type(current_value) == six.text_type(value)
[ "def", "_check_current_value", "(", "gnome_kwargs", ",", "value", ")", ":", "current_value", "=", "__salt__", "[", "'gnome.get'", "]", "(", "*", "*", "gnome_kwargs", ")", "return", "six", ".", "text_type", "(", "current_value", ")", "==", "six", ".", "text_t...
Check the current value with the passed value
[ "Check", "the", "current", "value", "with", "the", "passed", "value" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/gnomedesktop.py#L38-L43
train
saltstack/salt
salt/states/gnomedesktop.py
_do
def _do(name, gnome_kwargs, preferences): ''' worker function for the others to use this handles all the gsetting magic ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} messages = [] for pref in preferences: key = pref value = preferences[pref] if isinstance(value, bool): ftype = 'boolean' # need to convert boolean values to strings and make lowercase to # pass to gsettings value = six.text_type(value).lower() elif isinstance(value, int): ftype = 'int' elif isinstance(value, six.string_types): ftype = 'string' else: ftype = 'string' gnome_kwargs.update({'key': key, 'value': value}) if _check_current_value(gnome_kwargs, value): messages.append('{0} is already set to {1}'.format(key, value)) else: result = __salt__['gnome.set'](**gnome_kwargs) if result['retcode'] == 0: messages.append('Setting {0} to {1}'.format(key, value)) ret['changes'][key] = '{0}:{1}'.format(key, value) ret['result'] = True else: messages.append(result['stdout']) ret['result'] = False ret['comment'] = ', '.join(messages) return ret
python
def _do(name, gnome_kwargs, preferences): ''' worker function for the others to use this handles all the gsetting magic ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} messages = [] for pref in preferences: key = pref value = preferences[pref] if isinstance(value, bool): ftype = 'boolean' # need to convert boolean values to strings and make lowercase to # pass to gsettings value = six.text_type(value).lower() elif isinstance(value, int): ftype = 'int' elif isinstance(value, six.string_types): ftype = 'string' else: ftype = 'string' gnome_kwargs.update({'key': key, 'value': value}) if _check_current_value(gnome_kwargs, value): messages.append('{0} is already set to {1}'.format(key, value)) else: result = __salt__['gnome.set'](**gnome_kwargs) if result['retcode'] == 0: messages.append('Setting {0} to {1}'.format(key, value)) ret['changes'][key] = '{0}:{1}'.format(key, value) ret['result'] = True else: messages.append(result['stdout']) ret['result'] = False ret['comment'] = ', '.join(messages) return ret
[ "def", "_do", "(", "name", ",", "gnome_kwargs", ",", "preferences", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "messages", "=", "[", "]", "for",...
worker function for the others to use this handles all the gsetting magic
[ "worker", "function", "for", "the", "others", "to", "use", "this", "handles", "all", "the", "gsetting", "magic" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/gnomedesktop.py#L46-L92
train
saltstack/salt
salt/states/gnomedesktop.py
wm_preferences
def wm_preferences(name, user=None, action_double_click_titlebar=None, action_middle_click_titlebar=None, action_right_click_titlebar=None, application_based=None, audible_bell=None, auto_raise=None, auto_raise_delay=None, button_layout=None, disable_workarounds=None, focus_mode=None, focus_new_windows=None, mouse_button_modifier=None, num_workspaces=None, raise_on_click=None, resize_with_right_button=None, theme=None, titlebar_font=None, titlebar_uses_system_font=None, visual_bell=None, visual_bell_type=None, workspace_names=None, **kwargs): ''' wm_preferences: sets values in the org.gnome.desktop.wm.preferences schema ''' gnome_kwargs = { 'user': user, 'schema': 'org.gnome.desktop.wm.preferences' } preferences = ['action_double_click_titlebar', 'action_middle_click_titlebar', 'action_right_click_titlebar', 'application_based', 'audible_bell', 'auto_raise', 'auto_raise_delay', 'button_layout', 'disable_workarounds', 'focus_mode', 'focus_new_windows', 'mouse_button_modifier', 'num_workspaces', 'raise_on_click', 'resize_with_right_button', 'theme', 'titlebar_font', 'titlebar_uses_system_font', 'visual_bell', 'visual_bell_type', 'workspace_names'] preferences_hash = {} for pref in preferences: if pref in locals() and locals()[pref] is not None: key = re.sub('_', '-', pref) preferences_hash[key] = locals()[pref] return _do(name, gnome_kwargs, preferences_hash)
python
def wm_preferences(name, user=None, action_double_click_titlebar=None, action_middle_click_titlebar=None, action_right_click_titlebar=None, application_based=None, audible_bell=None, auto_raise=None, auto_raise_delay=None, button_layout=None, disable_workarounds=None, focus_mode=None, focus_new_windows=None, mouse_button_modifier=None, num_workspaces=None, raise_on_click=None, resize_with_right_button=None, theme=None, titlebar_font=None, titlebar_uses_system_font=None, visual_bell=None, visual_bell_type=None, workspace_names=None, **kwargs): ''' wm_preferences: sets values in the org.gnome.desktop.wm.preferences schema ''' gnome_kwargs = { 'user': user, 'schema': 'org.gnome.desktop.wm.preferences' } preferences = ['action_double_click_titlebar', 'action_middle_click_titlebar', 'action_right_click_titlebar', 'application_based', 'audible_bell', 'auto_raise', 'auto_raise_delay', 'button_layout', 'disable_workarounds', 'focus_mode', 'focus_new_windows', 'mouse_button_modifier', 'num_workspaces', 'raise_on_click', 'resize_with_right_button', 'theme', 'titlebar_font', 'titlebar_uses_system_font', 'visual_bell', 'visual_bell_type', 'workspace_names'] preferences_hash = {} for pref in preferences: if pref in locals() and locals()[pref] is not None: key = re.sub('_', '-', pref) preferences_hash[key] = locals()[pref] return _do(name, gnome_kwargs, preferences_hash)
[ "def", "wm_preferences", "(", "name", ",", "user", "=", "None", ",", "action_double_click_titlebar", "=", "None", ",", "action_middle_click_titlebar", "=", "None", ",", "action_right_click_titlebar", "=", "None", ",", "application_based", "=", "None", ",", "audible_...
wm_preferences: sets values in the org.gnome.desktop.wm.preferences schema
[ "wm_preferences", ":", "sets", "values", "in", "the", "org", ".", "gnome", ".", "desktop", ".", "wm", ".", "preferences", "schema" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/gnomedesktop.py#L95-L142
train
saltstack/salt
salt/states/gnomedesktop.py
desktop_lockdown
def desktop_lockdown(name, user=None, disable_application_handlers=None, disable_command_line=None, disable_lock_screen=None, disable_log_out=None, disable_print_setup=None, disable_printing=None, disable_save_to_disk=None, disable_user_switching=None, user_administration_disabled=None, **kwargs): ''' desktop_lockdown: sets values in the org.gnome.desktop.lockdown schema ''' gnome_kwargs = { 'user': user, 'schema': 'org.gnome.desktop.lockdown' } preferences = ['disable_application_handlers', 'disable_command_line', 'disable_lock_screen', 'disable_log_out', 'disable_print_setup', 'disable_printing', 'disable_save_to_disk', 'disable_user_switching', 'user_administration_disabled'] preferences_hash = {} for pref in preferences: if pref in locals() and locals()[pref] is not None: key = re.sub('_', '-', pref) preferences_hash[key] = locals()[pref] return _do(name, gnome_kwargs, preferences_hash)
python
def desktop_lockdown(name, user=None, disable_application_handlers=None, disable_command_line=None, disable_lock_screen=None, disable_log_out=None, disable_print_setup=None, disable_printing=None, disable_save_to_disk=None, disable_user_switching=None, user_administration_disabled=None, **kwargs): ''' desktop_lockdown: sets values in the org.gnome.desktop.lockdown schema ''' gnome_kwargs = { 'user': user, 'schema': 'org.gnome.desktop.lockdown' } preferences = ['disable_application_handlers', 'disable_command_line', 'disable_lock_screen', 'disable_log_out', 'disable_print_setup', 'disable_printing', 'disable_save_to_disk', 'disable_user_switching', 'user_administration_disabled'] preferences_hash = {} for pref in preferences: if pref in locals() and locals()[pref] is not None: key = re.sub('_', '-', pref) preferences_hash[key] = locals()[pref] return _do(name, gnome_kwargs, preferences_hash)
[ "def", "desktop_lockdown", "(", "name", ",", "user", "=", "None", ",", "disable_application_handlers", "=", "None", ",", "disable_command_line", "=", "None", ",", "disable_lock_screen", "=", "None", ",", "disable_log_out", "=", "None", ",", "disable_print_setup", ...
desktop_lockdown: sets values in the org.gnome.desktop.lockdown schema
[ "desktop_lockdown", ":", "sets", "values", "in", "the", "org", ".", "gnome", ".", "desktop", ".", "lockdown", "schema" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/gnomedesktop.py#L145-L176
train
saltstack/salt
salt/states/gnomedesktop.py
desktop_interface
def desktop_interface(name, user=None, automatic_mnemonics=None, buttons_have_icons=None, can_change_accels=None, clock_format=None, clock_show_date=None, clock_show_seconds=None, cursor_blink=None, cursor_blink_time=None, cursor_blink_timeout=None, cursor_size=None, cursor_theme=None, document_font_name=None, enable_animations=None, font_name=None, gtk_color_palette=None, gtk_color_scheme=None, gtk_im_module=None, gtk_im_preedit_style=None, gtk_im_status_style=None, gtk_key_theme=None, gtk_theme=None, gtk_timeout_initial=None, gtk_timeout_repeat=None, icon_theme=None, menubar_accel=None, menubar_detachable=None, menus_have_icons=None, menus_have_tearoff=None, monospace_font_name=None, show_input_method_menu=None, show_unicode_menu=None, text_scaling_factor=None, toolbar_detachable=None, toolbar_icons_size=None, toolbar_style=None, toolkit_accessibility=None, **kwargs): ''' desktop_interface: sets values in the org.gnome.desktop.interface schema ''' gnome_kwargs = { 'user': user, 'schema': 'org.gnome.desktop.interface' } preferences = ['automatic_mnemonics', 'buttons_have_icons', 'can_change_accels', 'clock_format', 'clock_show_date', 'clock_show_seconds', 'cursor_blink', 'cursor_blink_time', 'cursor_blink_timeout', 'cursor_size', 'cursor_theme', 'document_font_name', 'enable_animations', 'font_name', 'gtk_color_palette', 'gtk_color_scheme', 'gtk_im_module', 'gtk_im_preedit_style', 'gtk_im_status_style', 'gtk_key_theme', 'gtk_theme', 'gtk_timeout_initial', 'gtk_timeout_repeat', 'icon_theme', 'menubar_accel', 'menubar_detachable', 'menus_have_icons', 'menus_have_tearoff', 'monospace_font_name', 'show_input_method_menu', 'show_unicode_menu', 'text_scaling_factor', 'toolbar_detachable', 'toolbar_icons_size', 'toolbar_style', 'toolkit_accessibility'] preferences_hash = {} for pref in preferences: if pref in locals() and locals()[pref] is not None: key = re.sub('_', '-', pref) preferences_hash[key] = locals()[pref] return _do(name, gnome_kwargs, preferences_hash)
python
def desktop_interface(name, user=None, automatic_mnemonics=None, buttons_have_icons=None, can_change_accels=None, clock_format=None, clock_show_date=None, clock_show_seconds=None, cursor_blink=None, cursor_blink_time=None, cursor_blink_timeout=None, cursor_size=None, cursor_theme=None, document_font_name=None, enable_animations=None, font_name=None, gtk_color_palette=None, gtk_color_scheme=None, gtk_im_module=None, gtk_im_preedit_style=None, gtk_im_status_style=None, gtk_key_theme=None, gtk_theme=None, gtk_timeout_initial=None, gtk_timeout_repeat=None, icon_theme=None, menubar_accel=None, menubar_detachable=None, menus_have_icons=None, menus_have_tearoff=None, monospace_font_name=None, show_input_method_menu=None, show_unicode_menu=None, text_scaling_factor=None, toolbar_detachable=None, toolbar_icons_size=None, toolbar_style=None, toolkit_accessibility=None, **kwargs): ''' desktop_interface: sets values in the org.gnome.desktop.interface schema ''' gnome_kwargs = { 'user': user, 'schema': 'org.gnome.desktop.interface' } preferences = ['automatic_mnemonics', 'buttons_have_icons', 'can_change_accels', 'clock_format', 'clock_show_date', 'clock_show_seconds', 'cursor_blink', 'cursor_blink_time', 'cursor_blink_timeout', 'cursor_size', 'cursor_theme', 'document_font_name', 'enable_animations', 'font_name', 'gtk_color_palette', 'gtk_color_scheme', 'gtk_im_module', 'gtk_im_preedit_style', 'gtk_im_status_style', 'gtk_key_theme', 'gtk_theme', 'gtk_timeout_initial', 'gtk_timeout_repeat', 'icon_theme', 'menubar_accel', 'menubar_detachable', 'menus_have_icons', 'menus_have_tearoff', 'monospace_font_name', 'show_input_method_menu', 'show_unicode_menu', 'text_scaling_factor', 'toolbar_detachable', 'toolbar_icons_size', 'toolbar_style', 'toolkit_accessibility'] preferences_hash = {} for pref in preferences: if pref in locals() and locals()[pref] is not None: key = re.sub('_', '-', pref) preferences_hash[key] = locals()[pref] return _do(name, gnome_kwargs, preferences_hash)
[ "def", "desktop_interface", "(", "name", ",", "user", "=", "None", ",", "automatic_mnemonics", "=", "None", ",", "buttons_have_icons", "=", "None", ",", "can_change_accels", "=", "None", ",", "clock_format", "=", "None", ",", "clock_show_date", "=", "None", ",...
desktop_interface: sets values in the org.gnome.desktop.interface schema
[ "desktop_interface", ":", "sets", "values", "in", "the", "org", ".", "gnome", ".", "desktop", ".", "interface", "schema" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/gnomedesktop.py#L179-L246
train
saltstack/salt
salt/serializers/toml.py
deserialize
def deserialize(stream_or_string, **options): ''' Deserialize from TOML into Python data structure. :param stream_or_string: toml stream or string to deserialize. :param options: options given to lower pytoml module. ''' try: if not isinstance(stream_or_string, (bytes, six.string_types)): return toml.load(stream_or_string, **options) if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode('utf-8') return toml.loads(stream_or_string) except Exception as error: raise DeserializationError(error)
python
def deserialize(stream_or_string, **options): ''' Deserialize from TOML into Python data structure. :param stream_or_string: toml stream or string to deserialize. :param options: options given to lower pytoml module. ''' try: if not isinstance(stream_or_string, (bytes, six.string_types)): return toml.load(stream_or_string, **options) if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode('utf-8') return toml.loads(stream_or_string) except Exception as error: raise DeserializationError(error)
[ "def", "deserialize", "(", "stream_or_string", ",", "*", "*", "options", ")", ":", "try", ":", "if", "not", "isinstance", "(", "stream_or_string", ",", "(", "bytes", ",", "six", ".", "string_types", ")", ")", ":", "return", "toml", ".", "load", "(", "s...
Deserialize from TOML into Python data structure. :param stream_or_string: toml stream or string to deserialize. :param options: options given to lower pytoml module.
[ "Deserialize", "from", "TOML", "into", "Python", "data", "structure", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/toml.py#L29-L46
train
saltstack/salt
salt/serializers/toml.py
serialize
def serialize(obj, **options): ''' Serialize Python data to TOML. :param obj: the data structure to serialize. :param options: options given to lower pytoml module. ''' try: if 'file_out' in options: return toml.dump(obj, options['file_out'], **options) else: return toml.dumps(obj, **options) except Exception as error: raise SerializationError(error)
python
def serialize(obj, **options): ''' Serialize Python data to TOML. :param obj: the data structure to serialize. :param options: options given to lower pytoml module. ''' try: if 'file_out' in options: return toml.dump(obj, options['file_out'], **options) else: return toml.dumps(obj, **options) except Exception as error: raise SerializationError(error)
[ "def", "serialize", "(", "obj", ",", "*", "*", "options", ")", ":", "try", ":", "if", "'file_out'", "in", "options", ":", "return", "toml", ".", "dump", "(", "obj", ",", "options", "[", "'file_out'", "]", ",", "*", "*", "options", ")", "else", ":",...
Serialize Python data to TOML. :param obj: the data structure to serialize. :param options: options given to lower pytoml module.
[ "Serialize", "Python", "data", "to", "TOML", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/serializers/toml.py#L49-L63
train
saltstack/salt
salt/renderers/mako.py
render
def render(template_file, saltenv='base', sls='', context=None, tmplpath=None, **kws): ''' Render the template_file, passing the functions and grains into the Mako rendering system. :rtype: string ''' tmp_data = salt.utils.templates.MAKO(template_file, to_str=True, salt=__salt__, grains=__grains__, opts=__opts__, pillar=__pillar__, saltenv=saltenv, sls=sls, context=context, tmplpath=tmplpath, **kws) if not tmp_data.get('result', False): raise SaltRenderError(tmp_data.get('data', 'Unknown render error in mako renderer')) return six.moves.StringIO(tmp_data['data'])
python
def render(template_file, saltenv='base', sls='', context=None, tmplpath=None, **kws): ''' Render the template_file, passing the functions and grains into the Mako rendering system. :rtype: string ''' tmp_data = salt.utils.templates.MAKO(template_file, to_str=True, salt=__salt__, grains=__grains__, opts=__opts__, pillar=__pillar__, saltenv=saltenv, sls=sls, context=context, tmplpath=tmplpath, **kws) if not tmp_data.get('result', False): raise SaltRenderError(tmp_data.get('data', 'Unknown render error in mako renderer')) return six.moves.StringIO(tmp_data['data'])
[ "def", "render", "(", "template_file", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "context", "=", "None", ",", "tmplpath", "=", "None", ",", "*", "*", "kws", ")", ":", "tmp_data", "=", "salt", ".", "utils", ".", "templates", ".", "M...
Render the template_file, passing the functions and grains into the Mako rendering system. :rtype: string
[ "Render", "the", "template_file", "passing", "the", "functions", "and", "grains", "into", "the", "Mako", "rendering", "system", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/mako.py#L15-L35
train
saltstack/salt
salt/proxy/fx2.py
init
def init(opts): ''' This function gets called when the proxy starts up. We check opts to see if a fallback user and password are supplied. If they are present, and the primary credentials don't work, then we try the backup before failing. Whichever set of credentials works is placed in the persistent DETAILS dictionary and will be used for further communication with the chassis. ''' if 'host' not in opts['proxy']: log.critical('No "host" key found in pillar for this proxy') return False DETAILS['host'] = opts['proxy']['host'] (username, password) = find_credentials()
python
def init(opts): ''' This function gets called when the proxy starts up. We check opts to see if a fallback user and password are supplied. If they are present, and the primary credentials don't work, then we try the backup before failing. Whichever set of credentials works is placed in the persistent DETAILS dictionary and will be used for further communication with the chassis. ''' if 'host' not in opts['proxy']: log.critical('No "host" key found in pillar for this proxy') return False DETAILS['host'] = opts['proxy']['host'] (username, password) = find_credentials()
[ "def", "init", "(", "opts", ")", ":", "if", "'host'", "not", "in", "opts", "[", "'proxy'", "]", ":", "log", ".", "critical", "(", "'No \"host\" key found in pillar for this proxy'", ")", "return", "False", "DETAILS", "[", "'host'", "]", "=", "opts", "[", "...
This function gets called when the proxy starts up. We check opts to see if a fallback user and password are supplied. If they are present, and the primary credentials don't work, then we try the backup before failing. Whichever set of credentials works is placed in the persistent DETAILS dictionary and will be used for further communication with the chassis.
[ "This", "function", "gets", "called", "when", "the", "proxy", "starts", "up", ".", "We", "check", "opts", "to", "see", "if", "a", "fallback", "user", "and", "password", "are", "supplied", ".", "If", "they", "are", "present", "and", "the", "primary", "cre...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/fx2.py#L203-L220
train
saltstack/salt
salt/proxy/fx2.py
_grains
def _grains(host, user, password): ''' Get the grains from the proxied device ''' r = __salt__['dracr.system_info'](host=host, admin_username=user, admin_password=password) if r.get('retcode', 0) == 0: GRAINS_CACHE = r else: GRAINS_CACHE = {} return GRAINS_CACHE
python
def _grains(host, user, password): ''' Get the grains from the proxied device ''' r = __salt__['dracr.system_info'](host=host, admin_username=user, admin_password=password) if r.get('retcode', 0) == 0: GRAINS_CACHE = r else: GRAINS_CACHE = {} return GRAINS_CACHE
[ "def", "_grains", "(", "host", ",", "user", ",", "password", ")", ":", "r", "=", "__salt__", "[", "'dracr.system_info'", "]", "(", "host", "=", "host", ",", "admin_username", "=", "user", ",", "admin_password", "=", "password", ")", "if", "r", ".", "ge...
Get the grains from the proxied device
[ "Get", "the", "grains", "from", "the", "proxied", "device" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/fx2.py#L247-L258
train
saltstack/salt
salt/proxy/fx2.py
find_credentials
def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works ''' usernames = [__pillar__['proxy'].get('admin_username', 'root')] if 'fallback_admin_username' in __pillar__.get('proxy'): usernames.append(__pillar__['proxy'].get('fallback_admin_username')) for user in usernames: for pwd in __pillar__['proxy']['passwords']: r = __salt__['dracr.get_chassis_name'](host=__pillar__['proxy']['host'], admin_username=user, admin_password=pwd) # Retcode will be present if the chassis_name call failed try: if r.get('retcode', None) is None: DETAILS['admin_username'] = user DETAILS['admin_password'] = pwd __opts__['proxy']['admin_username'] = user __opts__['proxy']['admin_password'] = pwd return (user, pwd) except AttributeError: # Then the above was a string, and we can return the username # and password DETAILS['admin_username'] = user DETAILS['admin_password'] = pwd __opts__['proxy']['admin_username'] = user __opts__['proxy']['admin_password'] = pwd return (user, pwd) log.debug('proxy fx2.find_credentials found no valid credentials, using Dell default') return ('root', 'calvin')
python
def find_credentials(): ''' Cycle through all the possible credentials and return the first one that works ''' usernames = [__pillar__['proxy'].get('admin_username', 'root')] if 'fallback_admin_username' in __pillar__.get('proxy'): usernames.append(__pillar__['proxy'].get('fallback_admin_username')) for user in usernames: for pwd in __pillar__['proxy']['passwords']: r = __salt__['dracr.get_chassis_name'](host=__pillar__['proxy']['host'], admin_username=user, admin_password=pwd) # Retcode will be present if the chassis_name call failed try: if r.get('retcode', None) is None: DETAILS['admin_username'] = user DETAILS['admin_password'] = pwd __opts__['proxy']['admin_username'] = user __opts__['proxy']['admin_password'] = pwd return (user, pwd) except AttributeError: # Then the above was a string, and we can return the username # and password DETAILS['admin_username'] = user DETAILS['admin_password'] = pwd __opts__['proxy']['admin_username'] = user __opts__['proxy']['admin_password'] = pwd return (user, pwd) log.debug('proxy fx2.find_credentials found no valid credentials, using Dell default') return ('root', 'calvin')
[ "def", "find_credentials", "(", ")", ":", "usernames", "=", "[", "__pillar__", "[", "'proxy'", "]", ".", "get", "(", "'admin_username'", ",", "'root'", ")", "]", "if", "'fallback_admin_username'", "in", "__pillar__", ".", "get", "(", "'proxy'", ")", ":", "...
Cycle through all the possible credentials and return the first one that works
[ "Cycle", "through", "all", "the", "possible", "credentials", "and", "return", "the", "first", "one", "that", "works" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/fx2.py#L281-L313
train
saltstack/salt
salt/proxy/fx2.py
chconfig
def chconfig(cmd, *args, **kwargs): ''' This function is called by the :mod:`salt.modules.chassis.cmd <salt.modules.chassis.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.dracr <salt.modules.dracr>` module. :param cmd: The command to call inside salt.modules.dracr :param args: Arguments that need to be passed to that command :param kwargs: Keyword arguments that need to be passed to that command :return: Passthrough the return from the dracr module. ''' # Strip the __pub_ keys...is there a better way to do this? for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) # Catch password reset if 'dracr.'+cmd not in __salt__: ret = {'retcode': -1, 'message': 'dracr.' + cmd + ' is not available'} else: ret = __salt__['dracr.'+cmd](*args, **kwargs) if cmd == 'change_password': if 'username' in kwargs: __opts__['proxy']['admin_username'] = kwargs['username'] DETAILS['admin_username'] = kwargs['username'] if 'password' in kwargs: __opts__['proxy']['admin_password'] = kwargs['password'] DETAILS['admin_password'] = kwargs['password'] return ret
python
def chconfig(cmd, *args, **kwargs): ''' This function is called by the :mod:`salt.modules.chassis.cmd <salt.modules.chassis.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.dracr <salt.modules.dracr>` module. :param cmd: The command to call inside salt.modules.dracr :param args: Arguments that need to be passed to that command :param kwargs: Keyword arguments that need to be passed to that command :return: Passthrough the return from the dracr module. ''' # Strip the __pub_ keys...is there a better way to do this? for k in list(kwargs): if k.startswith('__pub_'): kwargs.pop(k) # Catch password reset if 'dracr.'+cmd not in __salt__: ret = {'retcode': -1, 'message': 'dracr.' + cmd + ' is not available'} else: ret = __salt__['dracr.'+cmd](*args, **kwargs) if cmd == 'change_password': if 'username' in kwargs: __opts__['proxy']['admin_username'] = kwargs['username'] DETAILS['admin_username'] = kwargs['username'] if 'password' in kwargs: __opts__['proxy']['admin_password'] = kwargs['password'] DETAILS['admin_password'] = kwargs['password'] return ret
[ "def", "chconfig", "(", "cmd", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Strip the __pub_ keys...is there a better way to do this?", "for", "k", "in", "list", "(", "kwargs", ")", ":", "if", "k", ".", "startswith", "(", "'__pub_'", ")", ":", "...
This function is called by the :mod:`salt.modules.chassis.cmd <salt.modules.chassis.cmd>` shim. It then calls whatever is passed in ``cmd`` inside the :mod:`salt.modules.dracr <salt.modules.dracr>` module. :param cmd: The command to call inside salt.modules.dracr :param args: Arguments that need to be passed to that command :param kwargs: Keyword arguments that need to be passed to that command :return: Passthrough the return from the dracr module.
[ "This", "function", "is", "called", "by", "the", ":", "mod", ":", "salt", ".", "modules", ".", "chassis", ".", "cmd", "<salt", ".", "modules", ".", "chassis", ".", "cmd", ">", "shim", ".", "It", "then", "calls", "whatever", "is", "passed", "in", "cmd...
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/fx2.py#L316-L348
train
saltstack/salt
salt/proxy/fx2.py
ping
def ping(): ''' Is the chassis responding? :return: Returns False if the chassis didn't respond, True otherwise. ''' r = __salt__['dracr.system_info'](host=DETAILS['host'], admin_username=DETAILS['admin_username'], admin_password=DETAILS['admin_password']) if r.get('retcode', 0) == 1: return False else: return True try: return r['dict'].get('ret', False) except Exception: return False
python
def ping(): ''' Is the chassis responding? :return: Returns False if the chassis didn't respond, True otherwise. ''' r = __salt__['dracr.system_info'](host=DETAILS['host'], admin_username=DETAILS['admin_username'], admin_password=DETAILS['admin_password']) if r.get('retcode', 0) == 1: return False else: return True try: return r['dict'].get('ret', False) except Exception: return False
[ "def", "ping", "(", ")", ":", "r", "=", "__salt__", "[", "'dracr.system_info'", "]", "(", "host", "=", "DETAILS", "[", "'host'", "]", ",", "admin_username", "=", "DETAILS", "[", "'admin_username'", "]", ",", "admin_password", "=", "DETAILS", "[", "'admin_p...
Is the chassis responding? :return: Returns False if the chassis didn't respond, True otherwise.
[ "Is", "the", "chassis", "responding?" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/proxy/fx2.py#L351-L368
train
saltstack/salt
salt/cache/consul.py
store
def store(bank, key, data): ''' Store a key value. ''' c_key = '{0}/{1}'.format(bank, key) try: c_data = __context__['serial'].dumps(data) api.kv.put(c_key, c_data) except Exception as exc: raise SaltCacheError( 'There was an error writing the key, {0}: {1}'.format( c_key, exc ) )
python
def store(bank, key, data): ''' Store a key value. ''' c_key = '{0}/{1}'.format(bank, key) try: c_data = __context__['serial'].dumps(data) api.kv.put(c_key, c_data) except Exception as exc: raise SaltCacheError( 'There was an error writing the key, {0}: {1}'.format( c_key, exc ) )
[ "def", "store", "(", "bank", ",", "key", ",", "data", ")", ":", "c_key", "=", "'{0}/{1}'", ".", "format", "(", "bank", ",", "key", ")", "try", ":", "c_data", "=", "__context__", "[", "'serial'", "]", ".", "dumps", "(", "data", ")", "api", ".", "k...
Store a key value.
[ "Store", "a", "key", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/consul.py#L95-L108
train
saltstack/salt
salt/cache/consul.py
fetch
def fetch(bank, key): ''' Fetch a key value. ''' c_key = '{0}/{1}'.format(bank, key) try: _, value = api.kv.get(c_key) if value is None: return {} return __context__['serial'].loads(value['Value']) except Exception as exc: raise SaltCacheError( 'There was an error reading the key, {0}: {1}'.format( c_key, exc ) )
python
def fetch(bank, key): ''' Fetch a key value. ''' c_key = '{0}/{1}'.format(bank, key) try: _, value = api.kv.get(c_key) if value is None: return {} return __context__['serial'].loads(value['Value']) except Exception as exc: raise SaltCacheError( 'There was an error reading the key, {0}: {1}'.format( c_key, exc ) )
[ "def", "fetch", "(", "bank", ",", "key", ")", ":", "c_key", "=", "'{0}/{1}'", ".", "format", "(", "bank", ",", "key", ")", "try", ":", "_", ",", "value", "=", "api", ".", "kv", ".", "get", "(", "c_key", ")", "if", "value", "is", "None", ":", ...
Fetch a key value.
[ "Fetch", "a", "key", "value", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/consul.py#L111-L126
train
saltstack/salt
salt/cache/consul.py
flush
def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. ''' if key is None: c_key = bank else: c_key = '{0}/{1}'.format(bank, key) try: return api.kv.delete(c_key, recurse=key is None) except Exception as exc: raise SaltCacheError( 'There was an error removing the key, {0}: {1}'.format( c_key, exc ) )
python
def flush(bank, key=None): ''' Remove the key from the cache bank with all the key content. ''' if key is None: c_key = bank else: c_key = '{0}/{1}'.format(bank, key) try: return api.kv.delete(c_key, recurse=key is None) except Exception as exc: raise SaltCacheError( 'There was an error removing the key, {0}: {1}'.format( c_key, exc ) )
[ "def", "flush", "(", "bank", ",", "key", "=", "None", ")", ":", "if", "key", "is", "None", ":", "c_key", "=", "bank", "else", ":", "c_key", "=", "'{0}/{1}'", ".", "format", "(", "bank", ",", "key", ")", "try", ":", "return", "api", ".", "kv", "...
Remove the key from the cache bank with all the key content.
[ "Remove", "the", "key", "from", "the", "cache", "bank", "with", "all", "the", "key", "content", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/consul.py#L129-L144
train
saltstack/salt
salt/cache/consul.py
list_
def list_(bank): ''' Return an iterable object containing all entries stored in the specified bank. ''' try: _, keys = api.kv.get(bank + '/', keys=True, separator='/') except Exception as exc: raise SaltCacheError( 'There was an error getting the key "{0}": {1}'.format( bank, exc ) ) if keys is None: keys = [] else: # Any key could be a branch and a leaf at the same time in Consul # so we have to return a list of unique names only. out = set() for key in keys: out.add(key[len(bank) + 1:].rstrip('/')) keys = list(out) return keys
python
def list_(bank): ''' Return an iterable object containing all entries stored in the specified bank. ''' try: _, keys = api.kv.get(bank + '/', keys=True, separator='/') except Exception as exc: raise SaltCacheError( 'There was an error getting the key "{0}": {1}'.format( bank, exc ) ) if keys is None: keys = [] else: # Any key could be a branch and a leaf at the same time in Consul # so we have to return a list of unique names only. out = set() for key in keys: out.add(key[len(bank) + 1:].rstrip('/')) keys = list(out) return keys
[ "def", "list_", "(", "bank", ")", ":", "try", ":", "_", ",", "keys", "=", "api", ".", "kv", ".", "get", "(", "bank", "+", "'/'", ",", "keys", "=", "True", ",", "separator", "=", "'/'", ")", "except", "Exception", "as", "exc", ":", "raise", "Sal...
Return an iterable object containing all entries stored in the specified bank.
[ "Return", "an", "iterable", "object", "containing", "all", "entries", "stored", "in", "the", "specified", "bank", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/consul.py#L147-L168
train
saltstack/salt
salt/cache/consul.py
contains
def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' if key is None: return True # any key could be a branch and a leaf at the same time in Consul else: try: c_key = '{0}/{1}'.format(bank, key) _, value = api.kv.get(c_key) except Exception as exc: raise SaltCacheError( 'There was an error getting the key, {0}: {1}'.format( c_key, exc ) ) return value is not None
python
def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' if key is None: return True # any key could be a branch and a leaf at the same time in Consul else: try: c_key = '{0}/{1}'.format(bank, key) _, value = api.kv.get(c_key) except Exception as exc: raise SaltCacheError( 'There was an error getting the key, {0}: {1}'.format( c_key, exc ) ) return value is not None
[ "def", "contains", "(", "bank", ",", "key", ")", ":", "if", "key", "is", "None", ":", "return", "True", "# any key could be a branch and a leaf at the same time in Consul", "else", ":", "try", ":", "c_key", "=", "'{0}/{1}'", ".", "format", "(", "bank", ",", "k...
Checks if the specified bank contains the specified key.
[ "Checks", "if", "the", "specified", "bank", "contains", "the", "specified", "key", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cache/consul.py#L171-L187
train
saltstack/salt
salt/modules/sensehat.py
set_pixel
def set_pixel(x, y, color): ''' Sets a single pixel on the LED matrix to a specified color. x The x coordinate of the pixel. Ranges from 0 on the left to 7 on the right. y The y coordinate of the pixel. Ranges from 0 at the top to 7 at the bottom. color The new color of the pixel as a list of ``[R, G, B]`` values. CLI Example: .. code-block:: bash salt 'raspberry' sensehat.set_pixel 0 0 '[255, 0, 0]' ''' _sensehat.set_pixel(x, y, color) return {'color': color}
python
def set_pixel(x, y, color): ''' Sets a single pixel on the LED matrix to a specified color. x The x coordinate of the pixel. Ranges from 0 on the left to 7 on the right. y The y coordinate of the pixel. Ranges from 0 at the top to 7 at the bottom. color The new color of the pixel as a list of ``[R, G, B]`` values. CLI Example: .. code-block:: bash salt 'raspberry' sensehat.set_pixel 0 0 '[255, 0, 0]' ''' _sensehat.set_pixel(x, y, color) return {'color': color}
[ "def", "set_pixel", "(", "x", ",", "y", ",", "color", ")", ":", "_sensehat", ".", "set_pixel", "(", "x", ",", "y", ",", "color", ")", "return", "{", "'color'", ":", "color", "}" ]
Sets a single pixel on the LED matrix to a specified color. x The x coordinate of the pixel. Ranges from 0 on the left to 7 on the right. y The y coordinate of the pixel. Ranges from 0 at the top to 7 at the bottom. color The new color of the pixel as a list of ``[R, G, B]`` values. CLI Example: .. code-block:: bash salt 'raspberry' sensehat.set_pixel 0 0 '[255, 0, 0]'
[ "Sets", "a", "single", "pixel", "on", "the", "LED", "matrix", "to", "a", "specified", "color", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sensehat.py#L89-L107
train
saltstack/salt
salt/modules/sensehat.py
show_message
def show_message(message, msg_type=None, text_color=None, back_color=None, scroll_speed=0.1): ''' Displays a message on the LED matrix. message The message to display msg_type The type of the message. Changes the appearance of the message. Available types are:: error: red text warning: orange text success: green text info: blue text scroll_speed The speed at which the message moves over the LED matrix. This value represents the time paused for between shifting the text to the left by one column of pixels. Defaults to '0.1'. text_color The color in which the message is shown. Defaults to '[255, 255, 255]' (white). back_color The background color of the display. Defaults to '[0, 0, 0]' (black). CLI Example: .. code-block:: bash salt 'raspberry' sensehat.show_message 'Status ok' salt 'raspberry' sensehat.show_message 'Something went wrong' error salt 'raspberry' sensehat.show_message 'Red' text_color='[255, 0, 0]' salt 'raspberry' sensehat.show_message 'Hello world' None '[0, 0, 255]' '[255, 255, 0]' 0.2 ''' text_color = text_color or [255, 255, 255] back_color = back_color or [0, 0, 0] color_by_type = { 'error': [255, 0, 0], 'warning': [255, 100, 0], 'success': [0, 255, 0], 'info': [0, 0, 255] } if msg_type in color_by_type: text_color = color_by_type[msg_type] _sensehat.show_message(message, scroll_speed, text_color, back_color) return {'message': message}
python
def show_message(message, msg_type=None, text_color=None, back_color=None, scroll_speed=0.1): ''' Displays a message on the LED matrix. message The message to display msg_type The type of the message. Changes the appearance of the message. Available types are:: error: red text warning: orange text success: green text info: blue text scroll_speed The speed at which the message moves over the LED matrix. This value represents the time paused for between shifting the text to the left by one column of pixels. Defaults to '0.1'. text_color The color in which the message is shown. Defaults to '[255, 255, 255]' (white). back_color The background color of the display. Defaults to '[0, 0, 0]' (black). CLI Example: .. code-block:: bash salt 'raspberry' sensehat.show_message 'Status ok' salt 'raspberry' sensehat.show_message 'Something went wrong' error salt 'raspberry' sensehat.show_message 'Red' text_color='[255, 0, 0]' salt 'raspberry' sensehat.show_message 'Hello world' None '[0, 0, 255]' '[255, 255, 0]' 0.2 ''' text_color = text_color or [255, 255, 255] back_color = back_color or [0, 0, 0] color_by_type = { 'error': [255, 0, 0], 'warning': [255, 100, 0], 'success': [0, 255, 0], 'info': [0, 0, 255] } if msg_type in color_by_type: text_color = color_by_type[msg_type] _sensehat.show_message(message, scroll_speed, text_color, back_color) return {'message': message}
[ "def", "show_message", "(", "message", ",", "msg_type", "=", "None", ",", "text_color", "=", "None", ",", "back_color", "=", "None", ",", "scroll_speed", "=", "0.1", ")", ":", "text_color", "=", "text_color", "or", "[", "255", ",", "255", ",", "255", "...
Displays a message on the LED matrix. message The message to display msg_type The type of the message. Changes the appearance of the message. Available types are:: error: red text warning: orange text success: green text info: blue text scroll_speed The speed at which the message moves over the LED matrix. This value represents the time paused for between shifting the text to the left by one column of pixels. Defaults to '0.1'. text_color The color in which the message is shown. Defaults to '[255, 255, 255]' (white). back_color The background color of the display. Defaults to '[0, 0, 0]' (black). CLI Example: .. code-block:: bash salt 'raspberry' sensehat.show_message 'Status ok' salt 'raspberry' sensehat.show_message 'Something went wrong' error salt 'raspberry' sensehat.show_message 'Red' text_color='[255, 0, 0]' salt 'raspberry' sensehat.show_message 'Hello world' None '[0, 0, 255]' '[255, 255, 0]' 0.2
[ "Displays", "a", "message", "on", "the", "LED", "matrix", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sensehat.py#L140-L189
train
saltstack/salt
salt/modules/sensehat.py
show_letter
def show_letter(letter, text_color=None, back_color=None): ''' Displays a single letter on the LED matrix. letter The letter to display text_color The color in which the letter is shown. Defaults to '[255, 255, 255]' (white). back_color The background color of the display. Defaults to '[0, 0, 0]' (black). CLI Example: .. code-block:: bash salt 'raspberry' sensehat.show_letter O salt 'raspberry' sensehat.show_letter X '[255, 0, 0]' salt 'raspberry' sensehat.show_letter B '[0, 0, 255]' '[255, 255, 0]' ''' text_color = text_color or [255, 255, 255] back_color = back_color or [0, 0, 0] _sensehat.show_letter(letter, text_color, back_color) return {'letter': letter}
python
def show_letter(letter, text_color=None, back_color=None): ''' Displays a single letter on the LED matrix. letter The letter to display text_color The color in which the letter is shown. Defaults to '[255, 255, 255]' (white). back_color The background color of the display. Defaults to '[0, 0, 0]' (black). CLI Example: .. code-block:: bash salt 'raspberry' sensehat.show_letter O salt 'raspberry' sensehat.show_letter X '[255, 0, 0]' salt 'raspberry' sensehat.show_letter B '[0, 0, 255]' '[255, 255, 0]' ''' text_color = text_color or [255, 255, 255] back_color = back_color or [0, 0, 0] _sensehat.show_letter(letter, text_color, back_color) return {'letter': letter}
[ "def", "show_letter", "(", "letter", ",", "text_color", "=", "None", ",", "back_color", "=", "None", ")", ":", "text_color", "=", "text_color", "or", "[", "255", ",", "255", ",", "255", "]", "back_color", "=", "back_color", "or", "[", "0", ",", "0", ...
Displays a single letter on the LED matrix. letter The letter to display text_color The color in which the letter is shown. Defaults to '[255, 255, 255]' (white). back_color The background color of the display. Defaults to '[0, 0, 0]' (black). CLI Example: .. code-block:: bash salt 'raspberry' sensehat.show_letter O salt 'raspberry' sensehat.show_letter X '[255, 0, 0]' salt 'raspberry' sensehat.show_letter B '[0, 0, 255]' '[255, 255, 0]'
[ "Displays", "a", "single", "letter", "on", "the", "LED", "matrix", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/sensehat.py#L192-L215
train
saltstack/salt
salt/modules/netbox.py
_add
def _add(app, endpoint, payload): ''' POST a payload ''' nb = _nb_obj(auth_required=True) try: return getattr(getattr(nb, app), endpoint).create(**payload) except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False
python
def _add(app, endpoint, payload): ''' POST a payload ''' nb = _nb_obj(auth_required=True) try: return getattr(getattr(nb, app), endpoint).create(**payload) except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False
[ "def", "_add", "(", "app", ",", "endpoint", ",", "payload", ")", ":", "nb", "=", "_nb_obj", "(", "auth_required", "=", "True", ")", "try", ":", "return", "getattr", "(", "getattr", "(", "nb", ",", "app", ")", ",", "endpoint", ")", ".", "create", "(...
POST a payload
[ "POST", "a", "payload" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L98-L107
train
saltstack/salt
salt/modules/netbox.py
slugify
def slugify(value): '''' Slugify given value. Credit to Djangoproject https://docs.djangoproject.com/en/2.0/_modules/django/utils/text/#slugify ''' value = re.sub(r'[^\w\s-]', '', value).strip().lower() return re.sub(r'[-\s]+', '-', value)
python
def slugify(value): '''' Slugify given value. Credit to Djangoproject https://docs.djangoproject.com/en/2.0/_modules/django/utils/text/#slugify ''' value = re.sub(r'[^\w\s-]', '', value).strip().lower() return re.sub(r'[-\s]+', '-', value)
[ "def", "slugify", "(", "value", ")", ":", "value", "=", "re", ".", "sub", "(", "r'[^\\w\\s-]'", ",", "''", ",", "value", ")", ".", "strip", "(", ")", ".", "lower", "(", ")", "return", "re", ".", "sub", "(", "r'[-\\s]+'", ",", "'-'", ",", "value",...
Slugify given value. Credit to Djangoproject https://docs.djangoproject.com/en/2.0/_modules/django/utils/text/#slugify
[ "Slugify", "given", "value", ".", "Credit", "to", "Djangoproject", "https", ":", "//", "docs", ".", "djangoproject", ".", "com", "/", "en", "/", "2", ".", "0", "/", "_modules", "/", "django", "/", "utils", "/", "text", "/", "#slugify" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L110-L116
train
saltstack/salt
salt/modules/netbox.py
_get
def _get(app, endpoint, id=None, auth_required=False, **kwargs): ''' Helper function to do a GET request to Netbox. Returns the actual pynetbox object, which allows manipulation from other functions. ''' nb = _nb_obj(auth_required=auth_required) if id: item = getattr(getattr(nb, app), endpoint).get(id) else: kwargs = __utils__['args.clean_kwargs'](**kwargs) item = getattr(getattr(nb, app), endpoint).get(**kwargs) return item
python
def _get(app, endpoint, id=None, auth_required=False, **kwargs): ''' Helper function to do a GET request to Netbox. Returns the actual pynetbox object, which allows manipulation from other functions. ''' nb = _nb_obj(auth_required=auth_required) if id: item = getattr(getattr(nb, app), endpoint).get(id) else: kwargs = __utils__['args.clean_kwargs'](**kwargs) item = getattr(getattr(nb, app), endpoint).get(**kwargs) return item
[ "def", "_get", "(", "app", ",", "endpoint", ",", "id", "=", "None", ",", "auth_required", "=", "False", ",", "*", "*", "kwargs", ")", ":", "nb", "=", "_nb_obj", "(", "auth_required", "=", "auth_required", ")", "if", "id", ":", "item", "=", "getattr",...
Helper function to do a GET request to Netbox. Returns the actual pynetbox object, which allows manipulation from other functions.
[ "Helper", "function", "to", "do", "a", "GET", "request", "to", "Netbox", ".", "Returns", "the", "actual", "pynetbox", "object", "which", "allows", "manipulation", "from", "other", "functions", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L119-L130
train
saltstack/salt
salt/modules/netbox.py
filter_
def filter_(app, endpoint, **kwargs): ''' Get a list of items from NetBox. app String of netbox app, e.g., ``dcim``, ``circuits``, ``ipam`` endpoint String of app endpoint, e.g., ``sites``, ``regions``, ``devices`` kwargs Optional arguments that can be used to filter. All filter keywords are available in Netbox, which can be found by surfing to the corresponding API endpoint, and clicking Filters. e.g., ``role=router`` Returns a list of dictionaries .. code-block:: bash salt myminion netbox.filter dcim devices status=1 role=router ''' ret = [] nb = _nb_obj(auth_required=True if app in AUTH_ENDPOINTS else False) nb_query = getattr(getattr(nb, app), endpoint).filter( **__utils__['args.clean_kwargs'](**kwargs) ) if nb_query: ret = [_strip_url_field(dict(i)) for i in nb_query] return sorted(ret)
python
def filter_(app, endpoint, **kwargs): ''' Get a list of items from NetBox. app String of netbox app, e.g., ``dcim``, ``circuits``, ``ipam`` endpoint String of app endpoint, e.g., ``sites``, ``regions``, ``devices`` kwargs Optional arguments that can be used to filter. All filter keywords are available in Netbox, which can be found by surfing to the corresponding API endpoint, and clicking Filters. e.g., ``role=router`` Returns a list of dictionaries .. code-block:: bash salt myminion netbox.filter dcim devices status=1 role=router ''' ret = [] nb = _nb_obj(auth_required=True if app in AUTH_ENDPOINTS else False) nb_query = getattr(getattr(nb, app), endpoint).filter( **__utils__['args.clean_kwargs'](**kwargs) ) if nb_query: ret = [_strip_url_field(dict(i)) for i in nb_query] return sorted(ret)
[ "def", "filter_", "(", "app", ",", "endpoint", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "[", "]", "nb", "=", "_nb_obj", "(", "auth_required", "=", "True", "if", "app", "in", "AUTH_ENDPOINTS", "else", "False", ")", "nb_query", "=", "getattr", "(...
Get a list of items from NetBox. app String of netbox app, e.g., ``dcim``, ``circuits``, ``ipam`` endpoint String of app endpoint, e.g., ``sites``, ``regions``, ``devices`` kwargs Optional arguments that can be used to filter. All filter keywords are available in Netbox, which can be found by surfing to the corresponding API endpoint, and clicking Filters. e.g., ``role=router`` Returns a list of dictionaries .. code-block:: bash salt myminion netbox.filter dcim devices status=1 role=router
[ "Get", "a", "list", "of", "items", "from", "NetBox", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L140-L167
train
saltstack/salt
salt/modules/netbox.py
get_
def get_(app, endpoint, id=None, **kwargs): ''' Get a single item from NetBox. app String of netbox app, e.g., ``dcim``, ``circuits``, ``ipam`` endpoint String of app endpoint, e.g., ``sites``, ``regions``, ``devices`` Returns a single dictionary To get an item based on ID. .. code-block:: bash salt myminion netbox.get dcim devices id=123 Or using named arguments that correspond with accepted filters on the NetBox endpoint. .. code-block:: bash salt myminion netbox.get dcim devices name=my-router ''' return _dict(_get(app, endpoint, id=id, auth_required=True if app in AUTH_ENDPOINTS else False, **kwargs))
python
def get_(app, endpoint, id=None, **kwargs): ''' Get a single item from NetBox. app String of netbox app, e.g., ``dcim``, ``circuits``, ``ipam`` endpoint String of app endpoint, e.g., ``sites``, ``regions``, ``devices`` Returns a single dictionary To get an item based on ID. .. code-block:: bash salt myminion netbox.get dcim devices id=123 Or using named arguments that correspond with accepted filters on the NetBox endpoint. .. code-block:: bash salt myminion netbox.get dcim devices name=my-router ''' return _dict(_get(app, endpoint, id=id, auth_required=True if app in AUTH_ENDPOINTS else False, **kwargs))
[ "def", "get_", "(", "app", ",", "endpoint", ",", "id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "_dict", "(", "_get", "(", "app", ",", "endpoint", ",", "id", "=", "id", ",", "auth_required", "=", "True", "if", "app", "in", "AUTH_...
Get a single item from NetBox. app String of netbox app, e.g., ``dcim``, ``circuits``, ``ipam`` endpoint String of app endpoint, e.g., ``sites``, ``regions``, ``devices`` Returns a single dictionary To get an item based on ID. .. code-block:: bash salt myminion netbox.get dcim devices id=123 Or using named arguments that correspond with accepted filters on the NetBox endpoint. .. code-block:: bash salt myminion netbox.get dcim devices name=my-router
[ "Get", "a", "single", "item", "from", "NetBox", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L170-L194
train
saltstack/salt
salt/modules/netbox.py
create_manufacturer
def create_manufacturer(name): ''' .. versionadded:: 2019.2.0 Create a device manufacturer. name The name of the manufacturer, e.g., ``Juniper`` CLI Example: .. code-block:: bash salt myminion netbox.create_manufacturer Juniper ''' nb_man = get_('dcim', 'manufacturers', name=name) if nb_man: return False else: payload = {'name': name, 'slug': slugify(name)} man = _add('dcim', 'manufacturers', payload) if man: return {'dcim': {'manufacturers': payload}} else: return False
python
def create_manufacturer(name): ''' .. versionadded:: 2019.2.0 Create a device manufacturer. name The name of the manufacturer, e.g., ``Juniper`` CLI Example: .. code-block:: bash salt myminion netbox.create_manufacturer Juniper ''' nb_man = get_('dcim', 'manufacturers', name=name) if nb_man: return False else: payload = {'name': name, 'slug': slugify(name)} man = _add('dcim', 'manufacturers', payload) if man: return {'dcim': {'manufacturers': payload}} else: return False
[ "def", "create_manufacturer", "(", "name", ")", ":", "nb_man", "=", "get_", "(", "'dcim'", ",", "'manufacturers'", ",", "name", "=", "name", ")", "if", "nb_man", ":", "return", "False", "else", ":", "payload", "=", "{", "'name'", ":", "name", ",", "'sl...
.. versionadded:: 2019.2.0 Create a device manufacturer. name The name of the manufacturer, e.g., ``Juniper`` CLI Example: .. code-block:: bash salt myminion netbox.create_manufacturer Juniper
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L197-L221
train
saltstack/salt
salt/modules/netbox.py
create_device_type
def create_device_type(model, manufacturer): ''' .. versionadded:: 2019.2.0 Create a device type. If the manufacturer doesn't exist, create a new manufacturer. model String of device model, e.g., ``MX480`` manufacturer String of device manufacturer, e.g., ``Juniper`` CLI Example: .. code-block:: bash salt myminion netbox.create_device_type MX480 Juniper ''' nb_type = get_('dcim', 'device-types', model=model) if nb_type: return False nb_man = get_('dcim', 'manufacturers', name=manufacturer) new_man = None if not nb_man: new_man = create_manufacturer(manufacturer) payload = {'model': model, 'manufacturer': nb_man['id'], 'slug': slugify(model)} typ = _add('dcim', 'device-types', payload) ret_dict = {'dcim': {'device-types': payload}} if new_man: ret_dict['dcim'].update(new_man['dcim']) if typ: return ret_dict else: return False
python
def create_device_type(model, manufacturer): ''' .. versionadded:: 2019.2.0 Create a device type. If the manufacturer doesn't exist, create a new manufacturer. model String of device model, e.g., ``MX480`` manufacturer String of device manufacturer, e.g., ``Juniper`` CLI Example: .. code-block:: bash salt myminion netbox.create_device_type MX480 Juniper ''' nb_type = get_('dcim', 'device-types', model=model) if nb_type: return False nb_man = get_('dcim', 'manufacturers', name=manufacturer) new_man = None if not nb_man: new_man = create_manufacturer(manufacturer) payload = {'model': model, 'manufacturer': nb_man['id'], 'slug': slugify(model)} typ = _add('dcim', 'device-types', payload) ret_dict = {'dcim': {'device-types': payload}} if new_man: ret_dict['dcim'].update(new_man['dcim']) if typ: return ret_dict else: return False
[ "def", "create_device_type", "(", "model", ",", "manufacturer", ")", ":", "nb_type", "=", "get_", "(", "'dcim'", ",", "'device-types'", ",", "model", "=", "model", ")", "if", "nb_type", ":", "return", "False", "nb_man", "=", "get_", "(", "'dcim'", ",", "...
.. versionadded:: 2019.2.0 Create a device type. If the manufacturer doesn't exist, create a new manufacturer. model String of device model, e.g., ``MX480`` manufacturer String of device manufacturer, e.g., ``Juniper`` CLI Example: .. code-block:: bash salt myminion netbox.create_device_type MX480 Juniper
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L224-L256
train
saltstack/salt
salt/modules/netbox.py
create_device_role
def create_device_role(role, color): ''' .. versionadded:: 2019.2.0 Create a device role role String of device role, e.g., ``router`` CLI Example: .. code-block:: bash salt myminion netbox.create_device_role router ''' nb_role = get_('dcim', 'device-roles', name=role) if nb_role: return False else: payload = {'name': role, 'slug': slugify(role), 'color': color} role = _add('dcim', 'device-roles', payload) if role: return{'dcim': {'device-roles': payload}} else: return False
python
def create_device_role(role, color): ''' .. versionadded:: 2019.2.0 Create a device role role String of device role, e.g., ``router`` CLI Example: .. code-block:: bash salt myminion netbox.create_device_role router ''' nb_role = get_('dcim', 'device-roles', name=role) if nb_role: return False else: payload = {'name': role, 'slug': slugify(role), 'color': color} role = _add('dcim', 'device-roles', payload) if role: return{'dcim': {'device-roles': payload}} else: return False
[ "def", "create_device_role", "(", "role", ",", "color", ")", ":", "nb_role", "=", "get_", "(", "'dcim'", ",", "'device-roles'", ",", "name", "=", "role", ")", "if", "nb_role", ":", "return", "False", "else", ":", "payload", "=", "{", "'name'", ":", "ro...
.. versionadded:: 2019.2.0 Create a device role role String of device role, e.g., ``router`` CLI Example: .. code-block:: bash salt myminion netbox.create_device_role router
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L259-L283
train
saltstack/salt
salt/modules/netbox.py
create_platform
def create_platform(platform): ''' .. versionadded:: 2019.2.0 Create a new device platform platform String of device platform, e.g., ``junos`` CLI Example: .. code-block:: bash salt myminion netbox.create_platform junos ''' nb_platform = get_('dcim', 'platforms', slug=slugify(platform)) if nb_platform: return False else: payload = {'name': platform, 'slug': slugify(platform)} plat = _add('dcim', 'platforms', payload) if plat: return {'dcim': {'platforms': payload}} else: return False
python
def create_platform(platform): ''' .. versionadded:: 2019.2.0 Create a new device platform platform String of device platform, e.g., ``junos`` CLI Example: .. code-block:: bash salt myminion netbox.create_platform junos ''' nb_platform = get_('dcim', 'platforms', slug=slugify(platform)) if nb_platform: return False else: payload = {'name': platform, 'slug': slugify(platform)} plat = _add('dcim', 'platforms', payload) if plat: return {'dcim': {'platforms': payload}} else: return False
[ "def", "create_platform", "(", "platform", ")", ":", "nb_platform", "=", "get_", "(", "'dcim'", ",", "'platforms'", ",", "slug", "=", "slugify", "(", "platform", ")", ")", "if", "nb_platform", ":", "return", "False", "else", ":", "payload", "=", "{", "'n...
.. versionadded:: 2019.2.0 Create a new device platform platform String of device platform, e.g., ``junos`` CLI Example: .. code-block:: bash salt myminion netbox.create_platform junos
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L286-L310
train
saltstack/salt
salt/modules/netbox.py
create_site
def create_site(site): ''' .. versionadded:: 2019.2.0 Create a new device site site String of device site, e.g., ``BRU`` CLI Example: .. code-block:: bash salt myminion netbox.create_site BRU ''' nb_site = get_('dcim', 'sites', name=site) if nb_site: return False else: payload = {'name': site, 'slug': slugify(site)} site = _add('dcim', 'sites', payload) if site: return {'dcim': {'sites': payload}} else: return False
python
def create_site(site): ''' .. versionadded:: 2019.2.0 Create a new device site site String of device site, e.g., ``BRU`` CLI Example: .. code-block:: bash salt myminion netbox.create_site BRU ''' nb_site = get_('dcim', 'sites', name=site) if nb_site: return False else: payload = {'name': site, 'slug': slugify(site)} site = _add('dcim', 'sites', payload) if site: return {'dcim': {'sites': payload}} else: return False
[ "def", "create_site", "(", "site", ")", ":", "nb_site", "=", "get_", "(", "'dcim'", ",", "'sites'", ",", "name", "=", "site", ")", "if", "nb_site", ":", "return", "False", "else", ":", "payload", "=", "{", "'name'", ":", "site", ",", "'slug'", ":", ...
.. versionadded:: 2019.2.0 Create a new device site site String of device site, e.g., ``BRU`` CLI Example: .. code-block:: bash salt myminion netbox.create_site BRU
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L313-L337
train
saltstack/salt
salt/modules/netbox.py
create_device
def create_device(name, role, model, manufacturer, site): ''' .. versionadded:: 2019.2.0 Create a new device with a name, role, model, manufacturer and site. All these components need to be already in Netbox. name The name of the device, e.g., ``edge_router`` role String of device role, e.g., ``router`` model String of device model, e.g., ``MX480`` manufacturer String of device manufacturer, e.g., ``Juniper`` site String of device site, e.g., ``BRU`` CLI Example: .. code-block:: bash salt myminion netbox.create_device edge_router router MX480 Juniper BRU ''' try: nb_role = get_('dcim', 'device-roles', name=role) if not nb_role: return False nb_type = get_('dcim', 'device-types', model=model) if not nb_type: return False nb_site = get_('dcim', 'sites', name=site) if not nb_site: return False status = {'label': "Active", 'value': 1} except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False payload = {'name': name, 'display_name': name, 'slug': slugify(name), 'device_type': nb_type['id'], 'device_role': nb_role['id'], 'site': nb_site['id']} new_dev = _add('dcim', 'devices', payload) if new_dev: return {'dcim': {'devices': payload}} else: return False
python
def create_device(name, role, model, manufacturer, site): ''' .. versionadded:: 2019.2.0 Create a new device with a name, role, model, manufacturer and site. All these components need to be already in Netbox. name The name of the device, e.g., ``edge_router`` role String of device role, e.g., ``router`` model String of device model, e.g., ``MX480`` manufacturer String of device manufacturer, e.g., ``Juniper`` site String of device site, e.g., ``BRU`` CLI Example: .. code-block:: bash salt myminion netbox.create_device edge_router router MX480 Juniper BRU ''' try: nb_role = get_('dcim', 'device-roles', name=role) if not nb_role: return False nb_type = get_('dcim', 'device-types', model=model) if not nb_type: return False nb_site = get_('dcim', 'sites', name=site) if not nb_site: return False status = {'label': "Active", 'value': 1} except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False payload = {'name': name, 'display_name': name, 'slug': slugify(name), 'device_type': nb_type['id'], 'device_role': nb_role['id'], 'site': nb_site['id']} new_dev = _add('dcim', 'devices', payload) if new_dev: return {'dcim': {'devices': payload}} else: return False
[ "def", "create_device", "(", "name", ",", "role", ",", "model", ",", "manufacturer", ",", "site", ")", ":", "try", ":", "nb_role", "=", "get_", "(", "'dcim'", ",", "'device-roles'", ",", "name", "=", "role", ")", "if", "not", "nb_role", ":", "return", ...
.. versionadded:: 2019.2.0 Create a new device with a name, role, model, manufacturer and site. All these components need to be already in Netbox. name The name of the device, e.g., ``edge_router`` role String of device role, e.g., ``router`` model String of device model, e.g., ``MX480`` manufacturer String of device manufacturer, e.g., ``Juniper`` site String of device site, e.g., ``BRU`` CLI Example: .. code-block:: bash salt myminion netbox.create_device edge_router router MX480 Juniper BRU
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L340-L391
train
saltstack/salt
salt/modules/netbox.py
update_device
def update_device(name, **kwargs): ''' .. versionadded:: 2019.2.0 Add attributes to an existing device, identified by name. name The name of the device, e.g., ``edge_router`` kwargs Arguments to change in device, e.g., ``serial=JN2932930`` CLI Example: .. code-block:: bash salt myminion netbox.update_device edge_router serial=JN2932920 ''' kwargs = __utils__['args.clean_kwargs'](**kwargs) nb_device = _get('dcim', 'devices', auth_required=True, name=name) for k, v in kwargs.items(): setattr(nb_device, k, v) try: nb_device.save() return {'dcim': {'devices': kwargs}} except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False
python
def update_device(name, **kwargs): ''' .. versionadded:: 2019.2.0 Add attributes to an existing device, identified by name. name The name of the device, e.g., ``edge_router`` kwargs Arguments to change in device, e.g., ``serial=JN2932930`` CLI Example: .. code-block:: bash salt myminion netbox.update_device edge_router serial=JN2932920 ''' kwargs = __utils__['args.clean_kwargs'](**kwargs) nb_device = _get('dcim', 'devices', auth_required=True, name=name) for k, v in kwargs.items(): setattr(nb_device, k, v) try: nb_device.save() return {'dcim': {'devices': kwargs}} except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False
[ "def", "update_device", "(", "name", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "__utils__", "[", "'args.clean_kwargs'", "]", "(", "*", "*", "kwargs", ")", "nb_device", "=", "_get", "(", "'dcim'", ",", "'devices'", ",", "auth_required", "=", "True...
.. versionadded:: 2019.2.0 Add attributes to an existing device, identified by name. name The name of the device, e.g., ``edge_router`` kwargs Arguments to change in device, e.g., ``serial=JN2932930`` CLI Example: .. code-block:: bash salt myminion netbox.update_device edge_router serial=JN2932920
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L394-L420
train
saltstack/salt
salt/modules/netbox.py
create_inventory_item
def create_inventory_item(device_name, item_name, manufacturer_name=None, serial='', part_id='', description=''): ''' .. versionadded:: 2019.2.0 Add an inventory item to an existing device. device_name The name of the device, e.g., ``edge_router``. item_name String of inventory item name, e.g., ``Transceiver``. manufacturer_name String of inventory item manufacturer, e.g., ``Fiberstore``. serial String of inventory item serial, e.g., ``FS1238931``. part_id String of inventory item part id, e.g., ``740-01234``. description String of inventory item description, e.g., ``SFP+-10G-LR``. CLI Example: .. code-block:: bash salt myminion netbox.create_inventory_item edge_router Transceiver part_id=740-01234 ''' nb_device = get_('dcim', 'devices', name=device_name) if not nb_device: return False if manufacturer_name: nb_man = get_('dcim', 'manufacturers', name=manufacturer_name) if not nb_man: create_manufacturer(manufacturer_name) nb_man = get_('dcim', 'manufacturers', name=manufacturer_name) payload = {'device': nb_device['id'], 'name': item_name, 'description': description, 'serial': serial, 'part_id': part_id, 'parent': None} if manufacturer_name: payload['manufacturer'] = nb_man['id'] done = _add('dcim', 'inventory-items', payload) if done: return {'dcim': {'inventory-items': payload}} else: return done
python
def create_inventory_item(device_name, item_name, manufacturer_name=None, serial='', part_id='', description=''): ''' .. versionadded:: 2019.2.0 Add an inventory item to an existing device. device_name The name of the device, e.g., ``edge_router``. item_name String of inventory item name, e.g., ``Transceiver``. manufacturer_name String of inventory item manufacturer, e.g., ``Fiberstore``. serial String of inventory item serial, e.g., ``FS1238931``. part_id String of inventory item part id, e.g., ``740-01234``. description String of inventory item description, e.g., ``SFP+-10G-LR``. CLI Example: .. code-block:: bash salt myminion netbox.create_inventory_item edge_router Transceiver part_id=740-01234 ''' nb_device = get_('dcim', 'devices', name=device_name) if not nb_device: return False if manufacturer_name: nb_man = get_('dcim', 'manufacturers', name=manufacturer_name) if not nb_man: create_manufacturer(manufacturer_name) nb_man = get_('dcim', 'manufacturers', name=manufacturer_name) payload = {'device': nb_device['id'], 'name': item_name, 'description': description, 'serial': serial, 'part_id': part_id, 'parent': None} if manufacturer_name: payload['manufacturer'] = nb_man['id'] done = _add('dcim', 'inventory-items', payload) if done: return {'dcim': {'inventory-items': payload}} else: return done
[ "def", "create_inventory_item", "(", "device_name", ",", "item_name", ",", "manufacturer_name", "=", "None", ",", "serial", "=", "''", ",", "part_id", "=", "''", ",", "description", "=", "''", ")", ":", "nb_device", "=", "get_", "(", "'dcim'", ",", "'devic...
.. versionadded:: 2019.2.0 Add an inventory item to an existing device. device_name The name of the device, e.g., ``edge_router``. item_name String of inventory item name, e.g., ``Transceiver``. manufacturer_name String of inventory item manufacturer, e.g., ``Fiberstore``. serial String of inventory item serial, e.g., ``FS1238931``. part_id String of inventory item part id, e.g., ``740-01234``. description String of inventory item description, e.g., ``SFP+-10G-LR``. CLI Example: .. code-block:: bash salt myminion netbox.create_inventory_item edge_router Transceiver part_id=740-01234
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L423-L473
train
saltstack/salt
salt/modules/netbox.py
delete_inventory_item
def delete_inventory_item(item_id): ''' .. versionadded:: 2019.2.0 Remove an item from a devices inventory. Identified by the netbox id item_id Integer of item to be deleted CLI Example: .. code-block:: bash salt myminion netbox.delete_inventory_item 1354 ''' nb_inventory_item = _get('dcim', 'inventory-items', auth_required=True, id=item_id) nb_inventory_item.delete() return {'DELETE': {'dcim': {'inventory-items': item_id}}}
python
def delete_inventory_item(item_id): ''' .. versionadded:: 2019.2.0 Remove an item from a devices inventory. Identified by the netbox id item_id Integer of item to be deleted CLI Example: .. code-block:: bash salt myminion netbox.delete_inventory_item 1354 ''' nb_inventory_item = _get('dcim', 'inventory-items', auth_required=True, id=item_id) nb_inventory_item.delete() return {'DELETE': {'dcim': {'inventory-items': item_id}}}
[ "def", "delete_inventory_item", "(", "item_id", ")", ":", "nb_inventory_item", "=", "_get", "(", "'dcim'", ",", "'inventory-items'", ",", "auth_required", "=", "True", ",", "id", "=", "item_id", ")", "nb_inventory_item", ".", "delete", "(", ")", "return", "{",...
.. versionadded:: 2019.2.0 Remove an item from a devices inventory. Identified by the netbox id item_id Integer of item to be deleted CLI Example: .. code-block:: bash salt myminion netbox.delete_inventory_item 1354
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L476-L493
train
saltstack/salt
salt/modules/netbox.py
create_interface_connection
def create_interface_connection(interface_a, interface_b): ''' .. versionadded:: 2019.2.0 Create an interface connection between 2 interfaces interface_a Interface id for Side A interface_b Interface id for Side B CLI Example: .. code-block:: bash salt myminion netbox.create_interface_connection 123 456 ''' payload = {'interface_a': interface_a, 'interface_b': interface_b} ret = _add('dcim', 'interface-connections', payload) if ret: return {'dcim': {'interface-connections': {ret['id']: payload}}} else: return ret
python
def create_interface_connection(interface_a, interface_b): ''' .. versionadded:: 2019.2.0 Create an interface connection between 2 interfaces interface_a Interface id for Side A interface_b Interface id for Side B CLI Example: .. code-block:: bash salt myminion netbox.create_interface_connection 123 456 ''' payload = {'interface_a': interface_a, 'interface_b': interface_b} ret = _add('dcim', 'interface-connections', payload) if ret: return {'dcim': {'interface-connections': {ret['id']: payload}}} else: return ret
[ "def", "create_interface_connection", "(", "interface_a", ",", "interface_b", ")", ":", "payload", "=", "{", "'interface_a'", ":", "interface_a", ",", "'interface_b'", ":", "interface_b", "}", "ret", "=", "_add", "(", "'dcim'", ",", "'interface-connections'", ",",...
.. versionadded:: 2019.2.0 Create an interface connection between 2 interfaces interface_a Interface id for Side A interface_b Interface id for Side B CLI Example: .. code-block:: bash salt myminion netbox.create_interface_connection 123 456
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L496-L519
train
saltstack/salt
salt/modules/netbox.py
get_interfaces
def get_interfaces(device_name=None, **kwargs): ''' .. versionadded:: 2019.2.0 Returns interfaces for a specific device using arbitrary netbox filters device_name The name of the device, e.g., ``edge_router`` kwargs Optional arguments to be used for filtering CLI Example: .. code-block:: bash salt myminion netbox.get_interfaces edge_router name="et-0/0/5" ''' if not device_name: device_name = __opts__['id'] netbox_device = get_('dcim', 'devices', name=device_name) return filter_('dcim', 'interfaces', device_id=netbox_device['id'], **kwargs)
python
def get_interfaces(device_name=None, **kwargs): ''' .. versionadded:: 2019.2.0 Returns interfaces for a specific device using arbitrary netbox filters device_name The name of the device, e.g., ``edge_router`` kwargs Optional arguments to be used for filtering CLI Example: .. code-block:: bash salt myminion netbox.get_interfaces edge_router name="et-0/0/5" ''' if not device_name: device_name = __opts__['id'] netbox_device = get_('dcim', 'devices', name=device_name) return filter_('dcim', 'interfaces', device_id=netbox_device['id'], **kwargs)
[ "def", "get_interfaces", "(", "device_name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "device_name", ":", "device_name", "=", "__opts__", "[", "'id'", "]", "netbox_device", "=", "get_", "(", "'dcim'", ",", "'devices'", ",", "name", "=...
.. versionadded:: 2019.2.0 Returns interfaces for a specific device using arbitrary netbox filters device_name The name of the device, e.g., ``edge_router`` kwargs Optional arguments to be used for filtering CLI Example: .. code-block:: bash salt myminion netbox.get_interfaces edge_router name="et-0/0/5"
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L522-L546
train
saltstack/salt
salt/modules/netbox.py
openconfig_interfaces
def openconfig_interfaces(device_name=None): ''' .. versionadded:: 2019.2.0 Return a dictionary structured as standardised in the `openconfig-interfaces <http://ops.openconfig.net/branches/master/openconfig-interfaces.html>`_ YANG model, containing physical and configuration data available in Netbox, e.g., IP addresses, MTU, enabled / disabled, etc. device_name: ``None`` The name of the device to query the interface data for. If not provided, will use the Minion ID. CLI Example: .. code-block:: bash salt '*' netbox.openconfig_interfaces salt '*' netbox.openconfig_interfaces device_name=cr1.thn.lon ''' oc_if = {} interfaces = get_interfaces(device_name=device_name) ipaddresses = get_ipaddresses(device_name=device_name) for interface in interfaces: if_name, if_unit = _if_name_unit(interface['name']) if if_name not in oc_if: oc_if[if_name] = { 'config': { 'name': if_name }, 'subinterfaces': {'subinterface': {}} } if if_unit == '0': oc_if[if_name]['config']['enabled'] = interface['enabled'] if interface['description']: if if_name == interface['name']: # When that's a real unit 0 interface # Otherwise it will inherit the description from the subif oc_if[if_name]['config']['description'] = str(interface['description']) else: subif_descr = { 'subinterfaces': { 'subinterface': { if_unit: { 'config': { 'description': str(interface['description']) } } } } } oc_if[if_name] = __utils__['dictupdate.update'](oc_if[if_name], subif_descr) if interface['mtu']: oc_if[if_name]['config']['mtu'] = int(interface['mtu']) else: oc_if[if_name]['subinterfaces']['subinterface'][if_unit] = { 'config': { 'index': int(if_unit), 'enabled': interface['enabled'] } } if interface['description']: oc_if[if_name]['subinterfaces']['subinterface'][if_unit]['config']['description'] =\ str(interface['description']) for ipaddress in ipaddresses: ip, prefix_length = ipaddress['address'].split('/') if_name = ipaddress['interface']['name'] if_name, if_unit = _if_name_unit(if_name) ipvkey = 'ipv{}'.format(ipaddress['family']) if if_unit not in oc_if[if_name]['subinterfaces']['subinterface']: oc_if[if_name]['subinterfaces']['subinterface'][if_unit] = { 'config': { 'index': int(if_unit), 'enabled': True } } if ipvkey not in oc_if[if_name]['subinterfaces']['subinterface'][if_unit]: oc_if[if_name]['subinterfaces']['subinterface'][if_unit][ipvkey] = { 'addresses': { 'address': {} } } oc_if[if_name]['subinterfaces']['subinterface'][if_unit][ipvkey]['addresses']['address'][ip] = { 'config': { 'ip': ip, 'prefix_length': int(prefix_length) } } return { 'interfaces': { 'interface': oc_if } }
python
def openconfig_interfaces(device_name=None): ''' .. versionadded:: 2019.2.0 Return a dictionary structured as standardised in the `openconfig-interfaces <http://ops.openconfig.net/branches/master/openconfig-interfaces.html>`_ YANG model, containing physical and configuration data available in Netbox, e.g., IP addresses, MTU, enabled / disabled, etc. device_name: ``None`` The name of the device to query the interface data for. If not provided, will use the Minion ID. CLI Example: .. code-block:: bash salt '*' netbox.openconfig_interfaces salt '*' netbox.openconfig_interfaces device_name=cr1.thn.lon ''' oc_if = {} interfaces = get_interfaces(device_name=device_name) ipaddresses = get_ipaddresses(device_name=device_name) for interface in interfaces: if_name, if_unit = _if_name_unit(interface['name']) if if_name not in oc_if: oc_if[if_name] = { 'config': { 'name': if_name }, 'subinterfaces': {'subinterface': {}} } if if_unit == '0': oc_if[if_name]['config']['enabled'] = interface['enabled'] if interface['description']: if if_name == interface['name']: # When that's a real unit 0 interface # Otherwise it will inherit the description from the subif oc_if[if_name]['config']['description'] = str(interface['description']) else: subif_descr = { 'subinterfaces': { 'subinterface': { if_unit: { 'config': { 'description': str(interface['description']) } } } } } oc_if[if_name] = __utils__['dictupdate.update'](oc_if[if_name], subif_descr) if interface['mtu']: oc_if[if_name]['config']['mtu'] = int(interface['mtu']) else: oc_if[if_name]['subinterfaces']['subinterface'][if_unit] = { 'config': { 'index': int(if_unit), 'enabled': interface['enabled'] } } if interface['description']: oc_if[if_name]['subinterfaces']['subinterface'][if_unit]['config']['description'] =\ str(interface['description']) for ipaddress in ipaddresses: ip, prefix_length = ipaddress['address'].split('/') if_name = ipaddress['interface']['name'] if_name, if_unit = _if_name_unit(if_name) ipvkey = 'ipv{}'.format(ipaddress['family']) if if_unit not in oc_if[if_name]['subinterfaces']['subinterface']: oc_if[if_name]['subinterfaces']['subinterface'][if_unit] = { 'config': { 'index': int(if_unit), 'enabled': True } } if ipvkey not in oc_if[if_name]['subinterfaces']['subinterface'][if_unit]: oc_if[if_name]['subinterfaces']['subinterface'][if_unit][ipvkey] = { 'addresses': { 'address': {} } } oc_if[if_name]['subinterfaces']['subinterface'][if_unit][ipvkey]['addresses']['address'][ip] = { 'config': { 'ip': ip, 'prefix_length': int(prefix_length) } } return { 'interfaces': { 'interface': oc_if } }
[ "def", "openconfig_interfaces", "(", "device_name", "=", "None", ")", ":", "oc_if", "=", "{", "}", "interfaces", "=", "get_interfaces", "(", "device_name", "=", "device_name", ")", "ipaddresses", "=", "get_ipaddresses", "(", "device_name", "=", "device_name", ")...
.. versionadded:: 2019.2.0 Return a dictionary structured as standardised in the `openconfig-interfaces <http://ops.openconfig.net/branches/master/openconfig-interfaces.html>`_ YANG model, containing physical and configuration data available in Netbox, e.g., IP addresses, MTU, enabled / disabled, etc. device_name: ``None`` The name of the device to query the interface data for. If not provided, will use the Minion ID. CLI Example: .. code-block:: bash salt '*' netbox.openconfig_interfaces salt '*' netbox.openconfig_interfaces device_name=cr1.thn.lon
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L549-L641
train
saltstack/salt
salt/modules/netbox.py
openconfig_lacp
def openconfig_lacp(device_name=None): ''' .. versionadded:: 2019.2.0 Return a dictionary structured as standardised in the `openconfig-lacp <http://ops.openconfig.net/branches/master/openconfig-lacp.html>`_ YANG model, with configuration data for Link Aggregation Control Protocol (LACP) for aggregate interfaces. .. note:: The ``interval`` and ``lacp_mode`` keys have the values set as ``SLOW`` and ``ACTIVE`` respectively, as this data is not currently available in Netbox, therefore defaulting to the values defined in the standard. See `interval <http://ops.openconfig.net/branches/master/docs/openconfig-lacp.html#lacp-interfaces-interface-config-interval>`_ and `lacp-mode <http://ops.openconfig.net/branches/master/docs/openconfig-lacp.html#lacp-interfaces-interface-config-lacp-mode>`_ for further details. device_name: ``None`` The name of the device to query the LACP information for. If not provided, will use the Minion ID. CLI Example: .. code-block:: bash salt '*' netbox.openconfig_lacp salt '*' netbox.openconfig_lacp device_name=cr1.thn.lon ''' oc_lacp = {} interfaces = get_interfaces(device_name=device_name) for interface in interfaces: if not interface['lag']: continue if_name, if_unit = _if_name_unit(interface['name']) parent_if = interface['lag']['name'] if parent_if not in oc_lacp: oc_lacp[parent_if] = { 'config': { 'name': parent_if, 'interval': 'SLOW', 'lacp_mode': 'ACTIVE' }, 'members': { 'member': {} } } oc_lacp[parent_if]['members']['member'][if_name] = {} return { 'lacp': { 'interfaces': { 'interface': oc_lacp } } }
python
def openconfig_lacp(device_name=None): ''' .. versionadded:: 2019.2.0 Return a dictionary structured as standardised in the `openconfig-lacp <http://ops.openconfig.net/branches/master/openconfig-lacp.html>`_ YANG model, with configuration data for Link Aggregation Control Protocol (LACP) for aggregate interfaces. .. note:: The ``interval`` and ``lacp_mode`` keys have the values set as ``SLOW`` and ``ACTIVE`` respectively, as this data is not currently available in Netbox, therefore defaulting to the values defined in the standard. See `interval <http://ops.openconfig.net/branches/master/docs/openconfig-lacp.html#lacp-interfaces-interface-config-interval>`_ and `lacp-mode <http://ops.openconfig.net/branches/master/docs/openconfig-lacp.html#lacp-interfaces-interface-config-lacp-mode>`_ for further details. device_name: ``None`` The name of the device to query the LACP information for. If not provided, will use the Minion ID. CLI Example: .. code-block:: bash salt '*' netbox.openconfig_lacp salt '*' netbox.openconfig_lacp device_name=cr1.thn.lon ''' oc_lacp = {} interfaces = get_interfaces(device_name=device_name) for interface in interfaces: if not interface['lag']: continue if_name, if_unit = _if_name_unit(interface['name']) parent_if = interface['lag']['name'] if parent_if not in oc_lacp: oc_lacp[parent_if] = { 'config': { 'name': parent_if, 'interval': 'SLOW', 'lacp_mode': 'ACTIVE' }, 'members': { 'member': {} } } oc_lacp[parent_if]['members']['member'][if_name] = {} return { 'lacp': { 'interfaces': { 'interface': oc_lacp } } }
[ "def", "openconfig_lacp", "(", "device_name", "=", "None", ")", ":", "oc_lacp", "=", "{", "}", "interfaces", "=", "get_interfaces", "(", "device_name", "=", "device_name", ")", "for", "interface", "in", "interfaces", ":", "if", "not", "interface", "[", "'lag...
.. versionadded:: 2019.2.0 Return a dictionary structured as standardised in the `openconfig-lacp <http://ops.openconfig.net/branches/master/openconfig-lacp.html>`_ YANG model, with configuration data for Link Aggregation Control Protocol (LACP) for aggregate interfaces. .. note:: The ``interval`` and ``lacp_mode`` keys have the values set as ``SLOW`` and ``ACTIVE`` respectively, as this data is not currently available in Netbox, therefore defaulting to the values defined in the standard. See `interval <http://ops.openconfig.net/branches/master/docs/openconfig-lacp.html#lacp-interfaces-interface-config-interval>`_ and `lacp-mode <http://ops.openconfig.net/branches/master/docs/openconfig-lacp.html#lacp-interfaces-interface-config-lacp-mode>`_ for further details. device_name: ``None`` The name of the device to query the LACP information for. If not provided, will use the Minion ID. CLI Example: .. code-block:: bash salt '*' netbox.openconfig_lacp salt '*' netbox.openconfig_lacp device_name=cr1.thn.lon
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L644-L697
train
saltstack/salt
salt/modules/netbox.py
create_interface
def create_interface(device_name, interface_name, mac_address=None, description=None, enabled=None, lag=None, lag_parent=None, form_factor=None): ''' .. versionadded:: 2019.2.0 Attach an interface to a device. If not all arguments are provided, they will default to Netbox defaults. device_name The name of the device, e.g., ``edge_router`` interface_name The name of the interface, e.g., ``TenGigE0/0/0/0`` mac_address String of mac address, e.g., ``50:87:89:73:92:C8`` description String of interface description, e.g., ``NTT`` enabled String of boolean interface status, e.g., ``True`` lag: Boolean of interface lag status, e.g., ``True`` lag_parent String of interface lag parent name, e.g., ``ae13`` form_factor Integer of form factor id, obtained through _choices API endpoint, e.g., ``200`` CLI Example: .. code-block:: bash salt myminion netbox.create_interface edge_router ae13 description="Core uplink" ''' nb_device = get_('dcim', 'devices', name=device_name) if not nb_device: return False if lag_parent: lag_interface = get_('dcim', 'interfaces', device_id=nb_device['id'], name=lag_parent) if not lag_interface: return False if not description: description = '' if not enabled: enabled = 'false' # Set default form factor to 1200. This maps to SFP+ (10GE). This should be addressed by # the _choices endpoint. payload = {'device': nb_device['id'], 'name': interface_name, 'description': description, 'enabled': enabled, 'form_factor': 1200} if form_factor is not None: payload['form_factor'] = form_factor if lag: payload['form_factor'] = 200 if lag_parent: payload['lag'] = lag_interface['id'] if mac_address: payload['mac_address'] = mac_address nb_interface = get_('dcim', 'interfaces', device_id=nb_device['id'], name=interface_name) if not nb_interface: nb_interface = _add('dcim', 'interfaces', payload) if nb_interface: return {'dcim': {'interfaces': {nb_interface['id']: payload}}} else: return nb_interface
python
def create_interface(device_name, interface_name, mac_address=None, description=None, enabled=None, lag=None, lag_parent=None, form_factor=None): ''' .. versionadded:: 2019.2.0 Attach an interface to a device. If not all arguments are provided, they will default to Netbox defaults. device_name The name of the device, e.g., ``edge_router`` interface_name The name of the interface, e.g., ``TenGigE0/0/0/0`` mac_address String of mac address, e.g., ``50:87:89:73:92:C8`` description String of interface description, e.g., ``NTT`` enabled String of boolean interface status, e.g., ``True`` lag: Boolean of interface lag status, e.g., ``True`` lag_parent String of interface lag parent name, e.g., ``ae13`` form_factor Integer of form factor id, obtained through _choices API endpoint, e.g., ``200`` CLI Example: .. code-block:: bash salt myminion netbox.create_interface edge_router ae13 description="Core uplink" ''' nb_device = get_('dcim', 'devices', name=device_name) if not nb_device: return False if lag_parent: lag_interface = get_('dcim', 'interfaces', device_id=nb_device['id'], name=lag_parent) if not lag_interface: return False if not description: description = '' if not enabled: enabled = 'false' # Set default form factor to 1200. This maps to SFP+ (10GE). This should be addressed by # the _choices endpoint. payload = {'device': nb_device['id'], 'name': interface_name, 'description': description, 'enabled': enabled, 'form_factor': 1200} if form_factor is not None: payload['form_factor'] = form_factor if lag: payload['form_factor'] = 200 if lag_parent: payload['lag'] = lag_interface['id'] if mac_address: payload['mac_address'] = mac_address nb_interface = get_('dcim', 'interfaces', device_id=nb_device['id'], name=interface_name) if not nb_interface: nb_interface = _add('dcim', 'interfaces', payload) if nb_interface: return {'dcim': {'interfaces': {nb_interface['id']: payload}}} else: return nb_interface
[ "def", "create_interface", "(", "device_name", ",", "interface_name", ",", "mac_address", "=", "None", ",", "description", "=", "None", ",", "enabled", "=", "None", ",", "lag", "=", "None", ",", "lag_parent", "=", "None", ",", "form_factor", "=", "None", "...
.. versionadded:: 2019.2.0 Attach an interface to a device. If not all arguments are provided, they will default to Netbox defaults. device_name The name of the device, e.g., ``edge_router`` interface_name The name of the interface, e.g., ``TenGigE0/0/0/0`` mac_address String of mac address, e.g., ``50:87:89:73:92:C8`` description String of interface description, e.g., ``NTT`` enabled String of boolean interface status, e.g., ``True`` lag: Boolean of interface lag status, e.g., ``True`` lag_parent String of interface lag parent name, e.g., ``ae13`` form_factor Integer of form factor id, obtained through _choices API endpoint, e.g., ``200`` CLI Example: .. code-block:: bash salt myminion netbox.create_interface edge_router ae13 description="Core uplink"
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L700-L766
train
saltstack/salt
salt/modules/netbox.py
update_interface
def update_interface(device_name, interface_name, **kwargs): ''' .. versionadded:: 2019.2.0 Update an existing interface with new attributes. device_name The name of the device, e.g., ``edge_router`` interface_name The name of the interface, e.g., ``ae13`` kwargs Arguments to change in interface, e.g., ``mac_address=50:87:69:53:32:D0`` CLI Example: .. code-block:: bash salt myminion netbox.update_interface edge_router ae13 mac_address=50:87:69:53:32:D0 ''' nb_device = get_('dcim', 'devices', name=device_name) nb_interface = _get('dcim', 'interfaces', auth_required=True, device_id=nb_device['id'], name=interface_name) if not nb_device: return False if not nb_interface: return False else: for k, v in __utils__['args.clean_kwargs'](**kwargs).items(): setattr(nb_interface, k, v) try: nb_interface.save() return {'dcim': {'interfaces': {nb_interface.id: dict(nb_interface)}}} except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False
python
def update_interface(device_name, interface_name, **kwargs): ''' .. versionadded:: 2019.2.0 Update an existing interface with new attributes. device_name The name of the device, e.g., ``edge_router`` interface_name The name of the interface, e.g., ``ae13`` kwargs Arguments to change in interface, e.g., ``mac_address=50:87:69:53:32:D0`` CLI Example: .. code-block:: bash salt myminion netbox.update_interface edge_router ae13 mac_address=50:87:69:53:32:D0 ''' nb_device = get_('dcim', 'devices', name=device_name) nb_interface = _get('dcim', 'interfaces', auth_required=True, device_id=nb_device['id'], name=interface_name) if not nb_device: return False if not nb_interface: return False else: for k, v in __utils__['args.clean_kwargs'](**kwargs).items(): setattr(nb_interface, k, v) try: nb_interface.save() return {'dcim': {'interfaces': {nb_interface.id: dict(nb_interface)}}} except RequestError as e: log.error('%s, %s, %s', e.req.request.headers, e.request_body, e.error) return False
[ "def", "update_interface", "(", "device_name", ",", "interface_name", ",", "*", "*", "kwargs", ")", ":", "nb_device", "=", "get_", "(", "'dcim'", ",", "'devices'", ",", "name", "=", "device_name", ")", "nb_interface", "=", "_get", "(", "'dcim'", ",", "'int...
.. versionadded:: 2019.2.0 Update an existing interface with new attributes. device_name The name of the device, e.g., ``edge_router`` interface_name The name of the interface, e.g., ``ae13`` kwargs Arguments to change in interface, e.g., ``mac_address=50:87:69:53:32:D0`` CLI Example: .. code-block:: bash salt myminion netbox.update_interface edge_router ae13 mac_address=50:87:69:53:32:D0
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L769-L802
train
saltstack/salt
salt/modules/netbox.py
delete_interface
def delete_interface(device_name, interface_name): ''' .. versionadded:: 2019.2.0 Delete an interface from a device. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface, e.g., ``ae13`` CLI Example: .. code-block:: bash salt myminion netbox.delete_interface edge_router ae13 ''' nb_device = get_('dcim', 'devices', name=device_name) nb_interface = _get('dcim', 'interfaces', auth_required=True, device_id=nb_device['id'], name=interface_name) if nb_interface: nb_interface.delete() return {'DELETE': {'dcim': {'interfaces': {nb_interface.id: nb_interface.name}}}} return False
python
def delete_interface(device_name, interface_name): ''' .. versionadded:: 2019.2.0 Delete an interface from a device. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface, e.g., ``ae13`` CLI Example: .. code-block:: bash salt myminion netbox.delete_interface edge_router ae13 ''' nb_device = get_('dcim', 'devices', name=device_name) nb_interface = _get('dcim', 'interfaces', auth_required=True, device_id=nb_device['id'], name=interface_name) if nb_interface: nb_interface.delete() return {'DELETE': {'dcim': {'interfaces': {nb_interface.id: nb_interface.name}}}} return False
[ "def", "delete_interface", "(", "device_name", ",", "interface_name", ")", ":", "nb_device", "=", "get_", "(", "'dcim'", ",", "'devices'", ",", "name", "=", "device_name", ")", "nb_interface", "=", "_get", "(", "'dcim'", ",", "'interfaces'", ",", "auth_require...
.. versionadded:: 2019.2.0 Delete an interface from a device. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface, e.g., ``ae13`` CLI Example: .. code-block:: bash salt myminion netbox.delete_interface edge_router ae13
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L805-L828
train
saltstack/salt
salt/modules/netbox.py
make_interface_child
def make_interface_child(device_name, interface_name, parent_name): ''' .. versionadded:: 2019.2.0 Set an interface as part of a LAG. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``. parent_name The name of the LAG interface, e.g., ``ae13``. CLI Example: .. code-block:: bash salt myminion netbox.make_interface_child xe-1/0/2 ae13 ''' nb_device = get_('dcim', 'devices', name=device_name) nb_parent = get_('dcim', 'interfaces', device_id=nb_device['id'], name=parent_name) if nb_device and nb_parent: return update_interface(device_name, interface_name, lag=nb_parent['id']) else: return False
python
def make_interface_child(device_name, interface_name, parent_name): ''' .. versionadded:: 2019.2.0 Set an interface as part of a LAG. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``. parent_name The name of the LAG interface, e.g., ``ae13``. CLI Example: .. code-block:: bash salt myminion netbox.make_interface_child xe-1/0/2 ae13 ''' nb_device = get_('dcim', 'devices', name=device_name) nb_parent = get_('dcim', 'interfaces', device_id=nb_device['id'], name=parent_name) if nb_device and nb_parent: return update_interface(device_name, interface_name, lag=nb_parent['id']) else: return False
[ "def", "make_interface_child", "(", "device_name", ",", "interface_name", ",", "parent_name", ")", ":", "nb_device", "=", "get_", "(", "'dcim'", ",", "'devices'", ",", "name", "=", "device_name", ")", "nb_parent", "=", "get_", "(", "'dcim'", ",", "'interfaces'...
.. versionadded:: 2019.2.0 Set an interface as part of a LAG. device_name The name of the device, e.g., ``edge_router``. interface_name The name of the interface to be attached to LAG, e.g., ``xe-1/0/2``. parent_name The name of the LAG interface, e.g., ``ae13``. CLI Example: .. code-block:: bash salt myminion netbox.make_interface_child xe-1/0/2 ae13
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L852-L878
train
saltstack/salt
salt/modules/netbox.py
create_ipaddress
def create_ipaddress(ip_address, family, device=None, interface=None): ''' .. versionadded:: 2019.2.0 Add an IP address, and optionally attach it to an interface. ip_address The IP address and CIDR, e.g., ``192.168.1.1/24`` family Integer of IP family, e.g., ``4`` device The name of the device to attach IP to, e.g., ``edge_router`` interface The name of the interface to attach IP to, e.g., ``ae13`` CLI Example: .. code-block:: bash salt myminion netbox.create_ipaddress 192.168.1.1/24 4 device=edge_router interface=ae13 ''' nb_addr = None payload = {'family': family, 'address': ip_address} if interface and device: nb_device = get_('dcim', 'devices', name=device) if not nb_device: return False nb_interface = get_('dcim', 'interfaces', device_id=nb_device['id'], name=interface) if not nb_interface: return False nb_addr = get_('ipam', 'ip-addresses', q=ip_address, interface_id=nb_interface['id'], family=family) if nb_addr: log.error(nb_addr) return False else: payload['interface'] = nb_interface['id'] ipaddr = _add('ipam', 'ip-addresses', payload) if ipaddr: return {'ipam': {'ip-addresses': payload}} else: return ipaddr
python
def create_ipaddress(ip_address, family, device=None, interface=None): ''' .. versionadded:: 2019.2.0 Add an IP address, and optionally attach it to an interface. ip_address The IP address and CIDR, e.g., ``192.168.1.1/24`` family Integer of IP family, e.g., ``4`` device The name of the device to attach IP to, e.g., ``edge_router`` interface The name of the interface to attach IP to, e.g., ``ae13`` CLI Example: .. code-block:: bash salt myminion netbox.create_ipaddress 192.168.1.1/24 4 device=edge_router interface=ae13 ''' nb_addr = None payload = {'family': family, 'address': ip_address} if interface and device: nb_device = get_('dcim', 'devices', name=device) if not nb_device: return False nb_interface = get_('dcim', 'interfaces', device_id=nb_device['id'], name=interface) if not nb_interface: return False nb_addr = get_('ipam', 'ip-addresses', q=ip_address, interface_id=nb_interface['id'], family=family) if nb_addr: log.error(nb_addr) return False else: payload['interface'] = nb_interface['id'] ipaddr = _add('ipam', 'ip-addresses', payload) if ipaddr: return {'ipam': {'ip-addresses': payload}} else: return ipaddr
[ "def", "create_ipaddress", "(", "ip_address", ",", "family", ",", "device", "=", "None", ",", "interface", "=", "None", ")", ":", "nb_addr", "=", "None", "payload", "=", "{", "'family'", ":", "family", ",", "'address'", ":", "ip_address", "}", "if", "int...
.. versionadded:: 2019.2.0 Add an IP address, and optionally attach it to an interface. ip_address The IP address and CIDR, e.g., ``192.168.1.1/24`` family Integer of IP family, e.g., ``4`` device The name of the device to attach IP to, e.g., ``edge_router`` interface The name of the interface to attach IP to, e.g., ``ae13`` CLI Example: .. code-block:: bash salt myminion netbox.create_ipaddress 192.168.1.1/24 4 device=edge_router interface=ae13
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L907-L947
train
saltstack/salt
salt/modules/netbox.py
delete_ipaddress
def delete_ipaddress(ipaddr_id): ''' .. versionadded:: 2019.2.0 Delete an IP address. IP addresses in Netbox are a combination of address and the interface it is assigned to. id The Netbox id for the IP address. CLI Example: .. code-block:: bash salt myminion netbox.delete_ipaddress 9002 ''' nb_ipaddr = _get('ipam', 'ip-addresses', auth_required=True, id=ipaddr_id) if nb_ipaddr: nb_ipaddr.delete() return {'DELETE': {'ipam': {'ip-address': ipaddr_id}}} return False
python
def delete_ipaddress(ipaddr_id): ''' .. versionadded:: 2019.2.0 Delete an IP address. IP addresses in Netbox are a combination of address and the interface it is assigned to. id The Netbox id for the IP address. CLI Example: .. code-block:: bash salt myminion netbox.delete_ipaddress 9002 ''' nb_ipaddr = _get('ipam', 'ip-addresses', auth_required=True, id=ipaddr_id) if nb_ipaddr: nb_ipaddr.delete() return {'DELETE': {'ipam': {'ip-address': ipaddr_id}}} return False
[ "def", "delete_ipaddress", "(", "ipaddr_id", ")", ":", "nb_ipaddr", "=", "_get", "(", "'ipam'", ",", "'ip-addresses'", ",", "auth_required", "=", "True", ",", "id", "=", "ipaddr_id", ")", "if", "nb_ipaddr", ":", "nb_ipaddr", ".", "delete", "(", ")", "retur...
.. versionadded:: 2019.2.0 Delete an IP address. IP addresses in Netbox are a combination of address and the interface it is assigned to. id The Netbox id for the IP address. CLI Example: .. code-block:: bash salt myminion netbox.delete_ipaddress 9002
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L950-L971
train
saltstack/salt
salt/modules/netbox.py
create_circuit_provider
def create_circuit_provider(name, asn=None): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit provider name The name of the circuit provider asn The ASN of the circuit provider CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_provider Telia 1299 ''' nb_circuit_provider = get_('circuits', 'providers', name=name) payload = {} if nb_circuit_provider: if nb_circuit_provider['asn'] == asn: return False else: log.error('Duplicate provider with different ASN: %s: %s', name, asn) raise CommandExecutionError( 'Duplicate provider with different ASN: {}: {}'.format(name, asn) ) else: payload = { 'name': name, 'slug': slugify(name) } if asn: payload['asn'] = asn circuit_provider = _add('circuits', 'providers', payload) if circuit_provider: return {'circuits': {'providers': {circuit_provider['id']: payload}}} else: return circuit_provider
python
def create_circuit_provider(name, asn=None): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit provider name The name of the circuit provider asn The ASN of the circuit provider CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_provider Telia 1299 ''' nb_circuit_provider = get_('circuits', 'providers', name=name) payload = {} if nb_circuit_provider: if nb_circuit_provider['asn'] == asn: return False else: log.error('Duplicate provider with different ASN: %s: %s', name, asn) raise CommandExecutionError( 'Duplicate provider with different ASN: {}: {}'.format(name, asn) ) else: payload = { 'name': name, 'slug': slugify(name) } if asn: payload['asn'] = asn circuit_provider = _add('circuits', 'providers', payload) if circuit_provider: return {'circuits': {'providers': {circuit_provider['id']: payload}}} else: return circuit_provider
[ "def", "create_circuit_provider", "(", "name", ",", "asn", "=", "None", ")", ":", "nb_circuit_provider", "=", "get_", "(", "'circuits'", ",", "'providers'", ",", "name", "=", "name", ")", "payload", "=", "{", "}", "if", "nb_circuit_provider", ":", "if", "n...
.. versionadded:: 2019.2.0 Create a new Netbox circuit provider name The name of the circuit provider asn The ASN of the circuit provider CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_provider Telia 1299
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L974-L1013
train
saltstack/salt
salt/modules/netbox.py
get_circuit_provider
def get_circuit_provider(name, asn=None): ''' .. versionadded:: 2019.2.0 Get a circuit provider with a given name and optional ASN. name The name of the circuit provider asn The ASN of the circuit provider CLI Example: .. code-block:: bash salt myminion netbox.get_circuit_provider Telia 1299 ''' if asn: nb_circuit_provider = get_('circuits', 'providers', asn=asn) else: nb_circuit_provider = get_('circuits', 'providers', name=name) return nb_circuit_provider
python
def get_circuit_provider(name, asn=None): ''' .. versionadded:: 2019.2.0 Get a circuit provider with a given name and optional ASN. name The name of the circuit provider asn The ASN of the circuit provider CLI Example: .. code-block:: bash salt myminion netbox.get_circuit_provider Telia 1299 ''' if asn: nb_circuit_provider = get_('circuits', 'providers', asn=asn) else: nb_circuit_provider = get_('circuits', 'providers', name=name) return nb_circuit_provider
[ "def", "get_circuit_provider", "(", "name", ",", "asn", "=", "None", ")", ":", "if", "asn", ":", "nb_circuit_provider", "=", "get_", "(", "'circuits'", ",", "'providers'", ",", "asn", "=", "asn", ")", "else", ":", "nb_circuit_provider", "=", "get_", "(", ...
.. versionadded:: 2019.2.0 Get a circuit provider with a given name and optional ASN. name The name of the circuit provider asn The ASN of the circuit provider CLI Example: .. code-block:: bash salt myminion netbox.get_circuit_provider Telia 1299
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L1016-L1037
train
saltstack/salt
salt/modules/netbox.py
create_circuit_type
def create_circuit_type(name): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit type. name The name of the circuit type CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_type Transit ''' nb_circuit_type = get_('circuits', 'circuit-types', slug=slugify(name)) if nb_circuit_type: return False else: payload = { 'name': name, 'slug': slugify(name) } circuit_type = _add('circuits', 'circuit-types', payload) if circuit_type: return {'circuits': {'circuit-types': {circuit_type['id']: payload}}} else: return circuit_type
python
def create_circuit_type(name): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit type. name The name of the circuit type CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_type Transit ''' nb_circuit_type = get_('circuits', 'circuit-types', slug=slugify(name)) if nb_circuit_type: return False else: payload = { 'name': name, 'slug': slugify(name) } circuit_type = _add('circuits', 'circuit-types', payload) if circuit_type: return {'circuits': {'circuit-types': {circuit_type['id']: payload}}} else: return circuit_type
[ "def", "create_circuit_type", "(", "name", ")", ":", "nb_circuit_type", "=", "get_", "(", "'circuits'", ",", "'circuit-types'", ",", "slug", "=", "slugify", "(", "name", ")", ")", "if", "nb_circuit_type", ":", "return", "False", "else", ":", "payload", "=", ...
.. versionadded:: 2019.2.0 Create a new Netbox circuit type. name The name of the circuit type CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_type Transit
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L1040-L1067
train
saltstack/salt
salt/modules/netbox.py
create_circuit
def create_circuit(name, provider_id, circuit_type, description=None): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit name Name of the circuit provider_id The netbox id of the circuit provider circuit_type The name of the circuit type asn The ASN of the circuit provider description The description of the circuit CLI Example: .. code-block:: bash salt myminion netbox.create_circuit NEW_CIRCUIT_01 Telia Transit 1299 "New Telia circuit" ''' nb_circuit_provider = get_('circuits', 'providers', provider_id) nb_circuit_type = get_('circuits', 'circuit-types', slug=slugify(circuit_type)) if nb_circuit_provider and nb_circuit_type: payload = { 'cid': name, 'provider': nb_circuit_provider['id'], 'type': nb_circuit_type['id'] } if description: payload['description'] = description nb_circuit = get_('circuits', 'circuits', cid=name) if nb_circuit: return False circuit = _add('circuits', 'circuits', payload) if circuit: return {'circuits': {'circuits': {circuit['id']: payload}}} else: return circuit else: return False
python
def create_circuit(name, provider_id, circuit_type, description=None): ''' .. versionadded:: 2019.2.0 Create a new Netbox circuit name Name of the circuit provider_id The netbox id of the circuit provider circuit_type The name of the circuit type asn The ASN of the circuit provider description The description of the circuit CLI Example: .. code-block:: bash salt myminion netbox.create_circuit NEW_CIRCUIT_01 Telia Transit 1299 "New Telia circuit" ''' nb_circuit_provider = get_('circuits', 'providers', provider_id) nb_circuit_type = get_('circuits', 'circuit-types', slug=slugify(circuit_type)) if nb_circuit_provider and nb_circuit_type: payload = { 'cid': name, 'provider': nb_circuit_provider['id'], 'type': nb_circuit_type['id'] } if description: payload['description'] = description nb_circuit = get_('circuits', 'circuits', cid=name) if nb_circuit: return False circuit = _add('circuits', 'circuits', payload) if circuit: return {'circuits': {'circuits': {circuit['id']: payload}}} else: return circuit else: return False
[ "def", "create_circuit", "(", "name", ",", "provider_id", ",", "circuit_type", ",", "description", "=", "None", ")", ":", "nb_circuit_provider", "=", "get_", "(", "'circuits'", ",", "'providers'", ",", "provider_id", ")", "nb_circuit_type", "=", "get_", "(", "...
.. versionadded:: 2019.2.0 Create a new Netbox circuit name Name of the circuit provider_id The netbox id of the circuit provider circuit_type The name of the circuit type asn The ASN of the circuit provider description The description of the circuit CLI Example: .. code-block:: bash salt myminion netbox.create_circuit NEW_CIRCUIT_01 Telia Transit 1299 "New Telia circuit"
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L1070-L1113
train
saltstack/salt
salt/modules/netbox.py
create_circuit_termination
def create_circuit_termination(circuit, interface, device, speed, xconnect_id=None, term_side='A'): ''' .. versionadded:: 2019.2.0 Terminate a circuit on an interface circuit The name of the circuit interface The name of the interface to terminate on device The name of the device the interface belongs to speed The speed of the circuit, in Kbps xconnect_id The cross-connect identifier term_side The side of the circuit termination CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_termination NEW_CIRCUIT_01 xe-0/0/1 myminion 10000 xconnect_id=XCON01 ''' nb_device = get_('dcim', 'devices', name=device) nb_interface = get_('dcim', 'interfaces', device_id=nb_device['id'], name=interface) nb_circuit = get_('circuits', 'circuits', cid=circuit) if nb_circuit and nb_device: nb_termination = get_('circuits', 'circuit-terminations', q=nb_circuit['cid']) if nb_termination: return False payload = { 'circuit': nb_circuit['id'], 'interface': nb_interface['id'], 'site': nb_device['site']['id'], 'port_speed': speed, 'term_side': term_side } if xconnect_id: payload['xconnect_id'] = xconnect_id circuit_termination = _add('circuits', 'circuit-terminations', payload) if circuit_termination: return {'circuits': {'circuit-terminations': {circuit_termination['id']: payload}}} else: return circuit_termination
python
def create_circuit_termination(circuit, interface, device, speed, xconnect_id=None, term_side='A'): ''' .. versionadded:: 2019.2.0 Terminate a circuit on an interface circuit The name of the circuit interface The name of the interface to terminate on device The name of the device the interface belongs to speed The speed of the circuit, in Kbps xconnect_id The cross-connect identifier term_side The side of the circuit termination CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_termination NEW_CIRCUIT_01 xe-0/0/1 myminion 10000 xconnect_id=XCON01 ''' nb_device = get_('dcim', 'devices', name=device) nb_interface = get_('dcim', 'interfaces', device_id=nb_device['id'], name=interface) nb_circuit = get_('circuits', 'circuits', cid=circuit) if nb_circuit and nb_device: nb_termination = get_('circuits', 'circuit-terminations', q=nb_circuit['cid']) if nb_termination: return False payload = { 'circuit': nb_circuit['id'], 'interface': nb_interface['id'], 'site': nb_device['site']['id'], 'port_speed': speed, 'term_side': term_side } if xconnect_id: payload['xconnect_id'] = xconnect_id circuit_termination = _add('circuits', 'circuit-terminations', payload) if circuit_termination: return {'circuits': {'circuit-terminations': {circuit_termination['id']: payload}}} else: return circuit_termination
[ "def", "create_circuit_termination", "(", "circuit", ",", "interface", ",", "device", ",", "speed", ",", "xconnect_id", "=", "None", ",", "term_side", "=", "'A'", ")", ":", "nb_device", "=", "get_", "(", "'dcim'", ",", "'devices'", ",", "name", "=", "devic...
.. versionadded:: 2019.2.0 Terminate a circuit on an interface circuit The name of the circuit interface The name of the interface to terminate on device The name of the device the interface belongs to speed The speed of the circuit, in Kbps xconnect_id The cross-connect identifier term_side The side of the circuit termination CLI Example: .. code-block:: bash salt myminion netbox.create_circuit_termination NEW_CIRCUIT_01 xe-0/0/1 myminion 10000 xconnect_id=XCON01
[ "..", "versionadded", "::", "2019", ".", "2", ".", "0" ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/netbox.py#L1116-L1164
train
saltstack/salt
salt/renderers/aws_kms.py
_cfg
def _cfg(key, default=None): ''' Return the requested value from the aws_kms key in salt configuration. If it's not set, return the default. ''' root_cfg = __salt__.get('config.get', __opts__.get) kms_cfg = root_cfg('aws_kms', {}) return kms_cfg.get(key, default)
python
def _cfg(key, default=None): ''' Return the requested value from the aws_kms key in salt configuration. If it's not set, return the default. ''' root_cfg = __salt__.get('config.get', __opts__.get) kms_cfg = root_cfg('aws_kms', {}) return kms_cfg.get(key, default)
[ "def", "_cfg", "(", "key", ",", "default", "=", "None", ")", ":", "root_cfg", "=", "__salt__", ".", "get", "(", "'config.get'", ",", "__opts__", ".", "get", ")", "kms_cfg", "=", "root_cfg", "(", "'aws_kms'", ",", "{", "}", ")", "return", "kms_cfg", "...
Return the requested value from the aws_kms key in salt configuration. If it's not set, return the default.
[ "Return", "the", "requested", "value", "from", "the", "aws_kms", "key", "in", "salt", "configuration", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/aws_kms.py#L102-L110
train
saltstack/salt
salt/renderers/aws_kms.py
_session
def _session(): ''' Return the boto3 session to use for the KMS client. If aws_kms:profile_name is set in the salt configuration, use that profile. Otherwise, fall back on the default aws profile. We use the boto3 profile system to avoid having to duplicate individual boto3 configuration settings in salt configuration. ''' profile_name = _cfg('profile_name') if profile_name: log.info('Using the "%s" aws profile.', profile_name) else: log.info('aws_kms:profile_name is not set in salt. Falling back on default profile.') try: return boto3.Session(profile_name=profile_name) except botocore.exceptions.ProfileNotFound as orig_exc: err_msg = 'Boto3 could not find the "{}" profile configured in Salt.'.format( profile_name or 'default') config_error = salt.exceptions.SaltConfigurationError(err_msg) six.raise_from(config_error, orig_exc) except botocore.exceptions.NoRegionError as orig_exc: err_msg = ('Boto3 was unable to determine the AWS ' 'endpoint region using the {} profile.').format(profile_name or 'default') config_error = salt.exceptions.SaltConfigurationError(err_msg) six.raise_from(config_error, orig_exc)
python
def _session(): ''' Return the boto3 session to use for the KMS client. If aws_kms:profile_name is set in the salt configuration, use that profile. Otherwise, fall back on the default aws profile. We use the boto3 profile system to avoid having to duplicate individual boto3 configuration settings in salt configuration. ''' profile_name = _cfg('profile_name') if profile_name: log.info('Using the "%s" aws profile.', profile_name) else: log.info('aws_kms:profile_name is not set in salt. Falling back on default profile.') try: return boto3.Session(profile_name=profile_name) except botocore.exceptions.ProfileNotFound as orig_exc: err_msg = 'Boto3 could not find the "{}" profile configured in Salt.'.format( profile_name or 'default') config_error = salt.exceptions.SaltConfigurationError(err_msg) six.raise_from(config_error, orig_exc) except botocore.exceptions.NoRegionError as orig_exc: err_msg = ('Boto3 was unable to determine the AWS ' 'endpoint region using the {} profile.').format(profile_name or 'default') config_error = salt.exceptions.SaltConfigurationError(err_msg) six.raise_from(config_error, orig_exc)
[ "def", "_session", "(", ")", ":", "profile_name", "=", "_cfg", "(", "'profile_name'", ")", "if", "profile_name", ":", "log", ".", "info", "(", "'Using the \"%s\" aws profile.'", ",", "profile_name", ")", "else", ":", "log", ".", "info", "(", "'aws_kms:profile_...
Return the boto3 session to use for the KMS client. If aws_kms:profile_name is set in the salt configuration, use that profile. Otherwise, fall back on the default aws profile. We use the boto3 profile system to avoid having to duplicate individual boto3 configuration settings in salt configuration.
[ "Return", "the", "boto3", "session", "to", "use", "for", "the", "KMS", "client", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/aws_kms.py#L125-L151
train
saltstack/salt
salt/renderers/aws_kms.py
_api_decrypt
def _api_decrypt(): ''' Return the response dictionary from the KMS decrypt API call. ''' kms = _kms() data_key = _cfg_data_key() try: return kms.decrypt(CiphertextBlob=data_key) except botocore.exceptions.ClientError as orig_exc: error_code = orig_exc.response.get('Error', {}).get('Code', '') if error_code != 'InvalidCiphertextException': raise err_msg = 'aws_kms:data_key is not a valid KMS data key' config_error = salt.exceptions.SaltConfigurationError(err_msg) six.raise_from(config_error, orig_exc)
python
def _api_decrypt(): ''' Return the response dictionary from the KMS decrypt API call. ''' kms = _kms() data_key = _cfg_data_key() try: return kms.decrypt(CiphertextBlob=data_key) except botocore.exceptions.ClientError as orig_exc: error_code = orig_exc.response.get('Error', {}).get('Code', '') if error_code != 'InvalidCiphertextException': raise err_msg = 'aws_kms:data_key is not a valid KMS data key' config_error = salt.exceptions.SaltConfigurationError(err_msg) six.raise_from(config_error, orig_exc)
[ "def", "_api_decrypt", "(", ")", ":", "kms", "=", "_kms", "(", ")", "data_key", "=", "_cfg_data_key", "(", ")", "try", ":", "return", "kms", ".", "decrypt", "(", "CiphertextBlob", "=", "data_key", ")", "except", "botocore", ".", "exceptions", ".", "Clien...
Return the response dictionary from the KMS decrypt API call.
[ "Return", "the", "response", "dictionary", "from", "the", "KMS", "decrypt", "API", "call", "." ]
e8541fd6e744ab0df786c0f76102e41631f45d46
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/renderers/aws_kms.py#L162-L176
train