def run(module, result): match = module.params['match'] replace = module.params['replace'] replace_config = replace == 'config' path = module.params['parents'] comment = module.params['comment'] admin = module.params['admin'] check_mode = module.check_mode candidate_config = get_candidate(module) running_config = get_running_config(module) sanitize_candidate_config(candidate_config.items) sanitize_running_config(running_config.items) commands = None if match != 'none' and replace != 'config': commands = candidate_config.difference(running_config, path=path, match=match, replace=replace) elif replace_config: can_config = candidate_config.difference(running_config, path=path, match=match, replace=replace) candidate = dumps(can_config, 'commands').split('\n') run_config = running_config.difference(candidate_config, path=path, match=match, replace=replace) running = dumps(run_config, 'commands').split('\n') if len(candidate) > 1 or len(running) > 1: ret = copy_file_to_node(module) if not ret: module.fail_json(msg='Copy of config file to the node failed') commands = ['load harddisk:/ansible_config.txt'] else: commands = candidate_config.items if commands: if not replace_config: commands = dumps(commands, 'commands').split('\n') if any((module.params['lines'], module.params['src'])): if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) result['commands'] = commands commit = not check_mode diff = load_config(module, commands, commit=commit, replace=replace_config, comment=comment, admin=admin) if diff: result['diff'] = dict(prepared=diff) result['changed'] = True
def run(module, result): match = module.params['match'] replace = module.params['replace'] candidate = get_candidate(module) if match != 'none': config = get_running_config(module) path = module.params['parents'] configobjs = candidate.difference(config, match=match, replace=replace, path=path) else: configobjs = candidate.items if configobjs: commands = dumps(configobjs, 'commands').split('\n') if module.params['lines']: if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) result['commands'] = commands result['updates'] = commands if not module.check_mode: load_config(module, commands) result['changed'] = True
def main(): argument_spec = dict( lines=dict(aliases=['commands'], required=True, type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact']), replace=dict(default='line', choices=['line', 'block']), force=dict(default=False, type='bool'), config=dict() ) argument_spec.update(asa_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) lines = module.params['lines'] result = {'changed': False} candidate = NetworkConfig(indent=1) candidate.add(lines) acl_name = parse_acl_name(module) if not module.params['force']: contents = get_acl_config(module, acl_name) config = NetworkConfig(indent=1, contents=contents) commands = candidate.difference(config) commands = dumps(commands, 'commands').split('\n') commands = [str(c) for c in commands if c] else: commands = str(candidate).split('\n') if commands: if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) if not module.check_mode: load_config(module, commands) result['changed'] = True result['updates'] = commands module.exit_json(**result)
def get_candidate_config(module): candidate = '' if module.params['src']: candidate = module.params['src'] elif module.params['lines']: candidate_obj = NetworkConfig(indent=1) parents = module.params['parents'] or list() candidate_obj.add(module.params['lines'], parents=parents) candidate = dumps(candidate_obj, 'raw') return candidate
def get_candidate(module): candidate = '' if module.params['src']: if module.params['replace'] != 'config': candidate = module.params['src'] if module.params['replace'] == 'config': candidate = 'config replace {0}'.format(module.params['replace_src']) elif module.params['lines']: candidate_obj = NetworkConfig(indent=2) parents = module.params['parents'] or list() candidate_obj.add(module.params['lines'], parents=parents) candidate = dumps(candidate_obj, 'raw') return candidate
def get_candidate(module): candidate = "" if module.params["src"]: if module.params["replace"] != "config": candidate = module.params["src"] if module.params["replace"] == "config": candidate = "config replace {0}".format(module.params["replace_src"]) elif module.params["lines"]: candidate_obj = NetworkConfig(indent=2) parents = module.params["parents"] or list() candidate_obj.add(module.params["lines"], parents=parents) candidate = dumps(candidate_obj, "raw") return candidate
def get_diff(self, candidate=None, running=None, diff_match='line', diff_ignore_lines=None, path=None, diff_replace='line'): diff = {} device_operations = self.get_device_operations() option_values = self.get_option_values() if candidate is None and device_operations['supports_generate_diff']: raise ValueError( "candidate configuration is required to generate diff") if diff_match not in option_values['diff_match']: raise ValueError( "'match' value %s in invalid, valid values are %s" % (diff_match, ', '.join(option_values['diff_match']))) if diff_replace not in option_values['diff_replace']: raise ValueError( "'replace' value %s in invalid, valid values are %s" % (diff_replace, ', '.join(option_values['diff_replace']))) # prepare candidate configuration sanitized_candidate = sanitize_config(candidate) candidate_obj = NetworkConfig(indent=1) candidate_obj.load(sanitized_candidate) if running and diff_match != 'none': # running configuration running = mask_config_blocks_from_diff(running, candidate, "ansible") running = sanitize_config(running) running_obj = NetworkConfig(indent=1, contents=running, ignore_lines=diff_ignore_lines) configdiffobjs = candidate_obj.difference(running_obj, path=path, match=diff_match, replace=diff_replace) else: configdiffobjs = candidate_obj.items diff['config_diff'] = dumps(configdiffobjs, 'commands') if configdiffobjs else '' return diff
def get_diff(self, candidate=None, running=None, diff_match='line', diff_ignore_lines=None, path=None, diff_replace='line'): diff = {} # prepare candidate configuration candidate_obj = NetworkConfig(indent=1) candidate_obj.load(candidate) if running and diff_match != 'none' and diff_replace != 'config': # running configuration running_obj = NetworkConfig(indent=1, contents=running, ignore_lines=diff_ignore_lines) configdiffobjs = candidate_obj.difference(running_obj, path=path, match=diff_match, replace=diff_replace) else: configdiffobjs = candidate_obj.items diff['config_diff'] = dumps(configdiffobjs, 'commands') if configdiffobjs else '' return diff
def get_candidate(self): candidate = '' if self.want.src: candidate = self.want.src elif self.want.lines: candidate_obj = ImishConfig(indent=1) parents = self.want.parents or list() if self.want.allow_duplicates: candidate_obj.add(self.want.lines, parents=parents, duplicates=True) else: candidate_obj.add(self.want.lines, parents=parents) candidate = dumps(candidate_obj, 'raw') return candidate
def run(module, result): match = module.params['match'] replace = module.params['replace'] path = module.params['parents'] candidate, want_banners = get_candidate(module) if match != 'none': config, have_banners = get_config(module, result) path = module.params['parents'] configobjs = candidate.difference(config, path=path, match=match, replace=replace) else: configobjs = candidate.items have_banners = {} banners = diff_banners(want_banners, have_banners) if configobjs or banners: commands = dumps(configobjs, 'commands').split('\n') if module.params['lines']: if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) result['updates'] = commands result['banners'] = banners # send the configuration commands to the device and merge # them with the current running config if not module.check_mode: if commands: module.config(commands) if banners: load_banners(module, banners) result['changed'] = True if module.params['save']: if not module.check_mode: module.config.save_config() result['changed'] = True
def main(): """ main entry point for module execution """ argument_spec = dict( rollback_location=dict(), local_max_checkpoints=dict(type='int'), remote_max_checkpoints=dict(type='int'), rescue_location=dict(), state=dict(default='present', choices=['present', 'absent']) ) argument_spec.update(sros_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) state = module.params['state'] result = dict(changed=False) commands = list() invoke(state, module, commands) candidate = NetworkConfig(indent=4, contents='\n'.join(commands)) config = get_device_config(module) configobjs = candidate.difference(config) if configobjs: # commands = dumps(configobjs, 'lines') commands = dumps(configobjs, 'commands') commands = sanitize_config(commands.split('\n')) result['updates'] = commands result['commands'] = commands # send the configuration commands to the device and merge # them with the current running config if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result)
def get_diff(self, candidate=None, running=None, match='line', diff_ignore_lines=None, path=None, replace='line'): diff = {} device_operations = self.get_device_operations() option_values = self.get_option_values() if candidate is None and device_operations['supports_generate_diff']: raise ValueError( "candidate configuration is required to generate diff") if match not in option_values['diff_match']: raise ValueError( "'match' value %s in invalid, valid values are %s" % (match, ', '.join(option_values['diff_match']))) if replace not in option_values['diff_replace']: raise ValueError( "'replace' value %s in invalid, valid values are %s" % (replace, ', '.join(option_values['diff_replace']))) # prepare candidate configuration candidate_obj = NetworkConfig(indent=3) candidate_obj.load(candidate) if running and match != 'none' and replace != 'config': # running configuration running_obj = NetworkConfig(indent=3, contents=running, ignore_lines=diff_ignore_lines) configdiffobjs = candidate_obj.difference(running_obj, path=path, match=match, replace=replace) else: configdiffobjs = candidate_obj.items configdiff = dumps(configdiffobjs, 'commands') if configdiffobjs else '' diff['config_diff'] = configdiff if configdiffobjs else {} return diff
def run(module, result): match = module.params['match'] replace = module.params['replace'] replace_config = replace == 'config' path = module.params['parents'] comment = module.params['comment'] admin = module.params['admin'] check_mode = module.check_mode candidate = get_candidate(module) if match != 'none' and replace != 'config': contents = get_running_config(module) configobj = NetworkConfig(contents=contents, indent=1) commands = candidate.difference(configobj, path=path, match=match, replace=replace) else: commands = candidate.items if commands: commands = dumps(commands, 'commands').split('\n') if any((module.params['lines'], module.params['src'])): if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) result['commands'] = commands commit = not check_mode diff = load_config(module, commands, commit=commit, replace=replace_config, comment=comment, admin=admin) if diff: result['diff'] = dict(prepared=diff) result['changed'] = True
def main(): """ main entry point for module execution """ argument_spec = dict(rollback_location=dict(), local_max_checkpoints=dict(type='int'), remote_max_checkpoints=dict(type='int'), rescue_location=dict(), state=dict(default='present', choices=['present', 'absent'])) argument_spec.update(sros_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) state = module.params['state'] result = dict(changed=False) commands = list() invoke(state, module, commands) candidate = NetworkConfig(indent=4, contents='\n'.join(commands)) config = get_device_config(module) configobjs = candidate.difference(config) if configobjs: # commands = dumps(configobjs, 'lines') commands = dumps(configobjs, 'commands') commands = sanitize_config(commands.split('\n')) result['updates'] = commands result['commands'] = commands # send the configuration commands to the device and merge # them with the current running config if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result)
def run(module, result): match = module.params['match'] replace = module.params['replace'] path = module.params['parents'] configobjs = None candidate = get_candidate(module) if match != 'none': contents = module.params['config'] if not contents: contents = get_config(module) config = NetworkConfig(indent=1, contents=contents) 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['lines']: if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) result['updates'] = commands # send the configuration commands to the device and merge # them with the current running config if not module.check_mode: load_config(module, commands) result['changed'] = True if result['changed'] or module.params['save_when'] == 'always': result['changed'] = True if not module.check_mode: cmd = {'command': 'write memory'} run_commands(module, [cmd])
def run(module, result): match = module.params['match'] replace = module.params['replace'] candidate = get_candidate(module) if match != 'none': config = get_running_config(module) path = module.params['parents'] configobjs = candidate.difference(config, match=match, replace=replace, path=path) else: configobjs = candidate.items if configobjs: commands = dumps(configobjs, 'commands').split('\n') if module.params['lines']: if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) command_display = [] for per_command in commands: if per_command.strip() not in ['quit', 'return', 'system-view']: command_display.append(per_command) result['commands'] = command_display result['updates'] = command_display if not module.check_mode: if module.params['parents'] is not None: load_config(module, commands) else: _load_config(module, commands) result['changed'] = True
def run(module, result): match = module.params['match'] replace = module.params['replace'] path = module.params['parents'] candidate = get_candidate(module) if match != 'none': contents = module.params['config'] if not contents: contents = get_config(module) config = NetworkConfig(indent=1, contents=contents) configobjs = candidate.difference(config, path=path, match=match, replace=replace) else: configobjs = candidate.items total_commands = [] if configobjs: commands = dumps(configobjs, 'commands').split('\n') if module.params['lines']: if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) total_commands.extend(commands) result['updates'] = total_commands if module.params['save']: total_commands.append('configuration write') if total_commands: result['changed'] = True if not module.check_mode: load_config(module, total_commands)
def run(module, result): match = module.params['match'] candidate = get_candidate(module) if match != 'none': config_text = get_active_config(module) config = NetworkConfig(indent=4, contents=config_text) configobjs = candidate.difference(config) else: configobjs = candidate.items if configobjs: commands = dumps(configobjs, 'commands') commands = commands.split('\n') 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: load_config(module, commands) result['changed'] = True
def run(self, terms, variables, **kwargs): ret = [] try: want = terms[0] except IndexError: raise AnsibleError("value of 'want' must be specified") try: have = kwargs['have'] except KeyError: raise AnsibleError("value of 'have' must be specified") match = kwargs.get('match', 'line') if match not in MATCH_CHOICES: choices_str = ", ".join(MATCH_CHOICES) raise AnsibleError("value of match must be one of: %s, got: %s" % (choices_str, match)) replace = kwargs.get('replace', 'line') if replace not in REPLACE_CHOICES: choices_str = ", ".join(REPLACE_CHOICES) raise AnsibleError("value of replace must be one of: %s, got: %s" % (choices_str, replace)) indent = int(kwargs.get('indent', 1)) ignore_lines = kwargs.get('ignore_lines') running_obj = NetworkConfig(indent=indent, contents=have, ignore_lines=ignore_lines) candidate_obj = NetworkConfig(indent=indent, contents=want, ignore_lines=ignore_lines) configobjs = candidate_obj.difference(running_obj, match=match, replace=replace) diff = dumps(configobjs, output='commands') ret.append(diff) return ret
def get_diff(self, candidate=None, running=None, diff_match='line', diff_ignore_lines=None, path=None, diff_replace='line'): """ Generate diff between candidate and running configuration. If the remote host supports onbox diff capabilities ie. supports_onbox_diff in that case candidate and running configurations are not required to be passed as argument. In case if onbox diff capability is not supported candidate argument is mandatory and running argument is optional. :param candidate: The configuration which is expected to be present on remote host. :param running: The base configuration which is used to generate diff. :param diff_match: Instructs how to match the candidate configuration with current device configuration Valid values are 'line', 'strict', 'exact', 'none'. 'line' - commands are matched line by line 'strict' - command lines are matched with respect to position 'exact' - command lines must be an equal match 'none' - will not compare the candidate configuration with the running configuration :param diff_ignore_lines: Use this argument to specify one or more lines that should be ignored during the diff. This is used for lines in the configuration that are automatically updated by the system. This argument takes a list of regular expressions or exact line matches. :param path: The ordered set of parents that uniquely identify the section or hierarchy the commands should be checked against. If the parents argument is omitted, the commands are checked against the set of top level or global commands. :param diff_replace: Instructs on the way to perform the configuration on the device. If the replace argument is set to I(line) then the modified lines are pushed to the device in configuration mode. If the replace argument is set to I(block) then the entire command block is pushed to the device in configuration mode if any line is not correct. :return: Configuration diff in json format. { 'config_diff': '', 'banner_diff': {} } """ diff = {} device_operations = self.get_device_operations() option_values = self.get_option_values() if candidate is None and device_operations['supports_generate_diff']: raise ValueError( "candidate configuration is required to generate diff") if diff_match not in option_values['diff_match']: raise ValueError( "'match' value %s in invalid, valid values are %s" % (diff_match, ', '.join(option_values['diff_match']))) if diff_replace not in option_values['diff_replace']: raise ValueError( "'replace' value %s in invalid, valid values are %s" % (diff_replace, ', '.join(option_values['diff_replace']))) # prepare candidate configuration candidate_obj = NetworkConfig(indent=1) want_src, want_banners = self._extract_banners(candidate) candidate_obj.load(want_src) if running and diff_match != 'none': # running configuration have_src, have_banners = self._extract_banners(running) running_obj = NetworkConfig(indent=1, contents=have_src, ignore_lines=diff_ignore_lines) configdiffobjs = candidate_obj.difference(running_obj, path=path, match=diff_match, replace=diff_replace) else: configdiffobjs = candidate_obj.items have_banners = {} diff['config_diff'] = dumps(configdiffobjs, 'commands') if configdiffobjs else '' banners = self._diff_banners(want_banners, have_banners) diff['banner_diff'] = banners if banners else {} return diff
def main(): """ main entry point for module execution """ argument_spec = dict( src=dict(type='path'), lines=dict(aliases=['commands'], type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'none']), running_config=dict(aliases=['config']), intended_config=dict(), backup=dict(type='bool', default=False), # save is deprecated as of 2.7, use save_when instead save=dict(type='bool', default=False, removed_in_version='2.11'), save_when=dict(choices=['always', 'never', 'changed'], default='never'), diff_against=dict(choices=['running', 'intended']), diff_ignore_lines=dict(type='list') ) argument_spec.update(aireos_argument_spec) mutually_exclusive = [('lines', 'src'), ('save', 'save_when')] required_if = [('diff_against', 'intended', ['intended_config'])] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True) warnings = list() aireos_check_args(module, warnings) result = {'changed': False, '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['src'], module.params['lines'])): match = module.params['match'] candidate = get_candidate(module) if match != 'none': config = get_running_config(module, config) configobjs = candidate.difference(config, match=match) 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 if not module.check_mode: load_config(module, commands) result['changed'] = True diff_ignore_lines = module.params['diff_ignore_lines'] if module.params['save_when'] == 'always' or module.params['save']: save_config(module, result) elif module.params['save_when'] == 'changed' and result['changed']: save_config(module, result) if module._diff: output = run_commands(module, 'show run-config commands') contents = output[0] # 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'] == '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: result.update({ 'changed': True, 'diff': {'before': str(base_config), 'after': str(running_config)} }) module.exit_json(**result)
def main(): """ main entry point for module execution """ 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', 'config']), defaults=dict(type='bool', default=False), backup=dict(type='bool', default=False), save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never'), diff_against=dict(choices=['startup', 'session', 'intended', 'running'], default='session'), diff_ignore_lines=dict(type='list'), running_config=dict(aliases=['config']), intended_config=dict(), # save is deprecated as of ans2.4, use save_when instead save=dict(default=False, type='bool', removed_in_version='2.8'), # force argument deprecated in ans2.2 force=dict(default=False, type='bool', removed_in_version='2.6') ) argument_spec.update(eos_argument_spec) mutually_exclusive = [('lines', 'src'), ('parents', 'src'), ('save', 'save_when')] required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines']), ('replace', 'config', ['src']), ('diff_against', 'intended', ['intended_config'])] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True) warnings = list() check_args(module, warnings) result = {'changed': False} if 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=3, contents=contents) if module.params['backup']: result['__backup__'] = contents if any((module.params['src'], module.params['lines'])): match = module.params['match'] replace = module.params['replace'] candidate = get_candidate(module) if match != 'none' and replace != 'config': config_text = get_running_config(module) config = NetworkConfig(indent=3, contents=config_text) path = module.params['parents'] configobjs = candidate.difference(config, match=match, replace=replace, path=path) 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 replace = module.params['replace'] == 'config' commit = not module.check_mode response = load_config(module, commands, replace=replace, commit=commit) if 'diff' in response and module.params['diff_against'] == 'session': result['diff'] = {'prepared': response['diff']} if 'session' in response: result['session'] = response['session'] result['changed'] = True running_config = None startup_config = None diff_ignore_lines = module.params['diff_ignore_lines'] if module.params['save_when'] == 'always' or module.params['save']: save_config(module, result) elif module.params['save_when'] == 'modified': output = run_commands(module, [{'command': 'show running-config', 'output': 'text'}, {'command': 'show startup-config', 'output': 'text'}]) 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, {'command': 'show running-config', 'output': 'text'}) 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, {'command': 'show startup-config', 'output': 'text'}) 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 main(): """ main entry point for module execution """ 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), 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 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']), 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} parents = module.params['parents'] or list() match = module.params['match'] replace = module.params['replace'] warnings = list() result['warnings'] = warnings diff_ignore_lines = module.params['diff_ignore_lines'] config = None contents = None flags = get_defaults_flag(module) if module.params['defaults'] else [] connection = get_connection(module) if module.params['backup'] or (module._diff and module.params['diff_against'] == 'running'): contents = get_config(module, flags=flags) config = VossNetworkConfig(indent=0, contents=contents) if module.params['backup']: result['__backup__'] = contents if any((module.params['lines'], module.params['src'])): candidate = get_candidate_config(module) if match != 'none': config = get_running_config(module) config = VossNetworkConfig(contents=config, indent=0) if parents: config = get_sublevel_config(config, module) configobjs = candidate.difference(config, match=match, replace=replace) else: configobjs = candidate.items if configobjs: commands = dumps(configobjs, 'commands') commands = 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: try: connection.edit_config(candidate=commands) except ConnectionError as exc: module.fail_json(msg=to_text( commands, errors='surrogate_then_replace')) result['changed'] = True running_config = module.params['running_config'] startup = None if module.params['save_when'] == 'always': save_config(module, result) elif module.params['save_when'] == 'modified': match = module.params['match'] replace = module.params['replace'] try: # Note we need to re-retrieve running config, not use cached version running = connection.get_config(source='running') startup = connection.get_config(source='startup') response = connection.get_diff(candidate=startup, running=running, diff_match=match, diff_ignore_lines=diff_ignore_lines, path=None, diff_replace=replace) except ConnectionError as exc: module.fail_json(msg=to_text(exc, errors='surrogate_then_replace')) config_diff = response['config_diff'] if config_diff: save_config(module, result) elif module.params['save_when'] == 'changed' and result['changed']: save_config(module, result) if module._diff: if not running_config: try: # Note we need to re-retrieve running config, not use cached version contents = connection.get_config(source='running') except ConnectionError as exc: module.fail_json( msg=to_text(exc, errors='surrogate_then_replace')) else: contents = running_config # recreate the object in order to process diff_ignore_lines running_config = VossNetworkConfig(indent=0, 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: try: contents = connection.get_config(source='startup') except ConnectionError as exc: module.fail_json( msg=to_text(exc, errors='surrogate_then_replace')) else: contents = startup elif module.params['diff_against'] == 'intended': contents = module.params['intended_config'] if contents is not None: base_config = VossNetworkConfig(indent=0, 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 main(): """ main entry point for module execution """ argument_spec = dict( src=dict(type='path'), lines=dict(aliases=['commands'], type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'none']), running_config=dict(aliases=['config']), intended_config=dict(), backup=dict(type='bool', default=False), save=dict(type='bool', default=False), diff_against=dict(choices=['running', 'intended']), diff_ignore_lines=dict(type='list') ) argument_spec.update(aireos_argument_spec) mutually_exclusive = [('lines', 'src')] required_if = [('diff_against', 'intended', ['intended_config'])] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True) warnings = list() aireos_check_args(module, warnings) result = {'changed': False, '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['src'], module.params['lines'])): match = module.params['match'] candidate = get_candidate(module) if match != 'none': config = get_running_config(module, config) configobjs = candidate.difference(config, match=match) 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 if not module.check_mode: load_config(module, commands) result['changed'] = True diff_ignore_lines = module.params['diff_ignore_lines'] if module.params['save']: result['changed'] = True if not module.check_mode: command = {"command": "save config", "prompt": "Are you sure you want to save", "answer": "y"} run_commands(module, command) else: module.warn('Skipping command `save config` due to check_mode. Configuration not copied to non-volatile storage') if module._diff: output = run_commands(module, 'show run-config commands') contents = output[0] # 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'] == '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: result.update({ 'changed': True, 'diff': {'before': str(base_config), 'after': str(running_config)} }) module.exit_json(**result)
def main(): """ main entry point for module execution """ 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', 'config']), defaults=dict(type='bool', default=False), backup=dict(type='bool', default=False), save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never'), diff_against=dict( choices=['startup', 'session', 'intended', 'running'], default='session'), diff_ignore_lines=dict(type='list'), running_config=dict(aliases=['config']), intended_config=dict(), # save is deprecated as of ans2.4, use save_when instead save=dict(default=False, type='bool', removed_in_version='2.8'), # force argument deprecated in ans2.2 force=dict(default=False, type='bool', removed_in_version='2.6')) argument_spec.update(eos_argument_spec) mutually_exclusive = [('lines', 'src'), ('parents', 'src'), ('save', 'save_when')] required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines']), ('replace', 'config', ['src']), ('diff_against', 'intended', ['intended_config'])] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True) warnings = list() check_args(module, warnings) result = {'changed': False} if 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=3, contents=contents) if module.params['backup']: result['__backup__'] = contents if any((module.params['src'], module.params['lines'])): match = module.params['match'] replace = module.params['replace'] candidate = get_candidate(module) if match != 'none' and replace != 'config': config_text = get_running_config(module) config = NetworkConfig(indent=3, contents=config_text) path = module.params['parents'] configobjs = candidate.difference(config, match=match, replace=replace, path=path) 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 replace = module.params['replace'] == 'config' commit = not module.check_mode response = load_config(module, commands, replace=replace, commit=commit) if 'diff' in response and module.params[ 'diff_against'] == 'session': result['diff'] = {'prepared': response['diff']} if 'session' in response: result['session'] = response['session'] result['changed'] = True running_config = None startup_config = None diff_ignore_lines = module.params['diff_ignore_lines'] if module.params['save_when'] == 'always' or module.params['save']: save_config(module, result) elif module.params['save_when'] == 'modified': output = run_commands(module, [{ 'command': 'show running-config', 'output': 'text' }, { 'command': 'show startup-config', 'output': 'text' }]) 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, { 'command': 'show running-config', 'output': 'text' }) 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, { 'command': 'show startup-config', 'output': 'text' }) 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 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']), running_config=dict(aliases=['config']), intended_config=dict(), 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=['running', 'startup', 'intended']), diff_ignore_lines=dict(type='list'), ) argument_spec.update(aoscx_argument_spec) 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) warnings = list() aoscx_check_args(module, warnings) result = {'changed': False, 'warnings': warnings} config = None if module.params['diff_against'] is not None: module._diff = True if module.params['backup'] or (module._diff and module.params['diff_against'] == 'running'): contents = get_config(module) config = NetworkConfig(contents=contents) if module.params['backup']: result['__backup__'] = contents result['backup_options'] = module.params['backup_options'] if module.params['backup_options']: if 'dir_path' in module.params['backup_options']: dir_path = module.params['backup_options']['dir_path'] else: dir_path = "" if 'filename' in module.params['backup_options']: filename = module.params['backup_options']['filename'] else: filename = "backup.cfg" with open(dir_path + '/' + filename, 'w') as backupfile: backupfile.write(contents) backupfile.write("\n") if any((module.params['src'], module.params['lines'])): match = module.params['match'] replace = module.params['replace'] candidate = get_candidate(module) if match != 'none': config = get_running_config(module, config) path = module.params['parents'] configobjs = candidate.difference(config, match=match, replace=replace, path=path) 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 if not module.check_mode: load_config(module, commands) result['changed'] = True running_config = None startup_config = None diff_ignore_lines = module.params['diff_ignore_lines'] if diff_ignore_lines is None: diff_ignore_lines = [] diff_ignore_lines.append("Current configuration:") diff_ignore_lines.append("Startup configuration:") 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(contents=output[0], ignore_lines=diff_ignore_lines) startup_config = NetworkConfig(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': if 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(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': with open(module.params['intended_config'], 'r') as intended_file: contents = intended_file.read() if contents is not None: base_config = NetworkConfig(contents=contents, ignore_lines=diff_ignore_lines) if running_config.sha1 != base_config.sha1: result.update({ 'changed': True, 'diff': { 'before': str(base_config), 'after': str(running_config) } }) module.exit_json(**result)
def main(): argument_spec = dict(lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), src=dict(type='path'), before=dict(type='list'), after=dict(type='list'), match=dict( default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block']), update=dict(choices=['merge', 'check'], default='merge'), save=dict(type='bool', default=False), config=dict(), backup=dict(type='bool', default=False)) argument_spec.update(dellos10_argument_spec) mutually_exclusive = [('lines', 'src'), ('parents', 'src')] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True) parents = module.params['parents'] or list() match = module.params['match'] replace = module.params['replace'] warnings = list() check_args(module, warnings) result = dict(changed=False, saved=False, warnings=warnings) candidate = get_candidate(module) if match != 'none': config = get_config(module) if parents: contents = get_sublevel_config(config, module) config = NetworkConfig(contents=contents, indent=1) else: config = NetworkConfig(contents=config, indent=1) configobjs = candidate.difference(config, match=match, replace=replace) else: configobjs = candidate.items if module.params['backup']: if not module.check_mode: result['__backup__'] = get_config(module) commands = list() if configobjs: commands = dumps(configobjs, 'commands') commands = commands.split('\n') if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) if not module.check_mode and module.params['update'] == 'merge': load_config(module, commands) if module.params['save']: cmd = { 'command': 'copy runing-config startup-config', 'prompt': WARNING_PROMPTS_RE, 'answer': 'yes' } run_commands(module, [cmd]) result['saved'] = True result['changed'] = True result['updates'] = commands module.exit_json(**result)
def run(module, result): match = module.params['match'] replace = module.params['replace'] candidate = get_candidate(module) if match != 'none': before = get_running_config(module) path = module.params['parents'] configobjs = candidate.difference(before, match=match, replace=replace, path=path) else: configobjs = candidate.items if configobjs: out_type = "commands" if module.params["src"] is not None: out_type = "raw" commands = dumps(configobjs, out_type).split('\n') if module.params['lines']: if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) command_display = [] for per_command in commands: if per_command.strip() not in ['quit', 'return', 'system-view']: command_display.append(per_command) result['commands'] = command_display result['updates'] = command_display if not module.check_mode: if module.params['parents'] is not None: load_config(module, commands) else: _load_config(module, commands) if match != "none": after = get_running_config(module) path = module.params["parents"] if path is not None and match != 'line': before_objs = before.get_block(path) after_objs = after.get_block(path) update = [] if len(before_objs) == len(after_objs): for b_item, a_item in zip(before_objs, after_objs): if b_item != a_item: update.append(a_item.text) else: update = [item.text for item in after_objs] if len(update) == 0: result["changed"] = False result['updates'] = [] else: result["changed"] = True result['updates'] = update else: configobjs = after.difference(before, match=match, replace=replace, path=path) if len(configobjs) > 0: result["changed"] = True else: result["changed"] = False result['updates'] = [] else: result['changed'] = True
def main(): argument_spec = dict( lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), src=dict(type='path'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block']), update=dict(choices=['merge', 'check'], default='merge'), save=dict(type='bool', default=False), config=dict(), backup=dict(type='bool', default=False) ) argument_spec.update(dellos6_argument_spec) mutually_exclusive = [('lines', 'src'), ('parents', 'src')] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True) parents = module.params['parents'] or list() match = module.params['match'] replace = module.params['replace'] warnings = list() check_args(module, warnings) result = dict(changed=False, saved=False, warnings=warnings) candidate = get_candidate(module) if module.params['backup']: if not module.check_mode: result['__backup__'] = get_config(module) commands = list() if any((module.params['lines'], module.params['src'])): if match != 'none': config = get_running_config(module) config = Dellos6NetworkConfig(contents=config, indent=0) if parents: config = get_sublevel_config(config, module) configobjs = candidate.difference(config, match=match, replace=replace) else: configobjs = candidate.items if configobjs: commands = dumps(configobjs, 'commands') if ((isinstance(module.params['lines'], list)) and (isinstance(module.params['lines'][0], dict)) and set(['prompt', 'answer']).issubset(module.params['lines'][0])): cmd = {'command': commands, 'prompt': module.params['lines'][0]['prompt'], 'answer': module.params['lines'][0]['answer']} commands = [module.jsonify(cmd)] else: commands = commands.split('\n') if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) if not module.check_mode and module.params['update'] == 'merge': load_config(module, commands) result['changed'] = True result['commands'] = commands result['updates'] = commands if module.params['save']: result['changed'] = True if not module.check_mode: cmd = {'command': 'copy running-config startup-config', 'prompt': r'\(y/n\)\s?$', 'answer': 'yes'} run_commands(module, [cmd]) result['saved'] = True else: module.warn('Skipping command `copy running-config startup-config`' 'due to check_mode. Configuration not copied to ' 'non-volatile storage') module.exit_json(**result)
def main(): """ main entry point for module execution """ argument_spec = dict( src=dict(type='path'), replace_src=dict(), 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', 'config']), running_config=dict(aliases=['config']), intended_config=dict(), defaults=dict(type='bool', default=False), backup=dict(type='bool', default=False), save_when=dict(choices=['always', 'never', 'modified', 'changed'], default='never'), diff_against=dict(choices=['running', 'startup', 'intended']), diff_ignore_lines=dict(type='list'), # save is deprecated as of ans2.4, use save_when instead save=dict(default=False, type='bool', removed_in_version='2.8'), # force argument deprecated in ans2.2 force=dict(default=False, type='bool', removed_in_version='2.6')) argument_spec.update(nxos_argument_spec) mutually_exclusive = [('lines', 'src', 'replace_src'), ('parents', 'src'), ('save', 'save_when')] required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines']), ('replace', 'config', ['replace_src']), ('diff_against', 'intended', ['intended_config'])] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True) warnings = list() nxos_check_args(module, warnings) result = {'changed': False, 'warnings': warnings} config = None try: info = get_capabilities(module) api = info.get('network_api') device_info = info.get('device_info', {}) os_platform = device_info.get('network_os_platform', '') except ConnectionError: api = '' os_platform = '' if api == 'cliconf' and module.params['replace'] == 'config': if '9K' not in os_platform: module.fail_json( msg= 'replace: config is supported only on Nexus 9K series switches' ) if module.params['replace_src']: if module.params['replace'] != 'config': module.fail_json( msg='replace: config is required with replace_src') if module.params['backup'] or (module._diff and module.params['diff_against'] == 'running'): contents = get_config(module) config = NetworkConfig(indent=2, contents=contents) if module.params['backup']: result['__backup__'] = contents if any((module.params['src'], module.params['lines'], module.params['replace_src'])): match = module.params['match'] replace = module.params['replace'] candidate = get_candidate(module) if match != 'none' and replace != 'config': config = get_running_config(module, config) path = module.params['parents'] configobjs = candidate.difference(config, match=match, replace=replace, path=path) 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 if not module.check_mode: load_config(module, commands) result['changed'] = True running_config = module.params['running_config'] startup_config = None diff_ignore_lines = module.params['diff_ignore_lines'] if module.params['save_when'] == 'always' or module.params['save']: save_config(module, result) elif module.params['save_when'] == 'modified': output = execute_show_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 = execute_show_commands(module, 'show running-config') contents = output[0] else: contents = running_config # 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 = execute_show_commands(module, 'show startup-config') contents = output[0] else: contents = output[0] 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 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 main(): argument_spec = dict( lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), src=dict(type='path'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block']), update=dict(choices=['merge', 'check'], default='merge'), save=dict(type='bool', default=False), config=dict(), backup=dict(type='bool', default=False) ) argument_spec.update(dellos10_argument_spec) mutually_exclusive = [('lines', 'src')] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True) parents = module.params['parents'] or list() match = module.params['match'] replace = module.params['replace'] warnings = list() check_args(module, warnings) result = dict(changed=False, saved=False, warnings=warnings) if module.params['backup']: if not module.check_mode: result['__backup__'] = get_config(module) commands = list() candidate = get_candidate(module) if any((module.params['lines'], module.params['src'])): if match != 'none': config = get_running_config(module) if parents: contents = get_sublevel_config(config, module) config = NetworkConfig(contents=contents, indent=1) else: config = NetworkConfig(contents=config, indent=1) configobjs = candidate.difference(config, match=match, replace=replace) else: configobjs = candidate.items if configobjs: commands = dumps(configobjs, 'commands') if ((isinstance((module.params['lines']), list)) and (isinstance((module.params['lines'][0]), dict)) and (['prompt', 'answer'].issubset(module.params['lines'][0]))): cmd = {'command': commands, 'prompt': module.params['lines'][0]['prompt'], 'answer': module.params['lines'][0]['answer']} commands = [module.jsonify(cmd)] else: commands = commands.split('\n') if module.params['before']: commands[:0] = module.params['before'] if module.params['after']: commands.extend(module.params['after']) if not module.check_mode and module.params['update'] == 'merge': load_config(module, commands) result['changed'] = True result['commands'] = commands result['updates'] = commands if module.params['save']: result['changed'] = True if not module.check_mode: cmd = {r'command': 'copy running-config startup-config', r'prompt': r'\[confirm yes/no\]:\s?$', 'answer': 'yes'} run_commands(module, [cmd]) result['saved'] = True else: module.warn('Skipping command `copy running-config startup-config`' 'due to check_mode. Configuration not copied to ' 'non-volatile storage') module.exit_json(**result)