def check_args(module, warnings): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'nxapi': module.fail_json(msg='module not supported over nxapi transport') os_platform = device_info['device_info']['network_os_platform'] if '7K' not in os_platform and module.params['sandbox']: module.fail_json( msg= 'sandbox or enable_sandbox is supported on NX-OS 7K series of switches' ) state = module.params['state'] if state == 'started': module.params['state'] = 'present' warnings.append('state=started is deprecated and will be removed in a ' 'a future release. Please use state=present instead') elif state == 'stopped': module.params['state'] = 'absent' warnings.append('state=stopped is deprecated and will be removed in a ' 'a future release. Please use state=absent instead') for key in ['http_port', 'https_port']: if module.params[key] is not None: if not 1 <= module.params[key] <= 65535: module.fail_json(msg='%s must be between 1 and 65535' % key) return warnings
def check_args(module, warnings): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'nxapi': module.fail_json(msg='module not supported over nxapi transport') os_platform = device_info['device_info']['network_os_platform'] if '7K' not in os_platform and module.params['sandbox']: module.fail_json(msg='sandbox or enable_sandbox is supported on NX-OS 7K series of switches') state = module.params['state'] if state == 'started': module.params['state'] = 'present' warnings.append('state=started is deprecated and will be removed in a ' 'a future release. Please use state=present instead') elif state == 'stopped': module.params['state'] = 'absent' warnings.append('state=stopped is deprecated and will be removed in a ' 'a future release. Please use state=absent instead') for key in ['http_port', 'https_port']: if module.params[key] is not None: if not 1 <= module.params[key] <= 65535: module.fail_json(msg='%s must be between 1 and 65535' % key) return warnings
def ipv6_structure_op_supported(self): data = get_capabilities(self.module) if data: nxos_os_version = data['device_info']['network_os_version'] unsupported_versions = ['I2', 'F1', 'A8'] for ver in unsupported_versions: if ver in nxos_os_version: return False return True
def validate_params(addr, interface, mask, dot1q, tag, allow_secondary, version, state, intf_type, module): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if state == "present": if addr is None or mask is None: module.fail_json(msg="An IP address AND a mask must be provided " "when state=present.") elif state == "absent" and version == "v6": if addr is None or mask is None: module.fail_json(msg="IPv6 address and mask must be provided when " "state=absent.") if intf_type != "ethernet" and network_api == 'cliconf': if is_default(interface, module) == "DNE": module.fail_json(msg="That interface does not exist yet. Create " "it first.", interface=interface) if mask is not None: try: if (int(mask) < 1 or int(mask) > 32) and version == "v4": raise ValueError elif int(mask) < 1 or int(mask) > 128: raise ValueError except ValueError: module.fail_json(msg="Warning! 'mask' must be an integer between" " 1 and 32 when version v4 and up to 128 " "when version v6.", version=version, mask=mask) if addr is not None and mask is not None: try: ipaddress.ip_interface(u'%s/%s' % (addr, mask)) except ValueError: module.fail_json(msg="Warning! Invalid ip address or mask set.", addr=addr, mask=mask) if dot1q is not None: try: if 2 > dot1q > 4093: raise ValueError except ValueError: module.fail_json(msg="Warning! 'dot1q' must be an integer between" " 2 and 4093", dot1q=dot1q) if tag is not None: try: if 0 > tag > 4294967295: raise ValueError except ValueError: module.fail_json(msg="Warning! 'tag' must be an integer between" " 0 (default) and 4294967295." "To use tag you must set 'addr' and 'mask' params.", tag=tag) if allow_secondary is not None: try: if addr is None or mask is None: raise ValueError except ValueError: module.fail_json(msg="Warning! 'secondary' can be used only when 'addr' and 'mask' set.", allow_secondary=allow_secondary)
def validate_params(addr, interface, mask, dot1q, tag, allow_secondary, version, state, intf_type, module): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if state == "present": if addr is None or mask is None: module.fail_json(msg="An IP address AND a mask must be provided " "when state=present.") elif state == "absent" and version == "v6": if addr is None or mask is None: module.fail_json(msg="IPv6 address and mask must be provided when " "state=absent.") if intf_type != "ethernet" and network_api == 'cliconf': if is_default(interface, module) == "DNE": module.fail_json(msg="That interface does not exist yet. Create " "it first.", interface=interface) if mask is not None: try: if (int(mask) < 1 or int(mask) > 32) and version == "v4": raise ValueError elif int(mask) < 1 or int(mask) > 128: raise ValueError except ValueError: module.fail_json(msg="Warning! 'mask' must be an integer between" " 1 and 32 when version v4 and up to 128 " "when version v6.", version=version, mask=mask) if addr is not None and mask is not None: try: ipaddress.ip_interface(u'%s/%s' % (addr, mask)) except ValueError: module.fail_json(msg="Warning! Invalid ip address or mask set.", addr=addr, mask=mask) if dot1q is not None: try: if 2 > dot1q > 4093: raise ValueError except ValueError: module.fail_json(msg="Warning! 'dot1q' must be an integer between" " 2 and 4093", dot1q=dot1q) if tag is not None: try: if 0 > tag > 4294967295: raise ValueError except ValueError: module.fail_json(msg="Warning! 'tag' must be an integer between" " 0 (default) and 4294967295." "To use tag you must set 'addr' and 'mask' params.", tag=tag) if allow_secondary is not None: try: if addr is None or mask is None: raise ValueError except ValueError: module.fail_json(msg="Warning! 'secondary' can be used only when 'addr' and 'mask' set.", allow_secondary=allow_secondary)
def execute_show_command(command, module, command_type='cli_show_ascii'): cmds = [command] device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': body = run_commands(module, cmds) elif network_api == 'nxapi': body = run_commands(module, cmds) return body
def execute_show_command(command, module, command_type='cli_show_ascii'): cmds = [command] device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': body = run_commands(module, cmds) elif network_api == 'nxapi': body = run_commands(module, cmds) return body
def execute_show_command(command, module): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': cmds = [command] body = run_commands(module, cmds) elif network_api == 'nxapi': cmds = {'command': command, 'output': 'text'} body = run_commands(module, cmds) return body
def execute_show_command(command, module): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': cmds = [command] body = run_commands(module, cmds) elif network_api == 'nxapi': cmds = {'command': command, 'output': 'text'} body = run_commands(module, cmds) return body
def execute_show_command(command, module): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': if 'show port-channel summary' in command: command += ' | json' cmds = [command] body = run_commands(module, cmds) elif network_api == 'nxapi': cmds = [command] body = run_commands(module, cmds) return body
def execute_show_command(command, module, command_type='cli_show'): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': if 'show run' not in command: command += ' | json' cmds = [command] body = run_commands(module, cmds) elif network_api == 'nxapi': cmds = [command] body = run_commands(module, cmds) return body
def execute_show_command(command, module): device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if network_api == 'cliconf': if 'show port-channel summary' in command: command += ' | json' cmds = [command] body = run_commands(module, cmds) elif network_api == 'nxapi': cmds = [command] body = run_commands(module, cmds) return body
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 get_vtp_password(module): command = 'show vtp password' output = 'json' cap = get_capabilities(module)['device_info']['network_os_model'] if re.search(r'Nexus 6', cap): output = 'text' body = execute_show_command(command, module, output)[0] if output == 'json': password = body.get('passwd', '') else: password = '' rp = r'VTP Password: (\S+)' mo = re.search(rp, body) if mo: password = mo.group(1) return str(password)
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 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 main(): """ main entry point for module execution """ element_spec = dict( vlan_id=dict(required=False, type='int'), vlan_range=dict(required=False), name=dict(required=False), interfaces=dict(type='list'), vlan_state=dict(choices=['active', 'suspend'], required=False, default='active'), mapped_vni=dict(required=False, type='int'), delay=dict(default=10, type='int'), state=dict(choices=['present', 'absent', 'active', 'suspend'], default='present', required=False), admin_state=dict(choices=['up', 'down'], required=False, default='up'), mode=dict(choices=['ce', 'fabricpath'], required=False, default='ce'), ) aggregate_spec = deepcopy(element_spec) aggregate_spec['vlan_id'] = 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 = [['vlan_id', 'aggregate', 'vlan_range']] mutually_exclusive = [['vlan_id', 'aggregate'], ['vlan_range', 'name'], ['vlan_id', 'vlan_range']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) info = get_capabilities(module).get('device_info', {}) os_platform = info.get('network_os_platform', '') warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings have = map_config_to_obj(module, os_platform) want = map_params_to_obj(module) if module.params['vlan_range']: commands = vlan_range_commands(module, have) result['commands'] = commands else: commands = map_obj_to_commands((want, have), module, os_platform) result['commands'] = commands if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True if want and result['changed']: check_declarative_intent_params(want, module, os_platform) module.exit_json(**result)
def main(): argument_spec = dict( group=dict(required=True, type='str'), interface=dict(required=True), interval=dict(required=False, type='str'), priority=dict(required=False, type='str'), preempt=dict(required=False, type='bool'), vip=dict(required=False, type='str'), admin_state=dict(required=False, type='str', choices=['shutdown', 'no shutdown', 'default'], default='shutdown'), authentication=dict(required=False, type='str'), state=dict(choices=['absent', 'present'], required=False, 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} state = module.params['state'] interface = module.params['interface'].lower() group = module.params['group'] priority = module.params['priority'] interval = module.params['interval'] preempt = module.params['preempt'] vip = module.params['vip'] authentication = module.params['authentication'] admin_state = module.params['admin_state'] device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if state == 'present' and not vip: module.fail_json(msg='the "vip" param is required when state=present') intf_type = get_interface_type(interface) if (intf_type != 'ethernet' and network_api == 'cliconf'): if is_default(interface, module) == 'DNE': module.fail_json(msg='That interface does not exist yet. Create ' 'it first.', interface=interface) if intf_type == 'loopback': module.fail_json(msg="Loopback interfaces don't support VRRP.", interface=interface) mode, name = get_interface_mode(interface, intf_type, module) if mode == 'layer2': module.fail_json(msg='That interface is a layer2 port.\nMake it ' 'a layer 3 port first.', interface=interface) args = dict(group=group, priority=priority, preempt=preempt, vip=vip, authentication=authentication, interval=interval, admin_state=admin_state) proposed = dict((k, v) for k, v in args.items() if v is not None) existing = get_existing_vrrp(interface, group, module, name) changed = False end_state = existing commands = [] if state == 'present': delta = dict( set(proposed.items()).difference(existing.items())) if delta: command = get_commands_config_vrrp(delta, existing, group) if command: commands.append(command) elif state == 'absent': if existing: commands.append(['no vrrp {0}'.format(group)]) if commands: commands.insert(0, ['interface {0}'.format(interface)]) commands = flatten_list(commands) results['commands'] = commands results['changed'] = True if not module.check_mode: load_config(module, commands) if 'configure' in commands: commands.pop(0) module.exit_json(**results)
def map_obj_to_commands(updates, module): commands = list() purge = module.params['purge'] want, have = updates info = get_capabilities(module).get('device_info') os_platform = info.get('network_os_platform') for w in want: vlan_id = w['vlan_id'] name = w['name'] interfaces = w.get('interfaces') or [] mapped_vni = w['mapped_vni'] mode = w['mode'] vlan_state = w['vlan_state'] admin_state = w['admin_state'] state = w['state'] del w['state'] obj_in_have = search_obj_in_list(vlan_id, have) or {} if not re.match('N[567]', os_platform) or (not obj_in_have.get('mode') and mode == 'ce'): mode = w['mode'] = None if state == 'absent': if obj_in_have: commands.append('no vlan {0}'.format(vlan_id)) elif state == 'present': if not obj_in_have: commands.append('vlan {0}'.format(vlan_id)) if name and name != 'default': commands.append('name {0}'.format(name)) if mode: commands.append('mode {0}'.format(mode)) if vlan_state: commands.append('state {0}'.format(vlan_state)) if mapped_vni != 'None' and mapped_vni != 'default': commands.append('vn-segment {0}'.format(mapped_vni)) if admin_state == 'up': commands.append('no shutdown') if admin_state == 'down': commands.append('shutdown') commands.append('exit') if interfaces and interfaces[0] != 'default': for i in interfaces: commands.append('interface {0}'.format(i)) commands.append('switchport') commands.append('switchport mode access') commands.append('switchport access vlan {0}'.format(vlan_id)) else: diff = get_diff(w, obj_in_have) if diff: commands.append('vlan {0}'.format(vlan_id)) for key, value in diff.items(): if key == 'name': if name != 'default': if name is not None: commands.append('name {0}'.format(value)) else: if not is_default_name(obj_in_have, vlan_id): commands.append('no name') if key == 'vlan_state' and value: commands.append('state {0}'.format(value)) if key == 'mapped_vni': if value == 'default': if obj_in_have['mapped_vni'] != 'None': commands.append('no vn-segment') elif value != 'None': commands.append('vn-segment {0}'.format(value)) if key == 'admin_state': if value == 'up': commands.append('no shutdown') elif value == 'down': commands.append('shutdown') if key == 'mode' and value: commands.append('mode {0}'.format(value)) if len(commands) > 1: commands.append('exit') else: del commands[:] if interfaces and interfaces[0] != 'default': if not obj_in_have['interfaces']: for i in interfaces: commands.append('vlan {0}'.format(vlan_id)) commands.append('exit') commands.append('interface {0}'.format(i)) commands.append('switchport') commands.append('switchport mode access') commands.append('switchport access vlan {0}'.format(vlan_id)) elif set(interfaces) != set(obj_in_have['interfaces']): missing_interfaces = list(set(interfaces) - set(obj_in_have['interfaces'])) for i in missing_interfaces: commands.append('vlan {0}'.format(vlan_id)) commands.append('exit') commands.append('interface {0}'.format(i)) commands.append('switchport') commands.append('switchport mode access') commands.append('switchport access vlan {0}'.format(vlan_id)) superfluous_interfaces = list(set(obj_in_have['interfaces']) - set(interfaces)) for i in superfluous_interfaces: commands.append('vlan {0}'.format(vlan_id)) commands.append('exit') commands.append('interface {0}'.format(i)) commands.append('switchport') commands.append('switchport mode access') commands.append('no switchport access vlan {0}'.format(vlan_id)) elif interfaces and interfaces[0] == 'default': if obj_in_have['interfaces']: for i in obj_in_have['interfaces']: commands.append('vlan {0}'.format(vlan_id)) commands.append('exit') commands.append('interface {0}'.format(i)) commands.append('switchport') commands.append('switchport mode access') commands.append('no switchport access vlan {0}'.format(vlan_id)) if purge: for h in have: if h['vlan_id'] == '1': module.warn("Deletion of vlan 1 is not allowed; purge will ignore vlan 1") continue obj_in_want = search_obj_in_list(h['vlan_id'], want) if not obj_in_want: commands.append('no vlan {0}'.format(h['vlan_id'])) return commands
def validate_feature(module, mode='show'): '''Some features may need to be mapped due to inconsistency between how they appear from "show feature" output and how they are configured''' feature = module.params['feature'] try: info = get_capabilities(module) device_info = info.get('device_info', {}) os_version = device_info.get('network_os_version', '') except ConnectionError: os_version = '' if '8.1' in os_version: feature_to_be_mapped = { 'show': { 'nv overlay': 'nve', 'vn-segment-vlan-based': 'vnseg_vlan', 'hsrp': 'hsrp_engine', 'fabric multicast': 'fabric_mcast', 'scp-server': 'scpServer', 'sftp-server': 'sftpServer', 'sla responder': 'sla_responder', 'sla sender': 'sla_sender', 'ssh': 'sshServer', 'tacacs+': 'tacacs', 'telnet': 'telnetServer', 'ethernet-link-oam': 'elo' }, 'config': { 'nve': 'nv overlay', 'vnseg_vlan': 'vn-segment-vlan-based', 'hsrp_engine': 'hsrp', 'fabric_mcast': 'fabric multicast', 'scpServer': 'scp-server', 'sftpServer': 'sftp-server', 'sla_sender': 'sla sender', 'sla_responder': 'sla responder', 'sshServer': 'ssh', 'tacacs': 'tacacs+', 'telnetServer': 'telnet', 'elo': 'ethernet-link-oam' } } else: feature_to_be_mapped = { 'show': { 'nv overlay': 'nve', 'vn-segment-vlan-based': 'vnseg_vlan', 'hsrp': 'hsrp_engine', 'fabric multicast': 'fabric_mcast', 'scp-server': 'scpServer', 'sftp-server': 'sftpServer', 'sla responder': 'sla_responder', 'sla sender': 'sla_sender', 'ssh': 'sshServer', 'tacacs+': 'tacacs', 'telnet': 'telnetServer', 'ethernet-link-oam': 'elo', 'port-security': 'eth_port_sec' }, 'config': { 'nve': 'nv overlay', 'vnseg_vlan': 'vn-segment-vlan-based', 'hsrp_engine': 'hsrp', 'fabric_mcast': 'fabric multicast', 'scpServer': 'scp-server', 'sftpServer': 'sftp-server', 'sla_sender': 'sla sender', 'sla_responder': 'sla responder', 'sshServer': 'ssh', 'tacacs': 'tacacs+', 'telnetServer': 'telnet', 'elo': 'ethernet-link-oam', 'eth_port_sec': 'port-security' } } if feature in feature_to_be_mapped[mode]: feature = feature_to_be_mapped[mode][feature] return feature
def __init__(self, module): self.module = module self.warnings = list() self.facts = dict() self.capabilities = get_capabilities(self.module)
def main(): argument_spec = dict( group=dict(required=True, type='str'), interface=dict(required=True), version=dict(choices=['1', '2'], default='1', required=False), priority=dict(type='str', required=False), preempt=dict(type='str', choices=['disabled', 'enabled'], required=False), vip=dict(type='str', required=False), auth_type=dict(choices=['text', 'md5'], required=False), auth_string=dict(type='str', required=False), state=dict(choices=['absent', 'present'], required=False, 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) interface = module.params['interface'].lower() group = module.params['group'] version = module.params['version'] state = module.params['state'] priority = module.params['priority'] preempt = module.params['preempt'] vip = module.params['vip'] auth_type = module.params['auth_type'] auth_full_string = module.params['auth_string'] auth_enc = '0' auth_string = None if auth_full_string: kstr = auth_full_string.split() if len(kstr) == 2: auth_enc = kstr[0] auth_string = kstr[1] elif len(kstr) == 1: auth_string = kstr[0] else: module.fail_json(msg='Inavlid auth_string') if auth_enc != '0' and auth_enc != '7': module.fail_json(msg='Inavlid auth_string, only 0 or 7 allowed') device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') intf_type = get_interface_type(interface) if (intf_type != 'ethernet' and network_api == 'cliconf'): if is_default(interface, module) == 'DNE': module.fail_json(msg='That interface does not exist yet. Create ' 'it first.', interface=interface) if intf_type == 'loopback': module.fail_json(msg="Loopback interfaces don't support HSRP.", interface=interface) mode = get_interface_mode(interface, intf_type, module) if mode == 'layer2': module.fail_json(msg='That interface is a layer2 port.\nMake it ' 'a layer 3 port first.', interface=interface) if auth_type or auth_string: if not (auth_type and auth_string): module.fail_json(msg='When using auth parameters, you need BOTH ' 'auth_type AND auth_string.') args = dict(group=group, version=version, priority=priority, preempt=preempt, vip=vip, auth_type=auth_type, auth_string=auth_string, auth_enc=auth_enc) proposed = dict((k, v) for k, v in args.items() if v is not None) existing = get_hsrp_group(group, interface, module) # This will enforce better practice with md5 and hsrp version. if proposed.get('auth_type', None) == 'md5': if proposed['version'] == '1': module.fail_json(msg="It's recommended to use HSRP v2 " "when auth_type=md5") elif not proposed.get('auth_type', None) and existing: if (proposed['version'] == '1' and existing['auth_type'] == 'md5') and state == 'present': module.fail_json(msg="Existing auth_type is md5. It's recommended " "to use HSRP v2 when using md5") commands = [] if state == 'present': delta = dict( set(proposed.items()).difference(existing.items())) if delta: command = get_commands_config_hsrp(delta, interface, args, existing) commands.extend(command) elif state == 'absent': if existing: command = get_commands_remove_hsrp(group, interface) commands.extend(command) if commands: if module.check_mode: module.exit_json(**results) else: load_config(module, commands) # validate IP if network_api == 'cliconf' and state == 'present': commands.insert(0, 'config t') body = run_commands(module, commands) validate_config(body, vip, module) results['changed'] = True if 'configure' in commands: commands.pop(0) results['commands'] = commands module.exit_json(**results)
def main(): argument_spec = dict( vrf=dict(required=True), interface=dict(type='str', required=True), state=dict(default='present', choices=['present', 'absent'], required=False), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = {'changed': False, 'commands': [], 'warnings': warnings} vrf = module.params['vrf'] interface = module.params['interface'].lower() state = module.params['state'] device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') current_vrfs = get_vrf_list(module) if vrf not in current_vrfs: warnings.append("The VRF is not present/active on the device. " "Use nxos_vrf to fix this.") intf_type = get_interface_type(interface) if (intf_type != 'ethernet' and network_api == 'cliconf'): if is_default(interface, module) == 'DNE': module.fail_json(msg="interface does not exist on switch. Verify " "switch platform or create it first with " "nxos_interface if it's a logical interface") mode = get_interface_mode(interface, intf_type, module) if mode == 'layer2': module.fail_json(msg='Ensure interface is a Layer 3 port before ' 'configuring a VRF on an interface. You can ' 'use nxos_interface') proposed = dict(interface=interface, vrf=vrf) current_vrf = get_interface_info(interface, module) existing = dict(interface=interface, vrf=current_vrf) changed = False end_state = existing if not existing['vrf']: pass elif vrf != existing['vrf'] and state == 'absent': module.fail_json(msg='The VRF you are trying to remove ' 'from the interface does not exist ' 'on that interface.', interface=interface, proposed_vrf=vrf, existing_vrf=existing['vrf']) commands = [] if existing: if state == 'absent': if existing and vrf == existing['vrf']: command = 'no vrf member {0}'.format(vrf) commands.append(command) elif state == 'present': if existing['vrf'] != vrf: command = 'vrf member {0}'.format(vrf) commands.append(command) if commands: commands.insert(0, 'interface {0}'.format(interface)) if commands: if module.check_mode: module.exit_json(changed=True, commands=commands) else: load_config(module, commands) changed = True changed_vrf = get_interface_info(interface, module) end_state = dict(interface=interface, vrf=changed_vrf) if 'configure' in commands: commands.pop(0) results['commands'] = commands results['changed'] = changed module.exit_json(**results)
def main(): spec = dict(gather_subset=dict(default=['!config'], type='list')) spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=spec, supports_check_mode=True) capabilities = get_capabilities(module) if capabilities: os_version = capabilities['device_info']['network_os_version'] os_version_major = int(os_version[0]) if os_version_major < 7 and "6.0(2)A8" not in os_version: module.fail_json( msg= "this module requires JSON structured output support on the NX-OS device" ) warnings = list() check_args(module, warnings) gather_subset = module.params['gather_subset'] runable_subsets = set() exclude_subsets = set() for subset in gather_subset: if subset == 'all': runable_subsets.update(VALID_SUBSETS) continue if subset.startswith('!'): subset = subset[1:] if subset == 'all': exclude_subsets.update(VALID_SUBSETS) continue exclude = True else: exclude = False if subset not in VALID_SUBSETS: module.fail_json(msg='Bad subset') if exclude: exclude_subsets.add(subset) else: runable_subsets.add(subset) if not runable_subsets: runable_subsets.update(VALID_SUBSETS) runable_subsets.difference_update(exclude_subsets) runable_subsets.add('default') facts = dict() facts['gather_subset'] = list(runable_subsets) instances = list() for key in runable_subsets: instances.append(FACT_SUBSETS[key](module)) for inst in instances: inst.populate() facts.update(inst.facts) warnings.extend(inst.warnings) ansible_facts = dict() for key, value in iteritems(facts): # this is to maintain capability with nxos_facts 2.1 if key.startswith('_'): ansible_facts[key[1:]] = value else: key = 'ansible_net_%s' % key ansible_facts[key] = value module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
def main(): argument_spec = dict( group=dict(required=True, type='str'), interface=dict(required=True), priority=dict(required=False, type='str'), preempt=dict(required=False, type='bool'), vip=dict(required=False, type='str'), admin_state=dict(required=False, type='str', choices=['shutdown', 'no shutdown'], default='no shutdown'), authentication=dict(required=False, type='str'), state=dict(choices=['absent', 'present'], required=False, 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} state = module.params['state'] interface = module.params['interface'].lower() group = module.params['group'] priority = module.params['priority'] preempt = module.params['preempt'] vip = module.params['vip'] authentication = module.params['authentication'] admin_state = module.params['admin_state'] device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if state == 'present' and not vip: module.fail_json(msg='the "vip" param is required when state=present') intf_type = get_interface_type(interface) if (intf_type != 'ethernet' and network_api == 'cliconf'): if is_default(interface, module) == 'DNE': module.fail_json(msg='That interface does not exist yet. Create ' 'it first.', interface=interface) if intf_type == 'loopback': module.fail_json(msg="Loopback interfaces don't support VRRP.", interface=interface) mode, name = get_interface_mode(interface, intf_type, module) if mode == 'layer2': module.fail_json(msg='That interface is a layer2 port.\nMake it ' 'a layer 3 port first.', interface=interface) args = dict(group=group, priority=priority, preempt=preempt, vip=vip, authentication=authentication, admin_state=admin_state) proposed = dict((k, v) for k, v in args.items() if v is not None) existing = get_existing_vrrp(interface, group, module, name) changed = False end_state = existing commands = [] if state == 'present': delta = dict( set(proposed.items()).difference(existing.items())) if delta: command = get_commands_config_vrrp(delta, group) commands.append(command) elif state == 'absent': if existing: commands.append(['no vrrp {0}'.format(group)]) if commands: commands.insert(0, ['interface {0}'.format(interface)]) commands = flatten_list(commands) results['commands'] = commands results['changed'] = True if not module.check_mode: load_config(module, commands) if 'configure' in commands: commands.pop(0) module.exit_json(**results)
def get_platform_id(module): info = get_capabilities(module).get('device_info', {}) return (info.get('network_os_platform', ''))
def main(): argument_spec = dict( vrf=dict(required=True), interface=dict(type='str', required=True), state=dict(default='present', choices=['present', 'absent'], required=False), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() results = {'changed': False, 'commands': [], 'warnings': warnings} vrf = module.params['vrf'] interface = module.params['interface'].lower() state = module.params['state'] device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') current_vrfs = get_vrf_list(module) if vrf not in current_vrfs: warnings.append("The VRF is not present/active on the device. " "Use nxos_vrf to fix this.") intf_type = get_interface_type(interface) if (intf_type != 'ethernet' and network_api == 'cliconf'): if is_default(interface, module) == 'DNE': module.fail_json(msg="interface does not exist on switch. Verify " "switch platform or create it first with " "nxos_interface if it's a logical interface") mode = get_interface_mode(interface, intf_type, module) if mode == 'layer2': module.fail_json(msg='Ensure interface is a Layer 3 port before ' 'configuring a VRF on an interface. You can ' 'use nxos_interface') proposed = dict(interface=interface, vrf=vrf) current_vrf = get_interface_info(interface, module) existing = dict(interface=interface, vrf=current_vrf) changed = False end_state = existing if not existing['vrf']: pass elif vrf != existing['vrf'] and state == 'absent': module.fail_json(msg='The VRF you are trying to remove ' 'from the interface does not exist ' 'on that interface.', interface=interface, proposed_vrf=vrf, existing_vrf=existing['vrf']) commands = [] if existing: if state == 'absent': if existing and vrf == existing['vrf']: command = 'no vrf member {0}'.format(vrf) commands.append(command) elif state == 'present': if existing['vrf'] != vrf: command = 'vrf member {0}'.format(vrf) commands.append(command) if commands: commands.insert(0, 'interface {0}'.format(interface)) if commands: if module.check_mode: module.exit_json(changed=True, commands=commands) else: load_config(module, commands) changed = True changed_vrf = get_interface_info(interface, module) end_state = dict(interface=interface, vrf=changed_vrf) if 'configure' in commands: commands.pop(0) results['commands'] = commands results['changed'] = changed module.exit_json(**results)
def main(): argument_spec = dict(group=dict(required=True, type='str'), interface=dict(required=True), version=dict(choices=['1', '2'], default='2', required=False), priority=dict(type='str', required=False), preempt=dict(type='str', choices=['disabled', 'enabled'], required=False), vip=dict(type='str', required=False), auth_type=dict(choices=['text', 'md5'], required=False), auth_string=dict(type='str', required=False), state=dict(choices=['absent', 'present'], required=False, 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) interface = module.params['interface'].lower() group = module.params['group'] version = module.params['version'] state = module.params['state'] priority = module.params['priority'] preempt = module.params['preempt'] vip = module.params['vip'] auth_type = module.params['auth_type'] auth_string = module.params['auth_string'] device_info = get_capabilities(module) network_api = device_info.get('network_api', 'nxapi') if state == 'present' and not vip: module.fail_json(msg='the "vip" param is required when state=present') for param in ['group', 'priority']: if module.params[param] is not None: validate_params(param, module) intf_type = get_interface_type(interface) if (intf_type != 'ethernet' and network_api == 'cliconf'): if is_default(interface, module) == 'DNE': module.fail_json(msg='That interface does not exist yet. Create ' 'it first.', interface=interface) if intf_type == 'loopback': module.fail_json(msg="Loopback interfaces don't support HSRP.", interface=interface) mode = get_interface_mode(interface, intf_type, module) if mode == 'layer2': module.fail_json(msg='That interface is a layer2 port.\nMake it ' 'a layer 3 port first.', interface=interface) if auth_type or auth_string: if not (auth_type and auth_string): module.fail_json(msg='When using auth parameters, you need BOTH ' 'auth_type AND auth_string.') args = dict(group=group, version=version, priority=priority, preempt=preempt, vip=vip, auth_type=auth_type, auth_string=auth_string) proposed = dict((k, v) for k, v in args.items() if v is not None) existing = get_hsrp_group(group, interface, module) # This will enforce better practice with md5 and hsrp version. if proposed.get('auth_type', None) == 'md5': if proposed['version'] == '1': module.fail_json(msg="It's recommended to use HSRP v2 " "when auth_type=md5") elif not proposed.get('auth_type', None) and existing: if (proposed['version'] == '1' and existing['auth_type'] == 'md5'): module.fail_json(msg="Existing auth_type is md5. It's recommended " "to use HSRP v2 when using md5") commands = [] if state == 'present': delta = dict(set(proposed.items()).difference(existing.items())) if delta: command = get_commands_config_hsrp(delta, interface, args) commands.extend(command) elif state == 'absent': if existing: command = get_commands_remove_hsrp(group, interface) commands.extend(command) if commands: if module.check_mode: module.exit_json(**results) else: load_config(module, commands) # validate IP if network_api == 'cliconf' and state == 'present': commands.insert(0, 'config t') body = run_commands(module, commands) validate_config(body, vip, module) results['changed'] = True if 'configure' in commands: commands.pop(0) results['commands'] = commands module.exit_json(**results)
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 validate_feature(module, mode='show'): '''Some features may need to be mapped due to inconsistency between how they appear from "show feature" output and how they are configured''' feature = module.params['feature'] try: info = get_capabilities(module) device_info = info.get('device_info', {}) os_version = device_info.get('network_os_version', '') except ConnectionError: os_version = '' if '8.1' in os_version: feature_to_be_mapped = { 'show': { 'nv overlay': 'nve', 'vn-segment-vlan-based': 'vnseg_vlan', 'hsrp': 'hsrp_engine', 'fabric multicast': 'fabric_mcast', 'scp-server': 'scpServer', 'sftp-server': 'sftpServer', 'sla responder': 'sla_responder', 'sla sender': 'sla_sender', 'ssh': 'sshServer', 'tacacs+': 'tacacs', 'telnet': 'telnetServer', 'ethernet-link-oam': 'elo' }, 'config': { 'nve': 'nv overlay', 'vnseg_vlan': 'vn-segment-vlan-based', 'hsrp_engine': 'hsrp', 'fabric_mcast': 'fabric multicast', 'scpServer': 'scp-server', 'sftpServer': 'sftp-server', 'sla_sender': 'sla sender', 'sla_responder': 'sla responder', 'sshServer': 'ssh', 'tacacs': 'tacacs+', 'telnetServer': 'telnet', 'elo': 'ethernet-link-oam' } } else: feature_to_be_mapped = { 'show': { 'nv overlay': 'nve', 'vn-segment-vlan-based': 'vnseg_vlan', 'hsrp': 'hsrp_engine', 'fabric multicast': 'fabric_mcast', 'scp-server': 'scpServer', 'sftp-server': 'sftpServer', 'sla responder': 'sla_responder', 'sla sender': 'sla_sender', 'ssh': 'sshServer', 'tacacs+': 'tacacs', 'telnet': 'telnetServer', 'ethernet-link-oam': 'elo', 'port-security': 'eth_port_sec' }, 'config': { 'nve': 'nv overlay', 'vnseg_vlan': 'vn-segment-vlan-based', 'hsrp_engine': 'hsrp', 'fabric_mcast': 'fabric multicast', 'scpServer': 'scp-server', 'sftpServer': 'sftp-server', 'sla_sender': 'sla sender', 'sla_responder': 'sla responder', 'sshServer': 'ssh', 'tacacs': 'tacacs+', 'telnetServer': 'telnet', 'elo': 'ethernet-link-oam', 'eth_port_sec': 'port-security' } } if feature in feature_to_be_mapped[mode]: feature = feature_to_be_mapped[mode][feature] return feature