Exemple #1
0
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
Exemple #2
0
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
Exemple #3
0
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,
                     date="2022-06-01",
                     collection_name="cisco.nxos")

    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(
        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 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)
Exemple #8
0
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)
Exemple #9
0
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 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
Exemple #11
0
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
Exemple #12
0
def get_platform_id(module):
    info = get_capabilities(module).get("device_info", {})
    return info.get("network_os_platform", "")
 def __init__(self, module):
     self.module = module
     self.warnings = list()
     self.facts = dict()
     self.capabilities = get_capabilities(self.module)
Exemple #14
0
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="Invalid auth_string")
        if auth_enc != "0" and auth_enc != "7":
            module.fail_json(msg="Invalid 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(
        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)

    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)
Exemple #16
0
def main():
    argument_spec = dict(
        vrf=dict(required=True),
        afi=dict(required=True, choices=["ipv4", "ipv6"]),
        route_target_both_auto_evpn=dict(required=False, type="bool"),
        state=dict(choices=["present", "absent"], default="present"),
        route_targets=dict(
            type="list",
            elements="dict",
            options=dict(
                rt=dict(type="str", required=True),
                direction=dict(
                    choices=["import", "export", "both"], default="both"
                ),
                state=dict(choices=["present", "absent"], default="present"),
            ),
        ),
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(
        argument_spec=argument_spec, supports_check_mode=True
    )

    warnings = list()

    result = {"changed": False, "warnings": warnings}

    config_text = get_config(module)
    config = NetworkConfig(indent=2, contents=config_text)

    path = [
        "vrf context %s" % module.params["vrf"],
        "address-family %s unicast" % module.params["afi"],
    ]

    try:
        current = config.get_block_config(path)
    except ValueError:
        current = None

    commands = list()
    if current and module.params["state"] == "absent":
        commands.append("no address-family %s unicast" % module.params["afi"])

    elif module.params["state"] == "present":
        rt_commands = list()

        if not current:
            commands.append("address-family %s unicast" % module.params["afi"])
            current = ""

        have_auto_evpn = "route-target both auto evpn" in current
        if module.params["route_target_both_auto_evpn"] is not None:
            want_auto_evpn = bool(module.params["route_target_both_auto_evpn"])
            if want_auto_evpn and not have_auto_evpn:
                commands.append("route-target both auto evpn")
            elif have_auto_evpn and not want_auto_evpn:
                commands.append("no route-target both auto evpn")

        if module.params["route_targets"] is not None:
            for rt in module.params["route_targets"]:
                if rt.get("direction") == "both" or not rt.get("direction"):
                    platform = get_capabilities(module)["device_info"][
                        "network_os_platform"
                    ]
                    if platform.startswith("N9K") and rt.get("rt") == "auto":
                        rt_commands = match_current_rt(
                            rt, "both", current, rt_commands
                        )
                    else:
                        rt_commands = match_current_rt(
                            rt, "import", current, rt_commands
                        )
                        rt_commands = match_current_rt(
                            rt, "export", current, rt_commands
                        )
                else:
                    rt_commands = match_current_rt(
                        rt, rt.get("direction"), current, rt_commands
                    )

        if rt_commands:
            commands.extend(rt_commands)

        if commands and current:
            commands.insert(
                0, "address-family %s unicast" % module.params["afi"]
            )

    if commands:
        commands.insert(0, "vrf context %s" % module.params["vrf"])
        if not module.check_mode:
            load_config(module, commands)
        result["changed"] = True

    result["commands"] = commands

    module.exit_json(**result)
def get_platform_id(module):
    info = get_capabilities(module).get('device_info', {})
    return (info.get('network_os_platform', ''))
Exemple #18
0
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 = normalize_interface(module.params["interface"])
    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")

    current_vrf = get_interface_info(interface, module)
    existing = dict(interface=interface, vrf=current_vrf)
    changed = False

    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
            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='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='Invalid auth_string')
        if auth_enc != '0' and auth_enc != '7':
            module.fail_json(msg='Invalid 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)
Exemple #20
0
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 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')

    current_vrf = get_interface_info(interface, module)
    existing = dict(interface=interface, vrf=current_vrf)
    changed = False

    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
            if 'configure' in commands:
                commands.pop(0)

    results['commands'] = commands
    results['changed'] = changed

    module.exit_json(**results)
Exemple #22
0
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)

    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)