def save_config(module, result): result['changed'] = True if not module.check_mode: command = { "command": "copy running-config startup-config", "prompt": "This operation will modify your startup configuration. Do you want to continue", "answer": "y" } run_commands(module, command) else: module.warn('Skipping command `copy running-config startup-config` ' 'due to check_mode. Configuration not copied to ' 'non-volatile storage')
def test_run_commands(self, connection): """ Test get_capabilities """ module = MagicMock() commands = [ 'hello', 'dolly', 'well hello', 'dolly', 'its so nice to have you back', 'where you belong', ] responses = [ 'Dolly, never go away again1', 'Dolly, never go away again2', 'Dolly, never go away again3', 'Dolly, never go away again4', 'Dolly, never go away again5', 'Dolly, never go away again6', ] module.slxos_connection.get.side_effect = responses run_command_responses = slxos.run_commands(module, commands) calls = [] for command in commands: calls.append(call(command, None, None)) module.slxos_connection.get.assert_has_calls(calls) self.assertEqual(responses, run_command_responses)
def get_switchport(name, module): config = run_commands(module, ['show interface {0} switchport'.format(name)])[0] mode = re.search(r'Switchport mode\s+:\s(?:.* )?(\w+)$', config, re.M) if mode: mode = mode.group(1) access = re.search(r'Default Vlan\s+:\s(\d+)', config) if access: access = access.group(1) native = re.search(r'Native Vlan\s+:\s(\d+)', config) if native: native = native.group(1) trunk = re.search(r'Active Vlans\s+:\s(.+)$', config, re.M) if trunk: trunk = trunk.group(1) if trunk == 'ALL': trunk = '1-4094' switchport_config = { "interface": name, "mode": mode, "access_vlan": access, "native_vlan": native, "trunk_vlans": trunk, } return switchport_config
def is_switchport(name, module): intf_type = get_interface_type(name) if intf_type in ('ethernet', 'portchannel'): config = run_commands(module, ['show interface {0} switchport'.format(name)])[0] match = re.search(r'Interface name\s+:\s', config) return bool(match) return False
def main(): """main entry point for module execution """ argument_spec = dict( commands=dict(type='list', required=True), wait_for=dict(type='list'), match=dict(default='all', choices=['all', 'any']), retries=dict(default=10, type='int'), interval=dict(default=1, type='int') ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) result = {'changed': False} warnings = list() commands = parse_commands(module, warnings) result['warnings'] = warnings wait_for = module.params['wait_for'] or list() conditionals = [Conditional(c) for c in wait_for] retries = module.params['retries'] interval = module.params['interval'] match = module.params['match'] while retries > 0: responses = run_commands(module, commands) for item in list(conditionals): if item(responses): if match == 'any': conditionals = list() break conditionals.remove(item) if not conditionals: break time.sleep(interval) retries -= 1 if conditionals: failed_conditions = [item.raw for item in conditionals] msg = 'One or more conditional statements have not been satisfied' module.fail_json(msg=msg, failed_conditions=failed_conditions) result.update({ 'changed': False, 'stdout': responses, 'stdout_lines': list(to_lines(responses)) }) module.exit_json(**result)
def get_list_of_vlans(module): config = run_commands(module, ['show vlan brief'])[0] vlans = set() lines = config.strip().splitlines() for line in lines: line_parts = line.split() if line_parts: try: int(line_parts[0]) except ValueError: continue vlans.add(line_parts[0]) return list(vlans)
def map_config_to_obj(module): output = run_commands(module, ['show vlan brief']) lines = output[0].strip().splitlines()[5:] if not lines: return list() objs = list() obj = {} for l in lines: splitted_line = re.split( r'([0-9]+)? +(\S.{14})? +(ACTIVE|INACTIVE\(.+?\))?.*(Eth .+?|Po .+?|Tu .+?)\([ut]\).*$', l.rstrip()) if len(splitted_line) == 1: # Handle situation where VLAN is configured, but has no associated ports inactive = re.match( r'([0-9]+)? +(\S.{14}) +INACTIVE\(no member port\).*$', l.rstrip()) if inactive: splitted_line = [ '', inactive.groups()[0], inactive.groups()[1], '', '' ] else: continue splitted_line[4] = splitted_line[4].replace('Eth', 'Ethernet').replace( 'Po', 'Port-channel').replace('Tu', 'Tunnel') if splitted_line[1] is None: obj['interfaces'].append(splitted_line[4]) continue obj = {} obj['vlan_id'] = splitted_line[1] obj['name'] = splitted_line[2].strip() obj['interfaces'] = [splitted_line[4]] objs.append(obj) return objs
def main(): """ main entry point for module execution """ backup_spec = dict(filename=dict(), dir_path=dict(type='path')) argument_spec = dict( src=dict(type='path'), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block']), multiline_delimiter=dict(default='@'), running_config=dict(aliases=['config']), intended_config=dict(), defaults=dict(type='bool', default=False), backup=dict(type='bool', default=False), backup_options=dict(type='dict', options=backup_spec), save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never'), diff_against=dict(choices=['startup', 'intended', 'running']), diff_ignore_lines=dict(type='list'), ) mutually_exclusive = [('lines', 'src'), ('parents', 'src')] required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines']), ('diff_against', 'intended', ['intended_config'])] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True) result = {'changed': False} warnings = list() check_args(module, warnings) result['warnings'] = warnings config = None if module.params['backup'] or (module._diff and module.params['diff_against'] == 'running'): contents = get_config(module) config = NetworkConfig(indent=1, contents=contents) if module.params['backup']: result['__backup__'] = contents if any((module.params['lines'], module.params['src'])): match = module.params['match'] replace = module.params['replace'] path = module.params['parents'] candidate = get_candidate(module) if match != 'none': config = get_running_config(module, config) path = module.params['parents'] configobjs = candidate.difference(config, path=path, match=match, replace=replace) else: configobjs = candidate.items if configobjs: commands = dumps(configobjs, 'commands').split('\n') if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) result['commands'] = commands result['updates'] = commands # send the configuration commands to the device and merge # them with the current running config if not module.check_mode: if commands: load_config(module, commands) result['changed'] = True running_config = None startup_config = None diff_ignore_lines = module.params['diff_ignore_lines'] if module.params['save_when'] == 'always': save_config(module, result) elif module.params['save_when'] == 'modified': output = run_commands(module, ['show running-config', 'show startup-config']) running_config = NetworkConfig(indent=1, contents=output[0], ignore_lines=diff_ignore_lines) startup_config = NetworkConfig(indent=1, contents=output[1], ignore_lines=diff_ignore_lines) if running_config.sha1 != startup_config.sha1: save_config(module, result) elif module.params['save_when'] == 'changed' and result['changed']: save_config(module, result) if module._diff: if not running_config: output = run_commands(module, 'show running-config') contents = output[0] else: contents = running_config.config_text # recreate the object in order to process diff_ignore_lines running_config = NetworkConfig(indent=1, contents=contents, ignore_lines=diff_ignore_lines) if module.params['diff_against'] == 'running': if module.check_mode: module.warn( "unable to perform diff against running-config due to check mode" ) contents = None else: contents = config.config_text elif module.params['diff_against'] == 'startup': if not startup_config: output = run_commands(module, 'show startup-config') contents = output[0] else: contents = startup_config.config_text elif module.params['diff_against'] == 'intended': contents = module.params['intended_config'] if contents is not None: base_config = NetworkConfig(indent=1, contents=contents, ignore_lines=diff_ignore_lines) if running_config.sha1 != base_config.sha1: if module.params['diff_against'] == 'intended': before = running_config after = base_config elif module.params['diff_against'] in ('startup', 'running'): before = base_config after = running_config result.update({ 'changed': True, 'diff': { 'before': str(before), 'after': str(after) } }) module.exit_json(**result)
def run(self, cmd): return run_commands(self.module, cmd)
def populate(self): self.responses = run_commands(self.module, self.COMMANDS)