def main(): argument_spec = dict( master=dict(required=False, type='bool'), stratum=dict(required=False, type='str'), logging=dict(required=False, type='bool'), state=dict(choices=['absent', 'present'], default='present'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() master = module.params['master'] stratum = module.params['stratum'] logging = module.params['logging'] state = module.params['state'] if stratum and master is False: if stratum != 8: module.fail_json(msg='master MUST be True when stratum is changed') current = get_current(module) result = {'changed': False} commands = list() if state == 'absent': if current['master']: commands.append('no ntp master') if current['logging']: commands.append('no ntp logging') elif state == 'present': if master and not current['master']: commands.append('ntp master') elif master is False and current['master']: commands.append('no ntp master') if stratum and stratum != current['stratum']: commands.append('ntp master %s' % stratum) if logging and not current['logging']: commands.append('ntp logging') elif logging is False and current['logging']: commands.append('no ntp logging') result['commands'] = commands result['updates'] = commands if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True result['warnings'] = warnings module.exit_json(**result)
def main(): """ main entry point for module execution """ element_spec = dict(name=dict(), configured_password=dict(no_log=True), update_password=dict(default='always', choices=['on_create', 'always']), roles=dict(type='list', aliases=['role']), sshkey=dict(), state=dict(default='present', choices=['present', 'absent'])) aggregate_spec = deepcopy(element_spec) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict(aggregate=dict(type='list', elements='dict', options=aggregate_spec, aliases=['collection', 'users']), purge=dict(type='bool', default=False)) argument_spec.update(element_spec) argument_spec.update(nxos_argument_spec) mutually_exclusive = [('name', 'aggregate')] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True) result = {'changed': False} want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands(update_objects(want, have), module) if module.params['purge']: want_users = [x['name'] for x in want] have_users = [x['name'] for x in have] for item in set(have_users).difference(want_users): if item != 'admin': item = item.replace("\\", "\\\\") commands.append('no username %s' % item) result['commands'] = commands # the nxos cli prevents this by rule so capture it and display # a nice failure message if 'no username admin' in commands: module.fail_json(msg='cannot delete the `admin` account') if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result)
def main(): argument_spec = dict( system_mode_maintenance=dict(required=False, type='bool'), system_mode_maintenance_dont_generate_profile=dict(required=False, type='bool'), system_mode_maintenance_timeout=dict(required=False, type='str'), system_mode_maintenance_shutdown=dict(required=False, type='bool'), system_mode_maintenance_on_reload_reset_reason=dict( required=False, choices=[ 'hw_error', 'svc_failure', 'kern_failure', 'wdog_timeout', 'fatal_error', 'lc_failure', 'match_any', 'manual_reload', 'any_other', 'maintenance' ]), state=dict(choices=['absent', 'present', 'default'], default='present', required=False)) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[[ 'system_mode_maintenance', 'system_mode_maintenance_dont_generate_profile', 'system_mode_maintenance_timeout', 'system_mode_maintenance_shutdown', 'system_mode_maintenance_on_reload_reset_reason' ]], required_one_of=[[ 'system_mode_maintenance', 'system_mode_maintenance_dont_generate_profile', 'system_mode_maintenance_timeout', 'system_mode_maintenance_shutdown', 'system_mode_maintenance_on_reload_reset_reason' ]], supports_check_mode=True) warnings = list() state = module.params['state'] mode = get_system_mode(module) commands = get_commands(module, state, mode) changed = False if commands: if module.check_mode: module.exit_json(changed=True, commands=commands) else: load_config(module, commands) changed = True result = {} result['changed'] = changed if module._verbosity > 0: final_system_mode = get_system_mode(module) result['final_system_mode'] = final_system_mode result['updates'] = commands result['warnings'] = warnings module.exit_json(**result)
def main(): argument_spec = dict(anycast_gateway_mac=dict(required=True, type='str'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() result = {'changed': False, 'commands': [], 'warnings': warnings} args = PARAM_TO_COMMAND_KEYMAP.keys() existing = get_existing(module, args) proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) candidate = CustomNetworkConfig(indent=3) get_commands(module, existing, proposed, candidate) if candidate: candidate = candidate.items_text() result['commands'] = candidate if not module.check_mode: load_config(module, candidate) result['changed'] = True module.exit_json(**result)
def main(): argument_spec = dict( bfd=dict(required=False, type='str', choices=['enable', 'disable']), ssm_range=dict(required=False, type='list', default=[]), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() result = {'changed': False, 'commands': [], 'warnings': warnings} params = module.params args = [k for k in PARAM_TO_COMMAND_KEYMAP.keys() if params[k] is not None] # SSM syntax check if 'ssm_range' in args: for item in params['ssm_range']: if re.search('none|default', item): break if len(item.split('.')) != 4: module.fail_json( msg="Valid ssm_range values are multicast addresses " "or the keyword 'none' or the keyword 'default'.") existing = get_existing(module, args) proposed_args = dict((k, v) for k, v in params.items() if k in args) proposed = {} for key, value in proposed_args.items(): if key == 'ssm_range': if value and value[0] == 'default': if existing.get(key): proposed[key] = 'default' else: v = sorted(set([str(i) for i in value])) ex = sorted(set([str(i) for i in existing.get(key, [])])) if v != ex: proposed[key] = ' '.join(str(s) for s in v) elif key == 'bfd': if value != existing.get('bfd', 'disable'): proposed[key] = value elif value != existing.get(key): proposed[key] = value candidate = CustomNetworkConfig(indent=3) get_commands(module, existing, proposed, candidate) if candidate: candidate = candidate.items_text() result['commands'] = candidate result['changed'] = True load_config(module, candidate) module.exit_json(**result)
def main(): argument_spec = dict( name=dict(required=False, type='str'), interface=dict(required=True), direction=dict(required=True, choices=['egress', 'ingress']), state=dict(choices=['absent', 'present'], default='present'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = dict(changed=False, warnings=warnings) state = module.params['state'] name = module.params['name'] interface = module.params['interface'].lower() direction = module.params['direction'].lower() proposed = dict(name=name, interface=interface, direction=direction) existing = check_for_acl_int_present(module, name, interface, direction) cmds = [] commands = [] if state == 'present': if not existing: command = apply_acl(proposed) if command: commands.append(command) elif state == 'absent': if existing: command = remove_acl(proposed) if command: commands.append(command) if commands: cmds = flatten_list(commands) if cmds: if module.check_mode: module.exit_json(changed=True, commands=cmds) else: load_config(module, cmds) results['changed'] = True if 'configure' in cmds: cmds.pop(0) else: cmds = [] results['commands'] = cmds module.exit_json(**results)
def main(): argument_spec = dict(vni=dict(required=True, type='str'), route_distinguisher=dict(required=False, type='str'), route_target_both=dict(required=False, type='list'), route_target_import=dict(required=False, type='list'), route_target_export=dict(required=False, type='list'), state=dict(choices=['present', 'absent'], default='present', required=False)) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = dict(changed=False, warnings=warnings) state = module.params['state'] args = PARAM_TO_COMMAND_KEYMAP.keys() existing = get_existing(module, args) proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) commands = [] parents = [] proposed = {} for key, value in proposed_args.items(): if key != 'vni': if value == 'true': value = True elif value == 'false': value = False if existing.get(key) != value: proposed[key] = value if state == 'present': commands, parents = state_present(module, existing, proposed) elif state == 'absent' and existing: commands, parents = state_absent(module, existing, proposed) if commands: candidate = CustomNetworkConfig(indent=3) candidate.add(commands, parents=parents) candidate = candidate.items_text() if not module.check_mode: load_config(module, candidate) results['changed'] = True results['commands'] = candidate else: results['commands'] = [] module.exit_json(**results)
def main(): argument_spec = dict(flush_routes=dict(type='bool'), enforce_rtr_alert=dict(type='bool'), restart=dict(type='bool', default=False), state=dict(choices=['present', 'default'], default='present')) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() current = get_current(module) desired = get_desired(module) state = module.params['state'] commands = list() if state == 'default': if current['flush_routes']: commands.append('no ip igmp flush-routes') if current['enforce_rtr_alert']: commands.append('no ip igmp enforce-router-alert') elif state == 'present': ldict = { 'flush_routes': 'flush-routes', 'enforce_rtr_alert': 'enforce-router-alert' } for arg in ['flush_routes', 'enforce_rtr_alert']: if desired[arg] and not current[arg]: commands.append('ip igmp {0}'.format(ldict.get(arg))) elif current[arg] and not desired[arg]: commands.append('no ip igmp {0}'.format(ldict.get(arg))) result = {'changed': False, 'updates': commands, 'warnings': warnings} if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True if module.params['restart']: cmd = {'command': 'restart igmp', 'output': 'text'} run_commands(module, cmd) module.exit_json(**result)
def main(): element_spec = dict( prefix=dict(type='str', aliases=['address']), next_hop=dict(type='str'), vrf=dict(type='str', default='default'), tag=dict(type='str'), route_name=dict(type='str'), pref=dict(type='str', aliases=['admin_distance']), state=dict(choices=['absent', 'present'], default='present'), track=dict(type='int'), ) aggregate_spec = deepcopy(element_spec) aggregate_spec['prefix'] = dict(required=True) aggregate_spec['next_hop'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec)) argument_spec.update(element_spec) argument_spec.update(nxos_argument_spec) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) warnings = list() result = {'changed': False, 'commands': []} if warnings: result['warnings'] = warnings want = map_params_to_obj(module) for w in want: prefix = normalize_prefix(module, w['prefix']) candidate = CustomNetworkConfig(indent=3) reconcile_candidate(module, candidate, prefix, w) if not module.check_mode and candidate: candidate = candidate.items_text() load_config(module, candidate) result['commands'].extend(candidate) result['changed'] = True module.exit_json(**result)
def main(): argument_spec = dict(commands=dict(required=False, type='list'), mode=dict(required=True, choices=['maintenance', 'normal']), state=dict(choices=['absent', 'present'], default='present')) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() state = module.params['state'] commands = module.params['commands'] or [] if state == 'absent' and commands: module.fail_json(msg='when state is absent, no command can be used.') existing = invoke('get_existing', module) end_state = existing changed = False result = {} cmds = [] if state == 'present' or (state == 'absent' and existing): cmds = invoke('state_%s' % state, module, existing, commands) if module.check_mode: module.exit_json(changed=True, commands=cmds) else: if cmds: load_config(module, cmds) changed = True end_state = invoke('get_existing', module) result['changed'] = changed if module._verbosity > 0: end_state = invoke('get_existing', module) result['end_state'] = end_state result['existing'] = existing result['proposed'] = commands result['updates'] = cmds result['warnings'] = warnings module.exit_json(**result)
def main(): argument_spec = dict(version=dict(type='str', choices=['1', '2'], required=True), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() version = module.params['version'] existing = get_vtp_config(module) end_state = existing args = dict(version=version) changed = False proposed = dict((k, v) for k, v in args.items() if v is not None) delta = dict(set(proposed.items()).difference(existing.items())) commands = [] if delta: commands.append(['vtp version {0}'.format(version)]) cmds = flatten_list(commands) if cmds: if module.check_mode: module.exit_json(changed=True, commands=cmds) else: changed = True load_config(module, cmds) end_state = get_vtp_config(module) if 'configure' in cmds: cmds.pop(0) results = {} results['proposed'] = proposed results['existing'] = existing results['end_state'] = end_state results['updates'] = cmds results['changed'] = changed results['warnings'] = warnings module.exit_json(**results)
def main(): """ main entry point for module execution """ element_spec = dict( group=dict(type='str'), mode=dict(required=False, choices=['on', 'active', 'passive'], default='on', type='str'), min_links=dict(required=False, default=None, type='int'), members=dict(required=False, default=None, type='list'), force=dict(required=False, default=False, type='bool'), state=dict(required=False, choices=['absent', 'present'], default='present') ) aggregate_spec = deepcopy(element_spec) aggregate_spec['group'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec), purge=dict(default=False, type='bool') ) argument_spec.update(element_spec) argument_spec.update(nxos_argument_spec) required_one_of = [['group', 'aggregate']] mutually_exclusive = [['group', 'aggregate']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands((want, have), module) result['commands'] = commands if commands: if not module.check_mode: resp = load_config(module, commands, True) if resp: for item in resp: if item: if isinstance(item, dict): err_str = item['clierror'] else: err_str = item if 'cannot add' in err_str.lower(): module.fail_json(msg=err_str) result['changed'] = True module.exit_json(**result)
def check_install_in_progress(module, commands, opts): for attempt in range(20): data = parse_show_install(load_config(module, commands, True, opts)) if data['install_in_progress']: sleep(1) continue break return data
def main(): """ main entry point for module execution """ element_spec = dict( name=dict(type='str', aliases=['vrf']), description=dict(type='str'), vni=dict(type='str'), rd=dict(type='str'), admin_state=dict(type='str', default='up', choices=['up', 'down']), interfaces=dict(type='list'), associated_interfaces=dict(type='list'), delay=dict(type='int', default=10), state=dict(type='str', default='present', choices=['present', 'absent']), ) aggregate_spec = deepcopy(element_spec) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict( aggregate=dict(type='list', elements='dict', options=aggregate_spec), purge=dict(type='bool', default=False), ) argument_spec.update(element_spec) argument_spec.update(nxos_argument_spec) required_one_of = [['name', 'aggregate']] mutually_exclusive = [['name', 'aggregate']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module) have = map_config_to_obj(want, element_spec, module) commands = map_obj_to_commands((want, have), module) result['commands'] = commands if commands and not module.check_mode: responses = load_config(module, commands, opts={'catch_clierror': True}) vrf_error_check(module, commands, responses) result['changed'] = True check_declarative_intent_params(want, module, element_spec, result) module.exit_json(**result)
def main(): """ main entry point for module execution """ element_spec = dict(name=dict(), ipv4=dict(), ipv6=dict(), state=dict(default='present', choices=['present', 'absent'])) aggregate_spec = deepcopy(element_spec) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict(aggregate=dict(type='list', elements='dict', options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(nxos_argument_spec) required_one_of = [['name', 'aggregate']] mutually_exclusive = [['name', 'aggregate']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() result = {'changed': False} want = map_params_to_obj(module) have = map_config_to_obj(want, module) commands = map_obj_to_commands((want, have), module, warnings) result['commands'] = commands if warnings: result['warnings'] = warnings if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result)
def main(): """ main entry point for module execution """ argument_spec = dict( http=dict(aliases=['enable_http'], type='bool', default=True), http_port=dict(type='int', default=80), https=dict(aliases=['enable_https'], type='bool', default=False), https_port=dict(type='int', default=443), sandbox=dict(aliases=['enable_sandbox'], type='bool'), state=dict(default='present', choices=['started', 'stopped', 'present', 'absent']), ssl_strong_ciphers=dict(type='bool', default=False), tlsv1_0=dict(type='bool', default=True), tlsv1_1=dict(type='bool', default=False), tlsv1_2=dict(type='bool', default=False)) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() warning_msg = "Module nxos_nxapi currently defaults to configure 'http port 80'. " warning_msg += "Default behavior is changing to configure 'https port 443'" warning_msg += " when params 'http, http_port, https, https_port' are not set in the playbook" module.deprecate(msg=warning_msg, version="2.11") capabilities = get_capabilities(module) check_args(module, warnings, capabilities) want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands(want, have, module, warnings, capabilities) result = {'changed': False, 'warnings': warnings, 'commands': commands} if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result)
def main(): """ main entry point for module execution """ argument_spec = dict( hostname=dict(), domain_lookup=dict(type='bool'), # { name: <str>, vrf: <str> } domain_name=dict(type='list'), # {name: <str>, vrf: <str> } domain_search=dict(type='list'), # { server: <str>; vrf: <str> } name_servers=dict(type='list'), system_mtu=dict(type='str'), state=dict(default='present', choices=['present', 'absent']) ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands(want, have, module) result['commands'] = commands if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result)
def main(): """ main entry point for module execution """ argument_spec = dict(banner=dict(required=True, choices=['exec', 'motd']), text=dict(), state=dict(default='present', choices=['present', 'absent'])) argument_spec.update(nxos_argument_spec) required_if = [('state', 'present', ('text', ))] module = AnsibleModule(argument_spec=argument_spec, required_if=required_if, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands(want, have, module) result['commands'] = commands if commands: if not module.check_mode: msgs = load_config(module, commands, True) if msgs: for item in msgs: if item: if isinstance(item, dict): err_str = item['clierror'] else: err_str = item if 'more than 40 lines' in err_str or 'buffer overflowed' in err_str: load_config(module, commands) result['changed'] = True module.exit_json(**result)
def main(): argument_spec = dict(ospf=dict(required=True, type='str'), state=dict(choices=['present', 'absent'], default='present', required=False)) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() result = dict(changed=False, warnings=warnings) state = module.params['state'] ospf = str(module.params['ospf']) existing = get_existing(module) proposed = dict(ospf=ospf) if not existing: existing_list = [] else: existing_list = existing['ospf'] candidate = CustomNetworkConfig(indent=3) if state == 'present' and ospf not in existing_list: state_present(module, proposed, candidate) if state == 'absent' and ospf in existing_list: state_absent(module, proposed, candidate) if candidate: candidate = candidate.items_text() load_config(module, candidate) result['changed'] = True result['commands'] = candidate else: result['commands'] = [] module.exit_json(**result)
def main(): """ main entry point for module execution """ argument_spec = dict( state=dict(default='present', choices=['present', 'absent', 'enabled', 'disabled'])) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings HAS_LLDP = has_lldp(module) commands = [] if module.params['state'] == 'absent' and HAS_LLDP: commands.append('no feature lldp') elif module.params['state'] == 'present' and not HAS_LLDP: commands.append('feature lldp') result['commands'] = commands if commands: # On N35 A8 images, some features return a yes/no prompt # on enablement or disablement. Bypass using terminal dont-ask commands.insert(0, 'terminal dont-ask') if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result)
def main(): argument_spec = dict(feature=dict(type='str', required=True), state=dict(choices=['enabled', 'disabled'], default='enabled')) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = dict(changed=False, warnings=warnings) feature = validate_feature(module) state = module.params['state'].lower() available_features = get_available_features(feature, module) if feature not in available_features: module.fail_json(msg='Invalid feature name.', features_currently_supported=available_features, invalid_feature=feature) else: existstate = available_features[feature] existing = dict(state=existstate) proposed = dict(state=state) results['changed'] = False cmds = get_commands(proposed, existing, state, module) if cmds: # On N35 A8 images, some features return a yes/no prompt # on enablement or disablement. Bypass using terminal dont-ask cmds.insert(0, 'terminal dont-ask') if not module.check_mode: load_config(module, cmds) results['changed'] = True results['commands'] = cmds module.exit_json(**results)
def config_cmd_operation(module, cmd): iteration = 0 while iteration < 10: msg = load_config(module, [cmd], True) if msg: if 'another install operation is in progress' in msg[0].lower( ) or 'failed' in msg[0].lower(): time.sleep(2) iteration += 1 else: return else: return
def main(): argument_spec = dict( echo_interface=dict(required=False, type='str'), echo_rx_interval=dict(required=False, type='int'), interval=dict(required=False, type='dict'), slow_timer=dict(required=False, type='int'), startup_timer=dict(required=False, type='int'), ipv4_echo_rx_interval=dict(required=False, type='int'), ipv4_interval=dict(required=False, type='dict'), ipv4_slow_timer=dict(required=False, type='int'), ipv6_echo_rx_interval=dict(required=False, type='int'), ipv6_interval=dict(required=False, type='dict'), ipv6_slow_timer=dict(required=False, type='int'), fabricpath_interval=dict(required=False, type='dict'), fabricpath_slow_timer=dict(required=False, type='int'), fabricpath_vlan=dict(required=False, type='int'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() cmd_ref = NxosCmdRef(module, BFD_CMD_REF) cmd_ref.get_existing() cmd_ref.get_playvals() cmds = reorder_cmds(cmd_ref.get_proposed()) result = { 'changed': False, 'commands': cmds, 'warnings': warnings, 'check_mode': module.check_mode } if cmds: result['changed'] = True if not module.check_mode: load_config(module, cmds) module.exit_json(**result)
def main(): argument_spec = dict( state=dict(choices=['enabled', 'disabled'], default='enabled'), group=dict(choices=[ 'aaa', 'bfd', 'bgp', 'bridge', 'callhome', 'cfs', 'config', 'eigrp', 'entity', 'feature-control', 'generic', 'hsrp', 'license', 'link', 'lldp', 'mmode', 'ospf', 'pim', 'rf', 'rmon', 'snmp', 'storm-control', 'stpx', 'switchfabric', 'syslog', 'sysmgr', 'system', 'upgrade', 'vtp', 'all' ], required=True), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = {'changed': False, 'commands': [], 'warnings': warnings} group = module.params['group'].lower() state = module.params['state'] existing = get_snmp_traps(group, module) commands = get_trap_commands(group, state, existing, module) cmds = flatten_list(commands) if cmds: results['changed'] = True if not module.check_mode: load_config(module, cmds) if 'configure' in cmds: cmds.pop(0) results['commands'] = cmds module.exit_json(**results)
def main(): argument_spec = dict( location=dict(required=True, type='str'), state=dict(choices=['absent', 'present'], default='present'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = {'changed': False, 'commands': [], 'warnings': warnings} location = module.params['location'] state = module.params['state'] existing = get_snmp_location(module) commands = [] if state == 'absent': if existing and existing['location'] == location: commands.append('no snmp-server location') elif state == 'present': if not existing or existing['location'] != location: commands.append('snmp-server location {0}'.format(location)) cmds = flatten_list(commands) if cmds: results['changed'] = True if not module.check_mode: load_config(module, cmds) if 'configure' in cmds: cmds.pop(0) results['commands'] = cmds module.exit_json(**results)
def main(): argument_spec = dict( nv_overlay_evpn=dict(required=True, type='bool'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) result = {'changed': False} warnings = list() if warnings: result['warnings'] = warnings config = get_config(module) commands = list() info = get_capabilities(module).get('device_info', {}) os_platform = info.get('network_os_platform', '') if '3K' in os_platform: module.fail_json(msg='This module is not supported on Nexus 3000 series') if module.params['nv_overlay_evpn'] is True: if 'nv overlay evpn' not in config: commands.append('nv overlay evpn') elif 'nv overlay evpn' in config: commands.append('no nv overlay evpn') if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True result['commands'] = commands module.exit_json(**result)
def vrf_error_check(module, commands, responses): """Checks for VRF config errors and executes a retry in some circumstances. """ pattern = 'ERROR: Deletion of VRF .* in progress' if re.search(pattern, str(responses)): # Allow delay/retry for VRF changes time.sleep(15) responses = load_config(module, commands, opts={'catch_clierror': True}) if re.search(pattern, str(responses)): module.fail_json(msg='VRF config (and retry) failure: %s ' % responses) module.warn('VRF config delayed by VRF deletion - passed on retry')
def check_mode_nextgen(module, issu, image, kick=None): """Use the 'install all impact' command for check_mode""" opts = {'ignore_timeout': True} commands = build_install_cmd_set(issu, image, kick, 'impact') data = parse_show_install(load_config(module, commands, True, opts)) # If an error is encountered when issu is 'desired' then try again # but set issu to 'no' if data['error'] and issu == 'desired': issu = 'no' commands = build_install_cmd_set(issu, image, kick, 'impact') # The system may be busy from the previous call to check_mode so loop # until it's done. data = check_install_in_progress(module, commands, opts) if data['server_error']: data['error'] = True data['upgrade_cmd'] = commands return data
def activate_reload(module, pkg, flag): iteration = 0 if flag: cmd = 'install activate {0} forced'.format(pkg) else: cmd = 'install deactivate {0} forced'.format(pkg) opts = {'ignore_timeout': True} while iteration < 10: msg = load_config(module, [cmd], True, opts) if msg: if isinstance(msg[0], int): if msg[0] == -32603: return cmd elif isinstance(msg[0], str): if 'another install operation is in progress' in msg[0].lower( ) or 'failed' in msg[0].lower(): time.sleep(2) iteration += 1
def main(): element_spec = dict( name=dict(required=True, type='str'), pwwn=dict(type='str'), remove=dict(type='bool', default=False) ) element_spec_rename = dict( old_name=dict(required=True, type='str'), new_name=dict(required=True, type='str'), ) argument_spec = dict( distribute=dict(type='bool'), mode=dict(type='str', choices=['enhanced', 'basic']), da=dict(type='list', elements='dict', options=element_spec), rename=dict(type='list', elements='dict', options=element_spec_rename) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() messages = list() commands_to_execute = list() result = {'changed': False} distribute = module.params['distribute'] mode = module.params['mode'] da = module.params['da'] rename = module.params['rename'] # Step 0.0: Validate syntax of name and pwwn # Also validate syntax of rename arguments if da is not None: for eachdict in da: name = eachdict['name'] pwwn = eachdict['pwwn'] remove = eachdict['remove'] if pwwn is not None: pwwn = pwwn.lower() if not remove: if pwwn is None: module.fail_json( msg='This device alias name ' + str(name) + ' which needs to be added, doenst have pwwn specified . Please specify a valid pwwn') if not isNameValid(name): module.fail_json(msg='This pwwn name is invalid : ' + str(name) + '. Note that name cannot be more than 64 chars and it should start with a letter') if not isPwwnValid(pwwn): module.fail_json(msg='This pwwn is invalid : ' + str(pwwn) + '. Please check that its a valid pwwn') if rename is not None: for eachdict in rename: oldname = eachdict['old_name'] newname = eachdict['new_name'] if not isNameValid(oldname): module.fail_json(msg='This pwwn name is invalid : ' + str(oldname) + '. Note that name cannot be more than 64 chars and it should start with a letter') if not isNameValid(newname): module.fail_json(msg='This pwwn name is invalid : ' + str(newname) + '. Note that name cannot be more than 64 chars and it should start with a letter') # Step 0.1: Check DA status shDAStausObj = showDeviceAliasStatus(module) d = shDAStausObj.getDistribute() m = shDAStausObj.getMode() if shDAStausObj.isLocked(): module.fail_json(msg='device-alias has acquired lock on the switch. Hence cannot procced.') # Step 1: Process distribute commands = [] if distribute is not None: if distribute: # playbook has distribute as True(enabled) if d == "disabled": # but switch distribute is disabled(false), so set it to true(enabled) commands.append("device-alias distribute") messages.append('device-alias distribute changed from disabled to enabled') else: messages.append('device-alias distribute remains unchanged. current distribution mode is enabled') else: # playbook has distribute as False(disabled) if d == "enabled": # but switch distribute is enabled(true), so set it to false(disabled) commands.append("no device-alias distribute") messages.append('device-alias distribute changed from enabled to disabled') else: messages.append('device-alias distribute remains unchanged. current distribution mode is disabled') cmds = flatten_list(commands) if cmds: commands_to_execute = commands_to_execute + cmds if module.check_mode: # Check mode implemented at the da_add/da_remove stage pass else: result['changed'] = True load_config(module, cmds) # Step 2: Process mode commands = [] if mode is not None: if mode == 'basic': # playbook has mode as basic if m == 'enhanced': # but switch mode is enhanced, so set it to basic commands.append("no device-alias mode enhanced") messages.append('device-alias mode changed from enhanced to basic') else: messages.append('device-alias mode remains unchanged. current mode is basic') else: # playbook has mode as enhanced if m == 'basic': # but switch mode is basic, so set it to enhanced commands.append("device-alias mode enhanced") messages.append('device-alias mode changed from basic to enhanced') else: messages.append('device-alias mode remains unchanged. current mode is enhanced') if commands: if distribute: commands.append("device-alias commit") commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] else: if distribute is None and d == 'enabled': commands.append("device-alias commit") commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] cmds = flatten_list(commands) if cmds: commands_to_execute = commands_to_execute + cmds if module.check_mode: # Check mode implemented at the end pass else: result['changed'] = True load_config(module, cmds) # Step 3: Process da commands = [] shDADatabaseObj = showDeviceAliasDatabase(module) if da is not None: da_remove_list = [] da_add_list = [] for eachdict in da: name = eachdict['name'] pwwn = eachdict['pwwn'] remove = eachdict['remove'] if pwwn is not None: pwwn = pwwn.lower() if remove: if shDADatabaseObj.isNameInDaDatabase(name): commands.append("no device-alias name " + name) da_remove_list.append(name) else: messages.append(name + ' - This device alias name is not in switch device-alias database, hence cannot be removed.') else: if shDADatabaseObj.isNamePwwnPresentInDatabase(name, pwwn): messages.append(name + ' : ' + pwwn + ' - This device alias name,pwwn is already in switch device-alias database, \ hence nothing to configure') else: if shDADatabaseObj.isNameInDaDatabase(name): module.fail_json( msg=name + ' - This device alias name is already present in switch device-alias database but assigned to another pwwn (' + shDADatabaseObj.getPwwnByName(name) + ') hence cannot be added') elif shDADatabaseObj.isPwwnInDaDatabase(pwwn): module.fail_json( msg=pwwn + ' - This device alias pwwn is already present in switch device-alias database but assigned to another name (' + shDADatabaseObj.getNameByPwwn(pwwn) + ') hence cannot be added') else: commands.append("device-alias name " + name + " pwwn " + pwwn) da_add_list.append(name) if len(da_add_list) != 0 or len(da_remove_list) != 0: commands = ["device-alias database"] + commands if distribute: commands.append("device-alias commit") commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] else: if distribute is None and d == 'enabled': commands.append("device-alias commit") commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] cmds = flatten_list(commands) if cmds: commands_to_execute = commands_to_execute + cmds if module.check_mode: # Check mode implemented at the end pass else: result['changed'] = True load_config(module, cmds) if len(da_remove_list) != 0: messages.append('the required device-alias were removed. ' + ','.join(da_remove_list)) if len(da_add_list) != 0: messages.append('the required device-alias were added. ' + ','.join(da_add_list)) # Step 5: Process rename commands = [] if rename is not None: for eachdict in rename: oldname = eachdict['old_name'] newname = eachdict['new_name'] if shDADatabaseObj.isNameInDaDatabase(newname): module.fail_json( changed=False, commands=cmds, msg=newname + " - this name is already present in the device-alias database, hence we cannot rename " + oldname + " with this one") if shDADatabaseObj.isNameInDaDatabase(oldname): commands.append('device-alias rename ' + oldname + ' ' + newname) else: module.fail_json(changed=False, commands=cmds, msg=oldname + " - this name is not present in the device-alias database, hence we cannot rename.") if len(commands) != 0: commands = ["device-alias database"] + commands if distribute: commands.append("device-alias commit") commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] else: if distribute is None and d == 'enabled': commands.append("device-alias commit") commands = ["terminal dont-ask"] + commands + ["no terminal dont-ask"] cmds = flatten_list(commands) if cmds: commands_to_execute = commands_to_execute + cmds if module.check_mode: # Check mode implemented at the end pass else: result['changed'] = True load_config(module, cmds) # Step END: check for 'check' mode if module.check_mode: module.exit_json(changed=False, commands=commands_to_execute, msg="Check Mode: No cmds issued to the hosts") result['messages'] = messages result['commands'] = commands_to_execute result['warnings'] = warnings module.exit_json(**result)