Beispiel #1
0
def main():
    argument_spec = dict(
        server_type=dict(choices=['radius', 'tacacs'], required=True),
        address=dict(type='str', required=True),
        key=dict(type='str'),
        encrypt_type=dict(type='str', choices=['0', '7']),
        host_timeout=dict(type='str'),
        auth_port=dict(type='str'),
        acct_port=dict(type='str'),
        tacacs_port=dict(type='str'),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    server_type = module.params['server_type']
    address = module.params['address']
    key = module.params['key']
    encrypt_type = module.params['encrypt_type']
    host_timeout = module.params['host_timeout']
    auth_port = module.params['auth_port']
    acct_port = module.params['acct_port']
    tacacs_port = module.params['tacacs_port']
    state = module.params['state']

    args = dict(server_type=server_type,
                address=address,
                key=key,
                encrypt_type=encrypt_type,
                host_timeout=host_timeout,
                auth_port=auth_port,
                acct_port=acct_port,
                tacacs_port=tacacs_port)

    proposed = dict((k, v) for k, v in args.items() if v is not None)
    changed = False

    if encrypt_type and not key:
        module.fail_json(msg='encrypt_type must be used with key')

    if tacacs_port and server_type != 'tacacs':
        module.fail_json(
            msg='tacacs_port can only be used with server_type=tacacs')

    if (auth_port or acct_port) and server_type != 'radius':
        module.fail_json(msg='auth_port and acct_port can only be used'
                         'when server_type=radius')

    existing = get_aaa_host_info(module, server_type, address)
    end_state = existing

    commands = []
    delta = {}
    if state == 'present':
        if not existing:
            delta = proposed
        else:
            for key, value in proposed.items():
                if key == 'encrypt_type':
                    delta[key] = value
                if value != existing.get(key):
                    if value != 'default' or existing.get(key):
                        delta[key] = value

        command = config_aaa_host(server_type, address, delta, existing)
        if command:
            commands.append(command)

    elif state == 'absent':
        intersect = dict(set(proposed.items()).intersection(existing.items()))
        if intersect.get('address') and intersect.get('server_type'):
            command = 'no {0}-server host {1}'.format(
                intersect.get('server_type'), intersect.get('address'))
            commands.append(command)

    cmds = flatten_list(commands)
    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            changed = True
            load_config(module, cmds)
            end_state = get_aaa_host_info(module, server_type, address)

    results = {}
    results['proposed'] = proposed
    results['existing'] = existing
    results['updates'] = cmds
    results['changed'] = changed
    results['warnings'] = warnings
    results['end_state'] = end_state

    module.exit_json(**results)
Beispiel #2
0
def main():
    argument_spec = dict(
        interface=dict(type="str", required=True),
        sparse=dict(type="bool", default=False),
        dr_prio=dict(type="str"),
        hello_auth_key=dict(type="str"),
        hello_interval=dict(type="int"),
        jp_policy_out=dict(type="str"),
        jp_policy_in=dict(type="str"),
        jp_type_out=dict(type="str", choices=["prefix", "routemap"]),
        jp_type_in=dict(type="str", choices=["prefix", "routemap"]),
        bfd=dict(type="str", choices=["enable", "disable", "default"]),
        border=dict(type="bool", default=False),
        neighbor_policy=dict(type="str"),
        neighbor_type=dict(type="str", choices=["prefix", "routemap"]),
        state=dict(
            type="str",
            default="present",
            choices=["absent", "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"]
    jp_type_in = module.params["jp_type_in"]
    jp_type_out = module.params["jp_type_out"]
    jp_policy_in = module.params["jp_policy_in"]
    jp_policy_out = module.params["jp_policy_out"]
    neighbor_policy = module.params["neighbor_policy"]
    neighbor_type = module.params["neighbor_type"]

    intf_type = get_interface_type(interface)
    if get_interface_mode(interface, intf_type, module) == "layer2":
        module.fail_json(msg="this module only works on Layer 3 interfaces.")

    if jp_policy_in:
        if not jp_type_in:
            module.fail_json(
                msg="jp_type_in required when using jp_policy_in.")
    if jp_policy_out:
        if not jp_type_out:
            module.fail_json(
                msg="jp_type_out required when using jp_policy_out.")
    if neighbor_policy:
        if not neighbor_type:
            module.fail_json(
                msg="neighbor_type required when using neighbor_policy.")

    get_existing = get_pim_interface(module, interface)
    existing, jp_bidir, isauth = local_existing(get_existing)

    args = PARAM_TO_COMMAND_KEYMAP.keys()
    proposed = dict((k, v) for k, v in module.params.items()
                    if v is not None and k in args)
    normalize_proposed_values(proposed)

    delta = dict(set(proposed.items()).difference(existing.items()))

    commands = []
    if state == "present":
        if delta:
            command = config_pim_interface(delta, existing, jp_bidir, isauth)
            if command:
                commands.append(command)
    elif state == "default" or state == "absent":
        defaults = config_pim_interface_defaults(existing, jp_bidir, isauth)
        if defaults:
            commands.append(defaults)

    if commands:
        commands.insert(0, ["interface {0}".format(interface)])

    cmds = flatten_list(commands)
    if cmds:
        results["changed"] = True
        if not module.check_mode:
            load_config(module, cmds)
        if "configure" in cmds:
            cmds.pop(0)

    results["commands"] = cmds

    module.exit_json(**results)
Beispiel #3
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        group=dict(type="str"),
        mode=dict(
            required=False,
            choices=["on", "active", "passive"],
            default="on",
            type="str",
        ),
        min_links=dict(required=False, default=None, type="int"),
        members=dict(required=False, default=None, type="list"),
        force=dict(required=False, default=False, type="bool"),
        state=dict(
            required=False, choices=["absent", "present"], default="present"
        ),
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec["group"] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type="list", elements="dict", options=aggregate_spec),
        purge=dict(default=False, type="bool"),
    )

    argument_spec.update(element_spec)
    argument_spec.update(nxos_argument_spec)

    required_one_of = [["group", "aggregate"]]
    mutually_exclusive = [["group", "aggregate"]]
    module = AnsibleModule(
        argument_spec=argument_spec,
        required_one_of=required_one_of,
        mutually_exclusive=mutually_exclusive,
        supports_check_mode=True,
    )

    warnings = list()
    result = {"changed": False}
    if warnings:
        result["warnings"] = warnings

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)
    result["commands"] = commands

    if commands:
        if not module.check_mode:
            resp = load_config(module, commands, True)
            if resp:
                for item in resp:
                    if item:
                        if isinstance(item, dict):
                            err_str = item["clierror"]
                        else:
                            err_str = item
                        if "cannot add" in err_str.lower():
                            module.fail_json(msg=err_str)
        result["changed"] = True

    module.exit_json(**result)
Beispiel #4
0
def main():
    argument_spec = dict(
        server=dict(type="str"),
        peer=dict(type="str"),
        key_id=dict(type="str"),
        prefer=dict(type="str", choices=["enabled", "disabled"]),
        vrf_name=dict(type="str"),
        source_addr=dict(type="str"),
        source_int=dict(type="str"),
        state=dict(choices=["absent", "present"], default="present"),
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(
        argument_spec=argument_spec,
        mutually_exclusive=[["server", "peer"], ["source_addr", "source_int"]],
        supports_check_mode=True,
    )

    warnings = list()

    server = module.params["server"] or None
    peer = module.params["peer"] or None
    key_id = module.params["key_id"]
    prefer = module.params["prefer"]
    vrf_name = module.params["vrf_name"]
    source_addr = module.params["source_addr"]
    source_int = module.params["source_int"]
    state = module.params["state"]

    if source_int is not None:
        source_int = source_int.lower()

    if server:
        peer_type = "server"
        address = server
    elif peer:
        peer_type = "peer"
        address = peer
    else:
        peer_type = None
        address = None

    source_type = None
    source = None
    if source_addr:
        source_type = "source"
        source = source_addr
    elif source_int:
        source_type = "source-interface"
        source = source_int

    if key_id or vrf_name or prefer:
        if not server and not peer:
            module.fail_json(msg="Please supply the server or peer parameter")

    args = dict(
        peer_type=peer_type,
        address=address,
        key_id=key_id,
        prefer=prefer,
        vrf_name=vrf_name,
        source_type=source_type,
        source=source,
    )

    proposed = dict((k, v) for k, v in args.items() if v is not None)

    existing, peer_server_list = get_ntp_existing(address, peer_type, module)

    end_state = existing
    changed = False
    commands = []

    if state == "present":
        delta = dict(set(proposed.items()).difference(existing.items()))
        if delta.get("key_id") and delta.get("key_id") == "default":
            if not existing.get("key_id"):
                delta.pop("key_id")
        if delta:
            command = config_ntp(delta, existing)
            if command:
                commands.append(command)

    elif state == "absent":
        if existing.get("peer_type") and existing.get("address"):
            command = "no ntp {0} {1}".format(existing["peer_type"],
                                              existing["address"])
            if command:
                commands.append([command])

        existing_source_type = existing.get("source_type")
        existing_source = existing.get("source")
        proposed_source_type = proposed.get("source_type")
        proposed_source = proposed.get("source")

        if proposed_source_type:
            if proposed_source_type == existing_source_type:
                if proposed_source == existing_source:
                    command = "no ntp {0} {1}".format(existing_source_type,
                                                      existing_source)
                    if command:
                        commands.append([command])

    cmds = flatten_list(commands)
    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            changed = True
            load_config(module, cmds)
            end_state = get_ntp_existing(address, peer_type, module)[0]
            if "configure" in cmds:
                cmds.pop(0)

    results = {}
    results["proposed"] = proposed
    results["existing"] = existing
    results["updates"] = cmds
    results["changed"] = changed
    results["warnings"] = warnings
    results["end_state"] = end_state
    results["peer_server_list"] = peer_server_list

    module.exit_json(**results)
def main():
    argument_spec = dict(
        mode=dict(choices=['enabled', 'disabled', 'aggressive'],
                  required=True),
        interface=dict(type='str', required=True),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    interface = module.params['interface'].lower()
    mode = module.params['mode']
    state = module.params['state']

    proposed = dict(mode=mode)
    existing, mode_str = get_udld_interface(module, interface)
    end_state = existing

    delta = dict(set(proposed.items()).difference(existing.items()))

    changed = False
    commands = []
    cmds = []
    if state == 'present':
        if delta:
            command = get_commands_config_udld_interface1(delta, interface,
                                                          module, existing)
            commands.append(command)
            cmds = flatten_list(commands)
            if module.check_mode:
                module.exit_json(changed=True, commands=cmds)
            else:
                changed = True
                load_config(module, cmds)

            if delta['mode'] == 'enabled' or delta['mode'] == 'disabled':
                commands = []
                command = get_commands_config_udld_interface2(delta, interface,
                                                              module, existing)
                commands.append(command)
                cmds = flatten_list(commands)
                if module.check_mode:
                    module.exit_json(changed=True, commands=cmds)
                else:
                    load_config(module, cmds)

    else:
        common = set(proposed.items()).intersection(existing.items())
        if common:
            command = get_commands_remove_udld_interface(
                dict(common), interface, module, existing
            )
            cmds = flatten_list(commands)
            if module.check_mode:
                module.exit_json(changed=True, commands=cmds)
            else:
                changed = True
                load_config(module, cmds)

    if not module.check_mode:
        end_state, mode_str = get_udld_interface(module, interface)
        if 'configure' in cmds:
            cmds.pop(0)

    results = {}
    results['proposed'] = proposed
    results['existing'] = existing
    results['end_state'] = end_state
    results['updates'] = cmds
    results['changed'] = changed
    results['warnings'] = warnings

    module.exit_json(**results)
def main():
    """ main entry point for module execution
    """
    neighbors_spec = dict(host=dict(), port=dict())

    element_spec = dict(
        name=dict(aliases=["interface"]),
        admin_state=dict(default="up", choices=["up", "down"]),
        description=dict(),
        speed=dict(),
        mode=dict(choices=["layer2", "layer3"]),
        mtu=dict(),
        duplex=dict(choices=["full", "half", "auto"]),
        interface_type=dict(choices=["loopback", "portchannel", "svi", "nve"]),
        ip_forward=dict(choices=["enable", "disable"]),
        fabric_forwarding_anycast_gateway=dict(type="bool"),
        tx_rate=dict(),
        rx_rate=dict(),
        neighbors=dict(type="list", elements="dict", options=neighbors_spec),
        delay=dict(default=10, type="int"),
        state=dict(choices=["absent", "present", "default"],
                   default="present"),
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec["name"] = 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,
        mutually_exclusive=[["name", "interface_type"]],
    ))

    argument_spec.update(element_spec)
    argument_spec.update(nxos_argument_spec)

    required_one_of = [["name", "aggregate", "interface_type"]]
    mutually_exclusive = [["name", "aggregate"], ["name", "interface_type"]]

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_one_of=required_one_of,
        mutually_exclusive=mutually_exclusive,
        supports_check_mode=True,
    )
    warnings = list()

    result = {"changed": False}
    if warnings:
        result["warnings"] = warnings

    want = map_params_to_obj(module)
    have = map_config_to_obj(want, module)

    commands = []
    commands1, commands2 = map_obj_to_commands((want, have), module)
    commands.extend(commands1)

    if commands:
        if not module.check_mode:
            load_config(module, commands)
            result["changed"] = True
            # if the mode changes from L2 to L3, the admin state
            # seems to change after the API call, so adding a second API
            # call to ensure it's in the desired state.
            if commands2:
                load_config(module, commands2)
                commands.extend(commands2)
            commands = [cmd for cmd in commands if cmd != "configure"]
    result["commands"] = commands

    if result["changed"]:
        failed_conditions = check_declarative_intent_params(module, want)

        if failed_conditions:
            msg = "One or more conditional statements have not been satisfied"
            module.fail_json(msg=msg, failed_conditions=failed_conditions)

    module.exit_json(**result)
def main():
    argument_spec = dict(
        action=dict(
            required=True,
            choices=['create', 'add', 'compare', 'delete', 'delete_all']),
        snapshot_name=dict(type='str'),
        description=dict(type='str'),
        snapshot1=dict(type='str'),
        snapshot2=dict(type='str'),
        compare_option=dict(choices=['summary', 'ipv4routes', 'ipv6routes']),
        comparison_results_file=dict(type='str'),
        section=dict(type='str'),
        show_command=dict(type='str'),
        row_id=dict(type='str'),
        element_key1=dict(type='str'),
        element_key2=dict(type='str'),
        save_snapshot_locally=dict(type='bool', default=False),
        path=dict(type='str', default='./'))

    argument_spec.update(nxos_argument_spec)

    required_if = [("action", "compare",
                    ["snapshot1", "snapshot2", "comparison_results_file"]),
                   ("action", "create", ["snapshot_name", "description"]),
                   ("action", "add",
                    ["section", "show_command", "row_id", "element_key1"]),
                   ("action", "delete", ["snapshot_name"])]

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

    action = module.params['action']
    comparison_results_file = module.params['comparison_results_file']

    if not os.path.isdir(module.params['path']):
        module.fail_json(msg='{0} is not a valid directory name.'.format(
            module.params['path']))

    existing_snapshots = invoke('get_existing', module)
    action_results = invoke('action_%s' % action, module, existing_snapshots)

    result = {'changed': False, 'commands': []}

    if not module.check_mode:
        if action == 'compare':
            result['commands'] = []

            if module.params['path'] and comparison_results_file:
                snapshot1 = module.params['snapshot1']
                snapshot2 = module.params['snapshot2']
                compare_option = module.params['compare_option']
                command = 'show snapshot compare {0} {1}'.format(
                    snapshot1, snapshot2)
                if compare_option:
                    command += ' {0}'.format(compare_option)
                content = execute_show_command(command, module)[0]
                if content:
                    write_on_file(content, comparison_results_file, module)
        else:
            if action_results:
                load_config(module, action_results)
                result['commands'] = action_results
                result['changed'] = True

            if action == 'create' and module.params['path'] and module.params[
                    'save_snapshot_locally']:
                command = 'show snapshot dump {0} | json'.format(
                    module.params['snapshot_name'])
                content = execute_show_command(command, module)[0]
                if content:
                    write_on_file(str(content), module.params['snapshot_name'],
                                  module)

    module.exit_json(**result)
Beispiel #8
0
def main():
    argument_spec = dict(vrf=dict(required=False,
                                  type='str',
                                  default='default'),
                         ospf=dict(required=True, type='str'),
                         router_id=dict(required=False, type='str'),
                         default_metric=dict(required=False, type='str'),
                         log_adjacency=dict(
                             required=False,
                             type='str',
                             choices=['log', 'detail', 'default']),
                         timer_throttle_lsa_start=dict(required=False,
                                                       type='str'),
                         timer_throttle_lsa_hold=dict(required=False,
                                                      type='str'),
                         timer_throttle_lsa_max=dict(required=False,
                                                     type='str'),
                         timer_throttle_spf_start=dict(required=False,
                                                       type='str'),
                         timer_throttle_spf_hold=dict(required=False,
                                                      type='str'),
                         timer_throttle_spf_max=dict(required=False,
                                                     type='str'),
                         auto_cost=dict(required=False, type='str'),
                         bfd=dict(required=False,
                                  type='str',
                                  choices=['enable', 'disable']),
                         passive_interface=dict(required=False, type='bool'),
                         state=dict(choices=['present', 'absent'],
                                    default='present',
                                    required=False))

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    result = dict(changed=False, commands=[], warnings=warnings)

    state = module.params['state']
    args = PARAM_TO_COMMAND_KEYMAP.keys()
    existing = get_existing(module, args)
    proposed_args = dict((k, v) for k, v in module.params.items()
                         if v is not None and k in args)

    proposed = {}
    for key, value in proposed_args.items():
        if key != 'interface':
            if str(value).lower() == 'true':
                value = True
            elif str(value).lower() == 'false':
                value = False
            elif str(value).lower() == 'default':
                value = PARAM_TO_DEFAULT_KEYMAP.get(key)
                if value is None:
                    value = 'default'
            if existing.get(key) != value:
                proposed[key] = value

    candidate = CustomNetworkConfig(indent=3)
    if state == 'present':
        state_present(module, existing, proposed, candidate)
    if state == 'absent' and existing:
        state_absent(module, existing, proposed, candidate)

    if candidate:
        candidate = candidate.items_text()
        result['commands'] = candidate
        if not module.check_mode:
            load_config(module, candidate)
            result['changed'] = True
    module.exit_json(**result)
Beispiel #9
0
def main():
    argument_spec = dict(
        key_id=dict(type="str"),
        md5string=dict(type="str"),
        auth_type=dict(choices=["text", "encrypt"], default="text"),
        trusted_key=dict(choices=["true", "false"], default="false"),
        authentication=dict(choices=["on", "off"]),
        state=dict(choices=["absent", "present"], default="present"),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    key_id = module.params["key_id"]
    md5string = module.params["md5string"]
    auth_type = module.params["auth_type"]
    trusted_key = module.params["trusted_key"]
    authentication = module.params["authentication"]
    state = module.params["state"]

    if key_id:
        if not trusted_key and not md5string:
            module.fail_json(msg="trusted_key or md5string MUST be specified")

    args = dict(
        key_id=key_id,
        md5string=md5string,
        auth_type=auth_type,
        trusted_key=trusted_key,
        authentication=authentication,
    )

    changed = False
    proposed = dict((k, v) for k, v in args.items() if v is not None)

    existing = get_ntp_auth_info(key_id, module)
    end_state = existing

    delta = dict(set(proposed.items()).difference(existing.items()))

    commands = []
    if state == "present":
        if delta:
            command = set_ntp_auth_key(
                key_id,
                md5string,
                delta.get("auth_type"),
                delta.get("trusted_key"),
                delta.get("authentication"),
            )
            if command:
                commands.append(command)
    elif state == "absent":
        auth_toggle = None
        if existing.get("authentication") == "on":
            auth_toggle = True
        if not existing.get("key_id"):
            key_id = None
        command = remove_ntp_auth_key(key_id, md5string, auth_type,
                                      trusted_key, auth_toggle)
        if command:
            commands.append(command)

    cmds = flatten_list(commands)
    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            load_config(module, cmds)
            end_state = get_ntp_auth_info(key_id, module)
            delta = dict(set(end_state.items()).difference(existing.items()))
            if delta or (len(existing) != len(end_state)):
                changed = True
            if "configure" in cmds:
                cmds.pop(0)

    results = {}
    results["proposed"] = proposed
    results["existing"] = existing
    results["updates"] = cmds
    results["changed"] = changed
    results["warnings"] = warnings
    results["end_state"] = end_state

    module.exit_json(**results)
Beispiel #10
0
def main():
    """ main entry point for module execution
    """
    backup_spec = dict(filename=dict(), dir_path=dict(type="path"))
    argument_spec = dict(
        src=dict(type="path"),
        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),
        backup_options=dict(type="dict", options=backup_spec),
        save_when=dict(choices=["always", "never", "modified", "changed"],
                       default="never"),
        diff_against=dict(choices=["running", "startup", "intended"]),
        diff_ignore_lines=dict(type="list"),
    )

    argument_spec.update(nxos_argument_spec)

    mutually_exclusive = [("lines", "src", "replace_src"), ("parents", "src")]

    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()

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

    config = None

    diff_ignore_lines = module.params["diff_ignore_lines"]
    path = module.params["parents"]
    connection = get_connection(module)
    contents = None
    flags = ["all"] if module.params["defaults"] else []
    replace_src = module.params["replace_src"]
    if 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, flags=flags)
        config = NetworkConfig(indent=2, contents=contents)
        if module.params["backup"]:
            result["__backup__"] = contents

    if any((module.params["src"], module.params["lines"], replace_src)):
        match = module.params["match"]
        replace = module.params["replace"]

        commit = not module.check_mode
        candidate = get_candidate(module)
        running = get_running_config(module, contents, flags=flags)
        if replace_src:
            commands = candidate.split("\n")
            result["commands"] = result["updates"] = commands
            if commit:
                load_config(module, commands, replace=replace_src)

            result["changed"] = True
        else:
            try:
                response = connection.get_diff(
                    candidate=candidate,
                    running=running,
                    diff_match=match,
                    diff_ignore_lines=diff_ignore_lines,
                    path=path,
                    diff_replace=replace,
                )
            except ConnectionError as exc:
                module.fail_json(
                    msg=to_text(exc, errors="surrogate_then_replace"))

            config_diff = response["config_diff"]
            if config_diff:
                commands = config_diff.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 commit:
                    load_config(module, commands, replace=replace_src)

                result["changed"] = True

    running_config = module.params["running_config"]
    startup_config = None

    if module.params["save_when"] == "always":
        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=2,
                                       contents=output[0],
                                       ignore_lines=diff_ignore_lines)
        startup_config = NetworkConfig(indent=2,
                                       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=2,
                                       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 = startup_config.config_text

        elif module.params["diff_against"] == "intended":
            contents = module.params["intended_config"]

        if contents is not None:
            base_config = NetworkConfig(indent=2,
                                        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)
Beispiel #11
0
def main():
    argument_spec = dict(
        mode=dict(choices=["enabled", "disabled", "aggressive"],
                  required=True),
        interface=dict(type="str", required=True),
        state=dict(choices=["absent", "present"], default="present"),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    interface = module.params["interface"].lower()
    mode = module.params["mode"]
    state = module.params["state"]

    proposed = dict(mode=mode)
    existing, mode_str = get_udld_interface(module, interface)
    end_state = existing

    delta = dict(set(proposed.items()).difference(existing.items()))

    changed = False
    commands = []
    cmds = []
    if state == "present":
        if delta:
            command = get_commands_config_udld_interface1(
                delta, interface, module, existing)
            commands.append(command)
            cmds = flatten_list(commands)
            if module.check_mode:
                module.exit_json(changed=True, commands=cmds)
            else:
                changed = True
                load_config(module, cmds)

            if delta["mode"] == "enabled" or delta["mode"] == "disabled":
                commands = []
                command = get_commands_config_udld_interface2(
                    delta, interface, module, existing)
                commands.append(command)
                cmds = flatten_list(commands)
                if module.check_mode:
                    module.exit_json(changed=True, commands=cmds)
                else:
                    load_config(module, cmds)

    else:
        common = set(proposed.items()).intersection(existing.items())
        if common:
            command = get_commands_remove_udld_interface(
                dict(common), interface, module, existing)
            cmds = flatten_list(commands)
            if module.check_mode:
                module.exit_json(changed=True, commands=cmds)
            else:
                changed = True
                load_config(module, cmds)

    if not module.check_mode:
        end_state, mode_str = get_udld_interface(module, interface)
        if "configure" in cmds:
            cmds.pop(0)

    results = {}
    results["proposed"] = proposed
    results["existing"] = existing
    results["end_state"] = end_state
    results["updates"] = cmds
    results["changed"] = changed
    results["warnings"] = warnings

    module.exit_json(**results)
Beispiel #12
0
def main():
    argument_spec = dict(
        snmp_host=dict(required=True, type="str"),
        community=dict(type="str"),
        udp=dict(type="str", default="162"),
        version=dict(choices=["v1", "v2c", "v3"]),
        src_intf=dict(type="str"),
        v3=dict(choices=["noauth", "auth", "priv"]),
        vrf_filter=dict(type="str"),
        vrf=dict(type="str"),
        snmp_type=dict(choices=["trap", "inform"]),
        state=dict(choices=["absent", "present"], default="present"),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    results = {"changed": False, "commands": [], "warnings": warnings}

    snmp_host = module.params["snmp_host"]
    community = module.params["community"]
    udp = module.params["udp"]
    version = module.params["version"]
    src_intf = module.params["src_intf"]
    v3 = module.params["v3"]
    vrf_filter = module.params["vrf_filter"]
    vrf = module.params["vrf"]
    snmp_type = module.params["snmp_type"]
    state = module.params["state"]

    existing = get_snmp_host(snmp_host, udp, module)

    if version is None:
        if existing:
            version = existing.get("version")
        else:
            version = "v1"

    if snmp_type is None:
        if existing:
            snmp_type = existing.get("snmp_type")
        else:
            snmp_type = "trap"

    if v3 is None:
        if version == "v3" and existing:
            v3 = existing.get("v3")

    if snmp_type == "inform" and version == "v1":
        module.fail_json(msg="inform requires snmp v2c or v3")

    if (version == "v1" or version == "v2c") and v3:
        module.fail_json(msg='param: "v3" should not be used when '
                         "using version v1 or v2c")

    if not any([vrf_filter, vrf, src_intf]):
        if not all([snmp_type, version, community, udp]):
            module.fail_json(msg="when not configuring options like "
                             "vrf_filter, vrf, and src_intf,"
                             "the following params are required: "
                             "type, version, community")

    if version == "v3" and v3 is None:
        module.fail_json(msg="when using version=v3, the param v3 "
                         "(options: auth, noauth, priv) is also required")

    # existing returns the list of vrfs configured for a given host
    # checking to see if the proposed is in the list
    store = existing.get("vrf_filter")
    if existing and store:
        if vrf_filter not in existing["vrf_filter"]:
            existing["vrf_filter"] = None
        else:
            existing["vrf_filter"] = vrf_filter
    commands = []

    args = dict(
        community=community,
        snmp_host=snmp_host,
        udp=udp,
        version=version,
        src_intf=src_intf,
        vrf_filter=vrf_filter,
        v3=v3,
        vrf=vrf,
        snmp_type=snmp_type,
    )
    proposed = dict((k, v) for k, v in args.items() if v is not None)

    if state == "absent" and existing:
        if proposed.get("community"):
            commands.append(remove_snmp_host(snmp_host, udp, existing))
        else:
            if proposed.get("src_intf"):
                commands.append(remove_src(snmp_host, udp, proposed, existing))
            if proposed.get("vrf"):
                commands.append(remove_vrf(snmp_host, udp, proposed, existing))
            if proposed.get("vrf_filter"):
                commands.append(
                    remove_filter(snmp_host, udp, proposed, existing))

    elif state == "present":
        delta = dict(set(proposed.items()).difference(existing.items()))
        if delta:
            command = config_snmp_host(delta, udp, proposed, existing, module)
            commands.append(command)

    cmds = flatten_list(commands)
    if cmds:
        results["changed"] = True
        if not module.check_mode:
            load_config(module, cmds)

        if "configure" in cmds:
            cmds.pop(0)
        results["commands"] = cmds

    module.exit_json(**results)
def main():
    argument_spec = dict(
        asn=dict(required=True, type="str"),
        vrf=dict(required=False, type="str", default="default"),
        safi=dict(required=True,
                  type="str",
                  choices=["unicast", "multicast", "evpn"]),
        afi=dict(
            required=True,
            type="str",
            choices=["ipv4", "ipv6", "vpnv4", "vpnv6", "l2vpn"],
        ),
        additional_paths_install=dict(required=False, type="bool"),
        additional_paths_receive=dict(required=False, type="bool"),
        additional_paths_selection=dict(required=False, type="str"),
        additional_paths_send=dict(required=False, type="bool"),
        advertise_l2vpn_evpn=dict(required=False, type="bool"),
        client_to_client=dict(required=False, type="bool"),
        dampen_igp_metric=dict(required=False, type="str"),
        dampening_state=dict(required=False, type="bool"),
        dampening_half_time=dict(required=False, type="str"),
        dampening_max_suppress_time=dict(required=False, type="str"),
        dampening_reuse_time=dict(required=False, type="str"),
        dampening_routemap=dict(required=False, type="str"),
        dampening_suppress_time=dict(required=False, type="str"),
        default_information_originate=dict(required=False, type="bool"),
        default_metric=dict(required=False, type="str"),
        distance_ebgp=dict(required=False, type="str"),
        distance_ibgp=dict(required=False, type="str"),
        distance_local=dict(required=False, type="str"),
        inject_map=dict(required=False, type="list", elements="list"),
        maximum_paths=dict(required=False, type="str"),
        maximum_paths_ibgp=dict(required=False, type="str"),
        networks=dict(required=False, type="list", elements="list"),
        next_hop_route_map=dict(required=False, type="str"),
        redistribute=dict(required=False, type="list", elements="list"),
        suppress_inactive=dict(required=False, type="bool"),
        table_map=dict(required=False, type="str"),
        table_map_filter=dict(required=False, type="bool"),
        state=dict(choices=["present", "absent"],
                   default="present",
                   required=False),
    )

    argument_spec.update(nxos_argument_spec)

    mutually_exclusive = [
        ("dampening_state", "dampening_routemap"),
        ("dampening_state", "dampening_half_time"),
        ("dampening_state", "dampening_suppress_time"),
        ("dampening_state", "dampening_reuse_time"),
        ("dampening_state", "dampening_max_suppress_time"),
        ("dampening_routemap", "dampening_half_time"),
        ("dampening_routemap", "dampening_suppress_time"),
        ("dampening_routemap", "dampening_reuse_time"),
        ("dampening_routemap", "dampening_max_suppress_time"),
    ]

    module = AnsibleModule(
        argument_spec=argument_spec,
        mutually_exclusive=mutually_exclusive,
        required_together=[
            DAMPENING_PARAMS,
            ["distance_ibgp", "distance_ebgp", "distance_local"],
        ],
        supports_check_mode=True,
    )

    warnings = list()
    result = dict(changed=False, warnings=warnings)

    state = module.params["state"]

    if module.params["advertise_l2vpn_evpn"]:
        if module.params["vrf"] == "default":
            module.fail_json(
                msg="It is not possible to advertise L2VPN "
                "EVPN in the default VRF. Please specify "
                "another one.",
                vrf=module.params["vrf"],
            )

    if module.params["table_map_filter"] and not module.params["table_map"]:
        module.fail_json(msg="table_map param is needed when using"
                         " table_map_filter filter.")

    args = PARAM_TO_COMMAND_KEYMAP.keys()
    existing = get_existing(module, args, warnings)

    if existing.get("asn") and state == "present":
        if existing.get("asn") != module.params["asn"]:
            module.fail_json(
                msg="Another BGP ASN already exists.",
                proposed_asn=module.params["asn"],
                existing_asn=existing.get("asn"),
            )

    proposed_args = dict((k, v) for k, v in module.params.items()
                         if v is not None and k in args)

    for arg in ["networks", "inject_map", "redistribute"]:
        if proposed_args.get(arg):
            if proposed_args[arg][0] == "default":
                proposed_args[arg] = "default"

    proposed = {}
    for key, value in proposed_args.items():
        if key not in ["asn", "vrf"]:
            if str(value).lower() == "default":
                value = PARAM_TO_DEFAULT_KEYMAP.get(key, "default")
            if existing.get(key) != value:
                proposed[key] = value

    candidate = CustomNetworkConfig(indent=3)
    if state == "present":
        state_present(module, existing, proposed, candidate)
    elif state == "absent" and existing:
        state_absent(module, candidate)

    if candidate:
        candidate = candidate.items_text()
        if not module.check_mode:
            load_config(module, candidate)
        result["changed"] = True
        result["commands"] = candidate
    else:
        result["commands"] = []

    module.exit_json(**result)
def main():
    element_spec = dict(
        name=dict(required=True, type="str"),
        pwwn=dict(type="str"),
        remove=dict(type="bool", default=False),
    )

    element_spec_rename = dict(
        old_name=dict(required=True, type="str"),
        new_name=dict(required=True, type="str"),
    )

    argument_spec = dict(
        distribute=dict(type="bool"),
        mode=dict(type="str", choices=["enhanced", "basic"]),
        da=dict(type="list", elements="dict", options=element_spec),
        rename=dict(type="list", elements="dict", options=element_spec_rename),
    )

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

    warnings = list()
    messages = list()
    commands_to_execute = list()
    result = {"changed": False}

    distribute = module.params["distribute"]
    mode = module.params["mode"]
    da = module.params["da"]
    rename = module.params["rename"]

    # Step 0.0: Validate syntax of name and pwwn
    #       Also validate syntax of rename arguments
    if da is not None:
        for eachdict in da:
            name = eachdict["name"]
            pwwn = eachdict["pwwn"]
            remove = eachdict["remove"]
            if pwwn is not None:
                pwwn = pwwn.lower()
            if not remove:
                if pwwn is None:
                    module.fail_json(
                        msg="This device alias name " + str(name) +
                        " which needs to be added, does not have pwwn specified. Please specify a valid pwwn"
                    )
                if not isNameValid(name):
                    module.fail_json(
                        msg="This pwwn name is invalid : " + str(name) +
                        ". Note that name cannot be more than 64 alphanumeric chars, "
                        +
                        "it must start with a letter, and can only contain these characters: "
                        +
                        ", ".join(["'{0}'".format(c) for c in VALID_DA_CHARS]))
                if not isPwwnValid(pwwn):
                    module.fail_json(msg="This pwwn is invalid : " +
                                     str(pwwn) +
                                     ". Please check that its a valid pwwn")
    if rename is not None:
        for eachdict in rename:
            oldname = eachdict["old_name"]
            newname = eachdict["new_name"]
            if not isNameValid(oldname):
                module.fail_json(
                    msg="This pwwn name is invalid : " + str(oldname) +
                    ". Note that name cannot be more than 64 alphanumeric chars, "
                    +
                    "it must start with a letter, and can only contain these characters: "
                    + ", ".join(["'{0}'".format(c) for c in VALID_DA_CHARS]))
            if not isNameValid(newname):
                module.fail_json(
                    msg="This pwwn name is invalid : " + str(newname) +
                    ". Note that name cannot be more than 64 alphanumeric chars, "
                    +
                    "it must start with a letter, and can only contain these characters: "
                    + ", ".join(["'{0}'".format(c) for c in VALID_DA_CHARS]))

    # Step 0.1: Check DA status
    shDAStausObj = showDeviceAliasStatus(module)
    d = shDAStausObj.getDistribute()
    m = shDAStausObj.getMode()
    if shDAStausObj.isLocked():
        module.fail_json(
            msg=
            "device-alias has acquired lock on the switch. Hence cannot procced."
        )

    # Step 1: Process distribute
    commands = []
    if distribute is not None:
        if distribute:
            # playbook has distribute as True(enabled)
            if d == "disabled":
                # but switch distribute is disabled(false), so set it to
                # true(enabled)
                commands.append("device-alias distribute")
                messages.append(
                    "device-alias distribute changed from disabled to enabled")
            else:
                messages.append(
                    "device-alias distribute remains unchanged. current distribution mode is enabled"
                )
        else:
            # playbook has distribute as False(disabled)
            if d == "enabled":
                # but switch distribute is enabled(true), so set it to
                # false(disabled)
                commands.append("no device-alias distribute")
                messages.append(
                    "device-alias distribute changed from enabled to disabled")
            else:
                messages.append(
                    "device-alias distribute remains unchanged. current distribution mode is disabled"
                )

    cmds = flatten_list(commands)
    if cmds:
        commands_to_execute = commands_to_execute + cmds
        if module.check_mode:
            # Check mode implemented at the da_add/da_remove stage
            pass
        else:
            result["changed"] = True
            load_config(module, cmds)

    # Step 2: Process mode
    commands = []
    if mode is not None:
        if mode == "basic":
            # playbook has mode as basic
            if m == "enhanced":
                # but switch mode is enhanced, so set it to basic
                commands.append("no device-alias mode enhanced")
                messages.append(
                    "device-alias mode changed from enhanced to basic")
            else:
                messages.append(
                    "device-alias mode remains unchanged. current mode is basic"
                )

        else:
            # playbook has mode as enhanced
            if m == "basic":
                # but switch mode is basic, so set it to enhanced
                commands.append("device-alias mode enhanced")
                messages.append(
                    "device-alias mode changed from basic to enhanced")
            else:
                messages.append(
                    "device-alias mode remains unchanged. current mode is enhanced"
                )

    if commands:
        if distribute:
            commands.append("device-alias commit")
            commands = (["terminal dont-ask"] + commands +
                        ["no terminal dont-ask"])
        else:
            if distribute is None and d == "enabled":
                commands.append("device-alias commit")
                commands = (["terminal dont-ask"] + commands +
                            ["no terminal dont-ask"])

    cmds = flatten_list(commands)

    if cmds:
        commands_to_execute = commands_to_execute + cmds
        if module.check_mode:
            # Check mode implemented at the end
            pass
        else:
            result["changed"] = True
            load_config(module, cmds)

    # Step 3: Process da
    commands = []
    shDADatabaseObj = showDeviceAliasDatabase(module)
    if da is not None:
        da_remove_list = []
        da_add_list = []
        for eachdict in da:
            name = eachdict["name"]
            pwwn = eachdict["pwwn"]
            remove = eachdict["remove"]
            if pwwn is not None:
                pwwn = pwwn.lower()
            if remove:
                if shDADatabaseObj.isNameInDaDatabase(name):
                    commands.append("no device-alias name " + name)
                    da_remove_list.append(name)
                else:
                    messages.append(
                        name +
                        " - This device alias name is not in switch device-alias database, hence cannot be removed."
                    )
            else:
                if shDADatabaseObj.isNamePwwnPresentInDatabase(name, pwwn):
                    messages.append(
                        name + " : " + pwwn +
                        " - This device alias name,pwwn is already in switch device-alias database, hence nothing to configure"
                    )
                else:
                    if shDADatabaseObj.isNameInDaDatabase(name):
                        module.fail_json(
                            msg=name +
                            " - This device alias name is already present in switch device-alias database but assigned to another pwwn ("
                            + shDADatabaseObj.getPwwnByName(name) +
                            ") hence cannot be added")

                    elif shDADatabaseObj.isPwwnInDaDatabase(pwwn):
                        module.fail_json(
                            msg=pwwn +
                            " - This device alias pwwn is already present in switch device-alias database but assigned to another name ("
                            + shDADatabaseObj.getNameByPwwn(pwwn) +
                            ") hence cannot be added")

                    else:
                        commands.append("device-alias name " + name +
                                        " pwwn " + pwwn)
                        da_add_list.append(name)

        if len(da_add_list) != 0 or len(da_remove_list) != 0:
            commands = ["device-alias database"] + commands
            if distribute:
                commands.append("device-alias commit")
                commands = (["terminal dont-ask"] + commands +
                            ["no terminal dont-ask"])
            else:
                if distribute is None and d == "enabled":
                    commands.append("device-alias commit")
                    commands = (["terminal dont-ask"] + commands +
                                ["no terminal dont-ask"])

        cmds = flatten_list(commands)
        if cmds:
            commands_to_execute = commands_to_execute + cmds
            if module.check_mode:
                # Check mode implemented at the end
                pass
            else:
                result["changed"] = True
                load_config(module, cmds)
                if len(da_remove_list) != 0:
                    messages.append(
                        "the required device-alias were removed. " +
                        ",".join(da_remove_list))
                if len(da_add_list) != 0:
                    messages.append("the required device-alias were added. " +
                                    ",".join(da_add_list))

    # Step 5: Process rename
    commands = []
    if rename is not None:
        for eachdict in rename:
            oldname = eachdict["old_name"]
            newname = eachdict["new_name"]
            if shDADatabaseObj.isNameInDaDatabase(newname):
                module.fail_json(
                    changed=False,
                    commands=cmds,
                    msg=newname +
                    " - this name is already present in the device-alias database, hence we cannot rename "
                    + oldname + " with this one",
                )
            if shDADatabaseObj.isNameInDaDatabase(oldname):
                commands.append("device-alias rename " + oldname + " " +
                                newname)
            else:
                module.fail_json(
                    changed=False,
                    commands=cmds,
                    msg=oldname +
                    " - this name is not present in the device-alias database, hence we cannot rename.",
                )

        if len(commands) != 0:
            commands = ["device-alias database"] + commands
            if distribute:
                commands.append("device-alias commit")
                commands = (["terminal dont-ask"] + commands +
                            ["no terminal dont-ask"])
            else:
                if distribute is None and d == "enabled":
                    commands.append("device-alias commit")
                    commands = (["terminal dont-ask"] + commands +
                                ["no terminal dont-ask"])
        cmds = flatten_list(commands)
        if cmds:
            commands_to_execute = commands_to_execute + cmds
            if module.check_mode:
                # Check mode implemented at the end
                pass
            else:
                result["changed"] = True
                load_config(module, cmds)

    # Step END: check for 'check' mode
    if module.check_mode:
        module.exit_json(
            changed=False,
            commands=commands_to_execute,
            msg="Check Mode: No cmds issued to the hosts",
        )

    result["messages"] = messages
    result["commands"] = commands_to_execute
    result["warnings"] = warnings
    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(type="str", aliases=["interface"]),
        mode=dict(choices=["access", "trunk"]),
        access_vlan=dict(type="str"),
        native_vlan=dict(type="str"),
        trunk_vlans=dict(type="str", aliases=["trunk_add_vlans"]),
        trunk_allowed_vlans=dict(type="str"),
        state=dict(choices=["absent", "present", "unconfigured"],
                   default="present"),
    )

    aggregate_spec = deepcopy(element_spec)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(type="list", elements="dict", options=aggregate_spec))

    argument_spec.update(element_spec)
    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(
        argument_spec=argument_spec,
        mutually_exclusive=[
            ["access_vlan", "trunk_vlans"],
            ["access_vlan", "native_vlan"],
            ["access_vlan", "trunk_allowed_vlans"],
        ],
        supports_check_mode=True,
    )

    warnings = list()
    commands = []
    result = {"changed": False}
    if warnings:
        result["warnings"] = warnings

    want = map_params_to_obj(module)
    for w in want:
        name = w["name"]
        mode = w["mode"]
        access_vlan = w["access_vlan"]
        state = w["state"]
        trunk_vlans = w["trunk_vlans"]
        native_vlan = w["native_vlan"]
        trunk_allowed_vlans = w["trunk_allowed_vlans"]

        args = dict(
            name=name,
            mode=mode,
            access_vlan=access_vlan,
            native_vlan=native_vlan,
            trunk_vlans=trunk_vlans,
            trunk_allowed_vlans=trunk_allowed_vlans,
        )

        proposed = dict((k, v) for k, v in args.items() if v is not None)

        name = name.lower()

        if mode == "access" and state == "present" and not access_vlan:
            module.fail_json(
                msg=
                "access_vlan param is required when mode=access && state=present"
            )

        if mode == "trunk" and access_vlan:
            module.fail_json(
                msg="access_vlan param not supported when using mode=trunk")

        current_mode = get_interface_mode(name, module)

        # Current mode will return layer3, layer2, or unknown
        if current_mode == "unknown" or current_mode == "layer3":
            module.fail_json(
                msg="Ensure interface is configured to be a L2"
                "\nport first before using this module. You can use"
                "\nthe nxos_interface module for this.")

        if interface_is_portchannel(name, module):
            module.fail_json(msg="Cannot change L2 config on physical "
                             "\nport because it is in a portchannel. "
                             "\nYou should update the portchannel config.")

        # existing will never be null for Eth intfs as there is always a default
        existing = get_switchport(name, module)

        # Safeguard check
        # If there isn't an existing, something is wrong per previous comment
        if not existing:
            module.fail_json(
                msg="Make sure you are using the FULL interface name")

        if trunk_vlans or trunk_allowed_vlans:
            if trunk_vlans:
                trunk_vlans_list = vlan_range_to_list(trunk_vlans)
            elif trunk_allowed_vlans:
                trunk_vlans_list = vlan_range_to_list(trunk_allowed_vlans)
                proposed["allowed"] = True

            existing_trunks_list = vlan_range_to_list(
                (existing["trunk_vlans"]))

            existing["trunk_vlans_list"] = existing_trunks_list
            proposed["trunk_vlans_list"] = trunk_vlans_list

        current_vlans = get_list_of_vlans(module)

        if state == "present":
            if access_vlan and access_vlan not in current_vlans:
                module.fail_json(
                    msg="You are trying to configure a VLAN"
                    " on an interface that\ndoes not exist on the "
                    " switch yet!",
                    vlan=access_vlan,
                )
            elif native_vlan and native_vlan not in current_vlans:
                module.fail_json(
                    msg="You are trying to configure a VLAN"
                    " on an interface that\ndoes not exist on the "
                    " switch yet!",
                    vlan=native_vlan,
                )
            else:
                command = get_switchport_config_commands(
                    name, existing, proposed, module)
                commands.append(command)
        elif state == "unconfigured":
            is_default = is_switchport_default(existing)
            if not is_default:
                command = default_switchport_config(name)
                commands.append(command)
        elif state == "absent":
            command = remove_switchport_config_commands(
                name, existing, proposed, module)
            commands.append(command)

        if trunk_vlans or trunk_allowed_vlans:
            existing.pop("trunk_vlans_list")
            proposed.pop("trunk_vlans_list")

    cmds = flatten_list(commands)
    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            result["changed"] = True
            load_config(module, cmds)
            if "configure" in cmds:
                cmds.pop(0)

    result["commands"] = cmds
    result["warnings"] = warnings

    module.exit_json(**result)
Beispiel #16
0
def main():
    argument_spec = dict(
        seq=dict(required=False, type='str'),
        name=dict(required=True, type='str'),
        action=dict(required=False, choices=['remark', 'permit', 'deny']),
        remark=dict(required=False, type='str'),
        proto=dict(required=False, type='str'),
        src=dict(required=False, type='str'),
        src_port_op=dict(required=False),
        src_port1=dict(required=False, type='str'),
        src_port2=dict(required=False, type='str'),
        dest=dict(required=False, type='str'),
        dest_port_op=dict(required=False),
        dest_port1=dict(required=False, type='str'),
        dest_port2=dict(required=False, type='str'),
        log=dict(required=False, choices=['enable']),
        urg=dict(required=False, choices=['enable']),
        ack=dict(required=False, choices=['enable']),
        psh=dict(required=False, choices=['enable']),
        rst=dict(required=False, choices=['enable']),
        syn=dict(required=False, choices=['enable']),
        fragments=dict(required=False, choices=['enable']),
        fin=dict(required=False, choices=['enable']),
        established=dict(required=False, choices=['enable']),
        time_range=dict(required=False),
        precedence=dict(required=False,
                        choices=[
                            'critical', 'flash', 'flash-override', 'immediate',
                            'internet', 'network', 'priority', 'routine'
                        ]),
        dscp=dict(required=False,
                  choices=[
                      'af11', 'af12', 'af13', 'af21', 'af22', 'af23', 'af31',
                      'af32', 'af33', 'af41', 'af42', 'af43', 'cs1', 'cs2',
                      'cs3', 'cs4', 'cs5', 'cs6', 'cs7', 'default', 'ef'
                  ]),
        state=dict(choices=['absent', 'present', 'delete_acl'],
                   default='present'))

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    results = dict(changed=False, warnings=warnings)

    state = module.params['state']
    action = module.params['action']
    remark = module.params['remark']
    dscp = module.params['dscp']
    precedence = module.params['precedence']
    seq = module.params['seq']
    name = module.params['name']
    seq = module.params['seq']

    if action == 'remark' and not remark:
        module.fail_json(
            msg='when state is action, remark param is also required')

    REQUIRED = ['seq', 'name', 'action', 'proto', 'src', 'dest']
    ABSENT = ['name', 'seq']
    if state == 'present':
        if action and remark and seq:
            pass
        else:
            for each in REQUIRED:
                if module.params[each] is None:
                    module.fail_json(msg="req'd params when state is present:",
                                     params=REQUIRED)
    elif state == 'absent':
        for each in ABSENT:
            if module.params[each] is None:
                module.fail_json(msg='require params when state is absent',
                                 params=ABSENT)
    elif state == 'delete_acl':
        if module.params['name'] is None:
            module.fail_json(msg="param name req'd when state is delete_acl")

    if dscp and precedence:
        module.fail_json(msg='only one of the params dscp/precedence '
                         'are allowed')

    OPTIONS_NAMES = [
        'log', 'urg', 'ack', 'psh', 'rst', 'syn', 'fin', 'established', 'dscp',
        'precedence', 'fragments', 'time_range'
    ]

    CORE = [
        'seq', 'name', 'action', 'proto', 'src', 'src_port_op', 'src_port1',
        'src_port2', 'dest', 'dest_port_op', 'dest_port1', 'dest_port2',
        'remark'
    ]

    proposed_core = dict((param, value)
                         for (param, value) in module.params.items()
                         if param in CORE and value is not None)

    proposed_options = dict((param, value)
                            for (param, value) in module.params.items()
                            if param in OPTIONS_NAMES and value is not None)
    proposed = {}
    proposed.update(proposed_core)
    proposed.update(proposed_options)

    existing_options = {}

    # getting existing existing_core=dict, acl=list, seq=list
    existing_core, acl = get_acl(module, name, seq)
    if existing_core:
        existing_options = existing_core.get('options')
        existing_core.pop('options')

    commands = []
    delta_core = {}
    delta_options = {}

    if not existing_core.get('remark'):
        dcore = dict(
            set(proposed_core.items()).difference(existing_core.items()))
        if not dcore:
            # check the diff in the other way just in case
            dcore = dict(
                set(existing_core.items()).difference(proposed_core.items()))
        delta_core = dcore
        if delta_core:
            delta_options = proposed_options
        else:
            doptions = dict(
                set(proposed_options.items()).difference(
                    existing_options.items()))
            # check the diff in the other way just in case
            if not doptions:
                doptions = dict(
                    set(existing_options.items()).difference(
                        proposed_options.items()))
            delta_options = doptions
    else:
        delta_core = dict(
            set(proposed_core.items()).difference(existing_core.items()))

    if state == 'present':
        if delta_core or delta_options:
            if existing_core:  # if the ace exists already
                commands.append(['no {0}'.format(seq)])
            if delta_options:
                myacl_str = config_core_acl(proposed_core)
                myacl_str += ' ' + config_acl_options(proposed_options)
            else:
                myacl_str = config_core_acl(proposed_core)
            command = [myacl_str]
            commands.append(command)
    elif state == 'absent':
        if existing_core:
            commands.append(['no {0}'.format(seq)])
    elif state == 'delete_acl':
        if acl and acl[0].get('acl') != 'no_entries':
            commands.append(['no ip access-list {0}'.format(name)])

    cmds = []
    if commands:
        preface = []
        if state in ['present', 'absent']:
            preface = ['ip access-list {0}'.format(name)]
            commands.insert(0, preface)

        cmds = flatten_list(commands)
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            load_config(module, cmds)
            results['changed'] = True
            if 'configure' in cmds:
                cmds.pop(0)

    results['commands'] = cmds

    module.exit_json(**results)
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"),
    )

    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":

        if current:
            have = "route-target both auto evpn" in current
            if module.params["route_target_both_auto_evpn"] is not None:
                want = bool(module.params["route_target_both_auto_evpn"])
                if want and not have:
                    commands.append("address-family %s unicast" %
                                    module.params["afi"])
                    commands.append("route-target both auto evpn")
                elif have and not want:
                    commands.append("address-family %s unicast" %
                                    module.params["afi"])
                    commands.append("no route-target both auto evpn")

        else:
            commands.append("address-family %s unicast" % module.params["afi"])
            if module.params["route_target_both_auto_evpn"]:
                commands.append("route-target both auto evpn")

    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 reboot(module):
    cmds = 'terminal dont-ask ; reload'
    opts = {'ignore_timeout': True}
    load_config(module, cmds, False, opts)
Beispiel #19
0
def main():
    vsan_element_spec = dict(
        id=dict(required=True, type="int"),
        name=dict(type="str"),
        remove=dict(type="bool"),
        suspend=dict(type="bool"),
        interface=dict(type="list", elements="str"),
    )

    argument_spec = dict(
        vsan=dict(type="list", elements="dict", options=vsan_element_spec))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    warnings = list()
    messages = list()
    commands_executed = list()
    result = {"changed": False}

    obj = GetVsanInfoFromSwitch(module)
    dictSwVsanObjs = obj.getVsanInfoObjects()

    commands = []
    vsan_list = module.params["vsan"]

    for eachvsan in vsan_list:
        vsanid = str(eachvsan["id"])
        vsanname = eachvsan["name"]
        vsanremove = eachvsan["remove"]
        vsansuspend = eachvsan["suspend"]
        vsaninterface_list = eachvsan["interface"]

        if int(vsanid) < 1 or int(vsanid) >= 4095:
            module.fail_json(
                msg=vsanid +
                " - This is an invalid vsan. Supported vsan range is 1-4094")

        if vsanid in dictSwVsanObjs.keys():
            sw_vsanid = vsanid
            sw_vsanname = dictSwVsanObjs[vsanid].vsanname
            sw_vsanstate = dictSwVsanObjs[vsanid].vsanstate
            sw_vsaninterfaces = dictSwVsanObjs[vsanid].vsaninterfaces
        else:
            sw_vsanid = None
            sw_vsanname = None
            sw_vsanstate = None
            sw_vsaninterfaces = []

        if vsanremove:
            # Negative case:
            if vsanid == "4079" or vsanid == "4094":
                messages.append(
                    str(vsanid) +
                    " is a reserved vsan, hence cannot be removed")
                continue
            if vsanid == sw_vsanid:
                commands.append("no vsan " + str(vsanid))
                messages.append("deleting the vsan " + str(vsanid))
            else:
                messages.append(
                    "There is no vsan " + str(vsanid) +
                    " present in the switch. Hence there is nothing to delete")
            continue
        else:
            # Negative case:
            if vsanid == "4079" or vsanid == "4094":
                messages.append(
                    str(vsanid) +
                    " is a reserved vsan, and always present on the switch")
            else:
                if vsanid == sw_vsanid:
                    messages.append(
                        "There is already a vsan " + str(vsanid) +
                        " present in the switch. Hence there is nothing to configure"
                    )
                else:
                    commands.append("vsan " + str(vsanid))
                    messages.append("creating vsan " + str(vsanid))

        if vsanname is not None:
            # Negative case:
            if vsanid == "4079" or vsanid == "4094":
                messages.append(
                    str(vsanid) + " is a reserved vsan, and cannot be renamed")
            else:
                if vsanname == sw_vsanname:
                    messages.append(
                        "There is already a vsan " + str(vsanid) +
                        " present in the switch, which has the name " +
                        vsanname + " Hence there is nothing to configure")
                else:
                    commands.append("vsan " + str(vsanid) + " name " +
                                    vsanname)
                    messages.append("setting vsan name to " + vsanname +
                                    " for vsan " + str(vsanid))

        if vsansuspend:
            # Negative case:
            if vsanid == "4079" or vsanid == "4094":
                messages.append(
                    str(vsanid) +
                    " is a reserved vsan, and cannot be suspended")
            else:
                if sw_vsanstate == "suspended":
                    messages.append(
                        "There is already a vsan " + str(vsanid) +
                        " present in the switch, which is in suspended state ")
                else:
                    commands.append("vsan " + str(vsanid) + " suspend")
                    messages.append("suspending the vsan " + str(vsanid))
        else:
            if sw_vsanstate == "active":
                messages.append(
                    "There is already a vsan " + str(vsanid) +
                    " present in the switch, which is in active state ")
            else:
                commands.append("no vsan " + str(vsanid) + " suspend")
                messages.append("no suspending the vsan " + str(vsanid))

        if vsaninterface_list is not None:
            for each_interface_name in vsaninterface_list:
                # For fcip,port-channel,vfc-port-channel need to remove the
                # extra space to compare
                temp = re.sub(" +", "", each_interface_name)
                if temp in sw_vsaninterfaces:
                    messages.append(each_interface_name +
                                    " is already present in the vsan " +
                                    str(vsanid) + " interface list")
                else:
                    commands.append("vsan " + str(vsanid) + " interface " +
                                    each_interface_name)
                    messages.append("adding interface " + each_interface_name +
                                    " to vsan " + str(vsanid))

    if len(commands) != 0:
        commands = (["terminal dont-ask"] + ["vsan database"] + commands +
                    ["no terminal dont-ask"])

    cmds = flatten_list(commands)
    commands_executed = cmds

    if commands_executed:
        if module.check_mode:
            module.exit_json(
                changed=False,
                commands=commands_executed,
                msg="Check Mode: No cmds issued to the hosts",
            )
        else:
            result["changed"] = True
            load_config(module, commands_executed)

    result["messages"] = messages
    result["commands"] = commands_executed
    result["warnings"] = warnings
    module.exit_json(**result)
def main():

    supported_choices = ["device_alias"]
    zone_member_spec = dict(
        pwwn=dict(required=True, type="str", aliases=["device_alias"]),
        devtype=dict(type="str", choices=["initiator", "target", "both"]),
        remove=dict(type="bool", default=False),
    )

    zone_spec = dict(
        name=dict(required=True, type="str"),
        members=dict(type="list", elements="dict", options=zone_member_spec),
        remove=dict(type="bool", default=False),
    )

    zoneset_member_spec = dict(
        name=dict(required=True, type="str"),
        remove=dict(type="bool", default=False),
    )

    zoneset_spec = dict(
        name=dict(type="str", required=True),
        members=dict(
            type="list", elements="dict", options=zoneset_member_spec
        ),
        remove=dict(type="bool", default=False),
        action=dict(type="str", choices=["activate", "deactivate"]),
    )

    zonedetails_spec = dict(
        vsan=dict(required=True, type="int"),
        mode=dict(type="str", choices=["enhanced", "basic"]),
        default_zone=dict(type="str", choices=["permit", "deny"]),
        smart_zoning=dict(type="bool"),
        zone=dict(type="list", elements="dict", options=zone_spec),
        zoneset=dict(type="list", elements="dict", options=zoneset_spec),
    )

    argument_spec = dict(
        zone_zoneset_details=dict(
            type="list", elements="dict", options=zonedetails_spec
        )
    )

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

    warnings = list()
    messages = list()
    commands = list()
    result = {"changed": False}

    commands_executed = []
    listOfZoneDetails = module.params["zone_zoneset_details"]
    for eachZoneZonesetDetail in listOfZoneDetails:
        vsan = eachZoneZonesetDetail["vsan"]
        op_mode = eachZoneZonesetDetail["mode"]
        op_default_zone = eachZoneZonesetDetail["default_zone"]
        op_smart_zoning = eachZoneZonesetDetail["smart_zoning"]
        op_zone = eachZoneZonesetDetail["zone"]
        op_zoneset = eachZoneZonesetDetail["zoneset"]

        # Step1: execute show zone status and get
        shZoneStatusObj = ShowZoneStatus(module, vsan)
        sw_default_zone = shZoneStatusObj.getDefaultZone()
        sw_mode = shZoneStatusObj.getMode()
        sw_smart_zoning = shZoneStatusObj.getSmartZoningStatus()

        if sw_smart_zoning.lower() == "Enabled".lower():
            sw_smart_zoning_bool = True
        else:
            sw_smart_zoning_bool = False

        if shZoneStatusObj.isVsanAbsent():
            module.fail_json(
                msg="Vsan "
                + str(vsan)
                + " is not present in the switch. Hence cannot procced."
            )

        if shZoneStatusObj.isLocked():
            module.fail_json(
                msg="zone has acquired lock on the switch for vsan "
                + str(vsan)
                + ". Hence cannot procced."
            )

        # Process zone default zone options
        if op_default_zone is not None:
            if op_default_zone != sw_default_zone:
                if op_default_zone == "permit":
                    commands_executed.append(
                        "zone default-zone permit vsan " + str(vsan)
                    )
                    messages.append(
                        "default zone configuration changed from deny to permit for vsan "
                        + str(vsan)
                    )
                else:
                    commands_executed.append(
                        "no zone default-zone permit vsan " + str(vsan)
                    )
                    messages.append(
                        "default zone configuration changed from permit to deny for vsan "
                        + str(vsan)
                    )
            else:
                messages.append(
                    "default zone is already "
                    + op_default_zone
                    + " ,no change in default zone configuration for vsan "
                    + str(vsan)
                )

        # Process zone mode options
        if op_mode is not None:
            if op_mode != sw_mode:
                if op_mode == "enhanced":
                    commands_executed.append(
                        "zone mode enhanced vsan " + str(vsan)
                    )
                    messages.append(
                        "zone mode configuration changed from basic to enhanced for vsan "
                        + str(vsan)
                    )
                else:
                    commands_executed.append(
                        "no zone mode enhanced vsan " + str(vsan)
                    )
                    messages.append(
                        "zone mode configuration changed from enhanced to basic for vsan "
                        + str(vsan)
                    )
            else:
                messages.append(
                    "zone mode is already "
                    + op_mode
                    + " ,no change in zone mode configuration for vsan "
                    + str(vsan)
                )

        # Process zone smart-zone options
        if op_smart_zoning is not None:
            if op_smart_zoning != sw_smart_zoning_bool:
                if op_smart_zoning:
                    commands_executed.append(
                        "zone smart-zoning enable vsan " + str(vsan)
                    )
                    messages.append(
                        "smart-zoning enabled for vsan " + str(vsan)
                    )
                else:
                    commands_executed.append(
                        "no zone smart-zoning enable vsan " + str(vsan)
                    )
                    messages.append(
                        "smart-zoning disabled for vsan " + str(vsan)
                    )
            else:
                messages.append(
                    "smart-zoning is already set to "
                    + sw_smart_zoning
                    + " , no change in smart-zoning configuration for vsan "
                    + str(vsan)
                )

        # Process zone member options
        # TODO: Obviously this needs to be cleaned up properly, as there are a lot of ifelse statements which is bad
        # Will take it up later becoz of time constraints
        if op_zone is not None:
            shZoneObj = ShowZone(module, vsan)
            for eachzone in op_zone:
                zname = eachzone["name"]
                zmembers = eachzone["members"]
                removeflag = eachzone["remove"]
                if removeflag:
                    if shZoneObj.isZonePresent(zname):
                        messages.append(
                            "zone '"
                            + zname
                            + "' is removed from vsan "
                            + str(vsan)
                        )
                        commands_executed.append(
                            "no zone name " + zname + " vsan " + str(vsan)
                        )
                    else:
                        messages.append(
                            "zone '"
                            + zname
                            + "' is not present in vsan "
                            + str(vsan)
                            + " , so nothing to remove"
                        )
                else:
                    if zmembers is None:
                        if shZoneObj.isZonePresent(zname):
                            messages.append(
                                "zone '"
                                + zname
                                + "' is already present in vsan "
                                + str(vsan)
                            )
                        else:
                            commands_executed.append(
                                "zone name " + zname + " vsan " + str(vsan)
                            )
                            messages.append(
                                "zone '"
                                + zname
                                + "' is created in vsan "
                                + str(vsan)
                            )
                    else:
                        cmdmemlist = []
                        for eachmem in zmembers:
                            memtype = getMemType(
                                supported_choices, eachmem.keys()
                            )
                            cmd = (
                                memtype.replace("_", "-")
                                + " "
                                + eachmem[memtype]
                            )
                            if op_smart_zoning or sw_smart_zoning_bool:
                                if eachmem["devtype"] is not None:
                                    cmd = cmd + " " + eachmem["devtype"]
                            if eachmem["remove"]:
                                if shZoneObj.isZonePresent(zname):
                                    if shZoneObj.isZoneMemberPresent(
                                        zname, cmd
                                    ):
                                        cmd = "no member " + cmd
                                        cmdmemlist.append(cmd)
                                        if (
                                            op_smart_zoning
                                            and eachmem["devtype"] is not None
                                        ):
                                            messages.append(
                                                "removing zone member '"
                                                + eachmem[memtype]
                                                + " of device type '"
                                                + eachmem["devtype"]
                                                + "' from zone '"
                                                + zname
                                                + "' in vsan "
                                                + str(vsan)
                                            )
                                        else:
                                            messages.append(
                                                "removing zone member '"
                                                + eachmem[memtype]
                                                + "' from zone '"
                                                + zname
                                                + "' in vsan "
                                                + str(vsan)
                                            )
                                    else:
                                        if (
                                            op_smart_zoning
                                            and eachmem["devtype"] is not None
                                        ):
                                            messages.append(
                                                "zone member '"
                                                + eachmem[memtype]
                                                + "' of device type '"
                                                + eachmem["devtype"]
                                                + "' is not present in zone '"
                                                + zname
                                                + "' in vsan "
                                                + str(vsan)
                                                + " hence nothing to remove"
                                            )
                                        else:
                                            messages.append(
                                                "zone member '"
                                                + eachmem[memtype]
                                                + "' is not present in zone '"
                                                + zname
                                                + "' in vsan "
                                                + str(vsan)
                                                + " hence nothing to remove"
                                            )
                                else:
                                    messages.append(
                                        "zone '"
                                        + zname
                                        + "' is not present in vsan "
                                        + str(vsan)
                                        + " , hence cannot remove the members"
                                    )

                            else:
                                if shZoneObj.isZoneMemberPresent(zname, cmd):
                                    if (
                                        op_smart_zoning
                                        and eachmem["devtype"] is not None
                                    ):
                                        messages.append(
                                            "zone member '"
                                            + eachmem[memtype]
                                            + "' of device type '"
                                            + eachmem["devtype"]
                                            + "' is already present in zone '"
                                            + zname
                                            + "' in vsan "
                                            + str(vsan)
                                            + " hence nothing to add"
                                        )
                                    else:
                                        messages.append(
                                            "zone member '"
                                            + eachmem[memtype]
                                            + "' is already present in zone '"
                                            + zname
                                            + "' in vsan "
                                            + str(vsan)
                                            + " hence nothing to add"
                                        )
                                else:
                                    cmd = "member " + cmd
                                    cmdmemlist.append(cmd)
                                    if (
                                        op_smart_zoning
                                        and eachmem["devtype"] is not None
                                    ):
                                        messages.append(
                                            "adding zone member '"
                                            + eachmem[memtype]
                                            + "' of device type '"
                                            + eachmem["devtype"]
                                            + "' to zone '"
                                            + zname
                                            + "' in vsan "
                                            + str(vsan)
                                        )
                                    else:
                                        messages.append(
                                            "adding zone member '"
                                            + eachmem[memtype]
                                            + "' to zone '"
                                            + zname
                                            + "' in vsan "
                                            + str(vsan)
                                        )
                        if len(cmdmemlist) != 0:
                            commands_executed.append(
                                "zone name " + zname + " vsan " + str(vsan)
                            )
                            commands_executed = commands_executed + cmdmemlist

        # Process zoneset member options
        if op_zoneset is not None:
            dactcmd = []
            actcmd = []
            shZonesetObj = ShowZoneset(module, vsan)
            shZonesetActiveObj = ShowZonesetActive(module, vsan)
            for eachzoneset in op_zoneset:
                zsetname = eachzoneset["name"]
                zsetmembers = eachzoneset["members"]
                removeflag = eachzoneset["remove"]
                actionflag = eachzoneset["action"]
                if removeflag:
                    if shZonesetObj.isZonesetPresent(zsetname):
                        messages.append(
                            "zoneset '"
                            + zsetname
                            + "' is removed from vsan "
                            + str(vsan)
                        )
                        commands_executed.append(
                            "no zoneset name "
                            + zsetname
                            + " vsan "
                            + str(vsan)
                        )
                    else:
                        messages.append(
                            "zoneset '"
                            + zsetname
                            + "' is not present in vsan "
                            + str(vsan)
                            + " ,hence there is nothing to remove"
                        )
                else:
                    if zsetmembers is not None:
                        cmdmemlist = []
                        for eachzsmem in zsetmembers:
                            zsetmem_name = eachzsmem["name"]
                            zsetmem_removeflag = eachzsmem["remove"]
                            if zsetmem_removeflag:
                                if shZonesetObj.isZonePresentInZoneset(
                                    zsetname, zsetmem_name
                                ):
                                    cmd = "no member " + zsetmem_name
                                    cmdmemlist.append(cmd)
                                    messages.append(
                                        "removing zoneset member '"
                                        + zsetmem_name
                                        + "' from zoneset '"
                                        + zsetname
                                        + "' in vsan "
                                        + str(vsan)
                                    )
                                else:
                                    messages.append(
                                        "zoneset member '"
                                        + zsetmem_name
                                        + "' is not present in zoneset '"
                                        + zsetname
                                        + "' in vsan "
                                        + str(vsan)
                                        + " ,hence there is nothing to remove"
                                    )
                            else:
                                if shZonesetObj.isZonePresentInZoneset(
                                    zsetname, zsetmem_name
                                ):
                                    messages.append(
                                        "zoneset member '"
                                        + zsetmem_name
                                        + "' is already present in zoneset '"
                                        + zsetname
                                        + "' in vsan "
                                        + str(vsan)
                                        + " ,hence there is nothing to add"
                                    )
                                else:
                                    cmd = "member " + zsetmem_name
                                    cmdmemlist.append(cmd)
                                    messages.append(
                                        "adding zoneset member '"
                                        + zsetmem_name
                                        + "' to zoneset '"
                                        + zsetname
                                        + "' in vsan "
                                        + str(vsan)
                                    )
                        if len(cmdmemlist) != 0:
                            commands_executed.append(
                                "zoneset name "
                                + zsetname
                                + " vsan "
                                + str(vsan)
                            )
                            commands_executed = commands_executed + cmdmemlist
                    else:
                        if shZonesetObj.isZonesetPresent(zsetname):
                            messages.append(
                                "zoneset '"
                                + zsetname
                                + "' is already present in vsan "
                                + str(vsan)
                            )
                        else:
                            commands_executed.append(
                                "zoneset name "
                                + zsetname
                                + " vsan "
                                + str(vsan)
                            )
                            messages.append(
                                "zoneset '"
                                + zsetname
                                + "' is created in vsan "
                                + str(vsan)
                            )

                # Process zoneset activate options
                if actionflag == "deactivate":
                    if shZonesetActiveObj.isZonesetActive(zsetname):
                        messages.append(
                            "deactivating zoneset '"
                            + zsetname
                            + "' in vsan "
                            + str(vsan)
                        )
                        dactcmd.append(
                            "no zoneset activate name "
                            + zsetname
                            + " vsan "
                            + str(vsan)
                        )
                    else:
                        messages.append(
                            "zoneset '"
                            + zsetname
                            + "' in vsan "
                            + str(vsan)
                            + " is not activated, hence cannot deactivate"
                        )
                elif actionflag == "activate":
                    if shZonesetActiveObj.isZonesetActive(zsetname):
                        messages.append(
                            "zoneset '"
                            + zsetname
                            + "' in vsan "
                            + str(vsan)
                            + " is already activated"
                        )
                    else:
                        messages.append(
                            "activating zoneset '"
                            + zsetname
                            + "' in vsan "
                            + str(vsan)
                        )
                        actcmd.append(
                            "zoneset activate name "
                            + zsetname
                            + " vsan "
                            + str(vsan)
                        )
            commands_executed = commands_executed + dactcmd + actcmd

        if commands_executed:
            if op_mode == "enhanced":
                commands_executed.append("zone commit vsan " + str(vsan))
            elif op_mode is None:
                if sw_mode == "enhanced":
                    commands_executed.append("zone commit vsan " + str(vsan))

    if commands_executed:
        commands_executed = (
            ["terminal dont-ask"]
            + commands_executed
            + ["no terminal dont-ask"]
        )

    cmds = flatten_list(commands_executed)
    if cmds:
        if module.check_mode:
            module.exit_json(
                changed=False,
                commands=cmds,
                msg="Check Mode: No cmds issued to the hosts",
            )
        else:
            result["changed"] = True
            commands = commands + cmds
            load_config(module, cmds)

    result["messages"] = messages
    result["commands"] = commands_executed
    result["warnings"] = warnings
    module.exit_json(**result)
Beispiel #21
0
def main():
    argument_spec = dict(
        state=dict(choices=["enabled", "disabled"], default="enabled"),
        group=dict(
            choices=[
                "aaa",
                "bfd",
                "bgp",
                "bridge",
                "callhome",
                "cfs",
                "config",
                "eigrp",
                "entity",
                "feature-control",
                "generic",
                "hsrp",
                "license",
                "link",
                "lldp",
                "mmode",
                "ospf",
                "pim",
                "rf",
                "rmon",
                "snmp",
                "storm-control",
                "stpx",
                "switchfabric",
                "syslog",
                "sysmgr",
                "system",
                "upgrade",
                "vtp",
                "all",
            ],
            required=True,
        ),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    results = {"changed": False, "commands": [], "warnings": warnings}

    group = module.params["group"].lower()
    state = module.params["state"]

    existing = get_snmp_traps(group, module)

    commands = get_trap_commands(group, state, existing, module)
    cmds = flatten_list(commands)
    if cmds:
        results["changed"] = True
        if not module.check_mode:
            load_config(module, cmds)

        if "configure" in cmds:
            cmds.pop(0)
        results["commands"] = cmds

    module.exit_json(**results)
Beispiel #22
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        dest=dict(choices=DEST_GROUP),
        name=dict(),
        facility=dict(),
        remote_server=dict(),
        use_vrf=dict(),
        dest_level=dict(type="int", aliases=["level"]),
        facility_level=dict(type="int"),
        interface=dict(),
        facility_link_status=dict(choices=[
            "link-down-notif",
            "link-down-error",
            "link-up-notif",
            "link-up-error",
        ]),
        event=dict(choices=[
            "link-enable",
            "link-default",
            "trunk-enable",
            "trunk-default",
        ]),
        interface_message=dict(choices=["add-interface-description"]),
        file_size=dict(type="int"),
        timestamp=dict(choices=["microseconds", "milliseconds", "seconds"]),
        state=dict(default="present", choices=["present", "absent"]),
        aggregate=dict(type="list"),
        purge=dict(default=False, type="bool"),
    )

    argument_spec.update(nxos_argument_spec)

    required_if = [
        ("dest", "logfile", ["name"]),
        ("dest", "server", ["remote_server"]),
    ]

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

    warnings = list()

    result = {"changed": False}
    if warnings:
        result["warnings"] = warnings

    want = map_params_to_obj(module)
    merged_wants = merge_wants(read_module_context(module), want)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands(module, (want, have))
    result["commands"] = commands

    if commands:
        if not module.check_mode:
            load_config(module, commands)
        result["changed"] = True

    save_module_context(module, merged_wants)

    if module.params.get("purge"):
        pcommands = map_obj_to_commands(module,
                                        (outliers(have, merged_wants), have))
        if pcommands:
            if not module.check_mode:
                load_config(module, pcommands)
            result["changed"] = True
        result["commands"] += pcommands

    module.exit_json(**result)
Beispiel #23
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        configured_password=dict(no_log=True),
        update_password=dict(default="always", choices=["on_create",
                                                        "always"]),
        roles=dict(type="list", aliases=["role"]),
        sshkey=dict(),
        state=dict(default="present", choices=["present", "absent"]),
    )

    aggregate_spec = deepcopy(element_spec)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(
        aggregate=dict(
            type="list",
            elements="dict",
            options=aggregate_spec,
            aliases=["collection", "users"],
        ),
        purge=dict(type="bool", default=False),
    )

    argument_spec.update(element_spec)
    argument_spec.update(nxos_argument_spec)

    mutually_exclusive = [("name", "aggregate")]

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

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

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands(update_objects(want, have), module)

    if module.params["purge"]:
        want_users = [x["name"] for x in want]
        have_users = [x["name"] for x in have]
        for item in set(have_users).difference(want_users):
            if item != "admin":
                item = item.replace("\\", "\\\\")
                commands.append("no username %s" % item)

    result["commands"] = commands

    # the nxos cli prevents this by rule so capture it and display
    # a nice failure message
    if "no username admin" in commands:
        module.fail_json(msg="cannot delete the `admin` account")

    if commands:
        if not module.check_mode:
            responses = load_config(module, commands)
            for resp in responses:
                if resp.lower().startswith("wrong password"):
                    module.fail_json(msg=resp)
                else:
                    result["warnings"].extend([
                        x[9:] for x in resp.splitlines()
                        if x.startswith("WARNING: ")
                    ])

        result["changed"] = True

    module.exit_json(**result)
Beispiel #24
0
def main():
    argument_spec = dict(
        community=dict(required=True, type="str"),
        access=dict(choices=["ro", "rw"]),
        group=dict(type="str"),
        acl=dict(type="str"),
        state=dict(choices=["absent", "present"], default="present"),
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_one_of=[["access", "group"]],
        mutually_exclusive=[["access", "group"]],
        supports_check_mode=True,
    )

    warnings = list()
    results = {"changed": False, "commands": [], "warnings": warnings}

    access = module.params["access"]
    group = module.params["group"]
    community = module.params["community"]
    acl = module.params["acl"]
    state = module.params["state"]

    if access:
        if access == "ro":
            group = "network-operator"
        elif access == "rw":
            group = "network-admin"

    # group check - ensure group being configured exists on the device
    configured_groups = get_snmp_groups(module)

    if group not in configured_groups:
        module.fail_json(
            msg="Group not on switch. Please add before moving forward"
        )

    existing = get_snmp_community(module, community)
    args = dict(group=group, acl=acl)
    proposed = dict((k, v) for k, v in args.items() if v is not None)
    delta = dict(set(proposed.items()).difference(existing.items()))
    if delta.get("acl") == "default":
        delta.pop("acl")
        if existing.get("acl"):
            delta["no_acl"] = existing.get("acl")

    commands = []

    if state == "absent":
        if existing:
            command = "no snmp-server community {0}".format(community)
            commands.append(command)
    elif state == "present":
        if delta:
            command = config_snmp_community(dict(delta), community)
            commands.append(command)

    cmds = flatten_list(commands)

    if cmds:
        results["changed"] = True
        if not module.check_mode:
            load_config(module, cmds)

        if "configure" in cmds:
            cmds.pop(0)
        results["commands"] = cmds

    module.exit_json(**results)
Beispiel #25
0
def main():
    argument_spec = dict(
        snooping=dict(required=False, type="bool"),
        group_timeout=dict(required=False, type="str"),
        link_local_grp_supp=dict(required=False, type="bool"),
        report_supp=dict(required=False, type="bool"),
        v3_report_supp=dict(required=False, type="bool"),
        state=dict(choices=["present", "default"], default="present"),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    results = {"changed": False, "commands": [], "warnings": warnings}

    snooping = module.params["snooping"]
    link_local_grp_supp = module.params["link_local_grp_supp"]
    report_supp = module.params["report_supp"]
    v3_report_supp = module.params["v3_report_supp"]
    group_timeout = module.params["group_timeout"]
    state = module.params["state"]

    args = dict(
        snooping=snooping,
        link_local_grp_supp=link_local_grp_supp,
        report_supp=report_supp,
        v3_report_supp=v3_report_supp,
        group_timeout=group_timeout,
    )

    proposed = dict(
        (param, value) for (param, value) in args.items() if value is not None)

    existing = get_igmp_snooping(module)

    commands = []
    if state == "present":
        delta = dict(set(proposed.items()).difference(existing.items()))
        if delta:
            command = config_igmp_snooping(delta, existing)
            if command:
                if group_timeout:
                    igmp_snooping_gt_dependency(command, existing, module)
                commands.append(command)
    elif state == "default":
        proposed = get_igmp_snooping_defaults()
        delta = dict(set(proposed.items()).difference(existing.items()))
        if delta:
            command = config_igmp_snooping(delta, existing, default=True)
            if command:
                commands.append(command)

    cmds = flatten_list(commands)
    if cmds:
        results["changed"] = True
        if not module.check_mode:
            load_config(module, cmds)
        if "configure" in cmds:
            cmds.pop(0)
        results["commands"] = cmds

    module.exit_json(**results)
def main():
    argument_spec = dict(
        vtp_password=dict(type='str', no_log=True),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    vtp_password = module.params['vtp_password'] or None
    state = module.params['state']

    existing = get_vtp_config(module)
    end_state = existing

    args = dict(vtp_password=vtp_password)

    changed = False
    proposed = dict((k, v) for k, v in args.items() if v is not None)
    delta = dict(set(proposed.items()).difference(existing.items()))

    commands = []
    if state == 'absent':
        # if vtp_password is not set, some devices returns '\\' or the string 'None'
        if not existing['vtp_password'] or existing[
                'vtp_password'] == '\\' or existing['vtp_password'] == 'None':
            pass
        elif vtp_password is not None:
            if existing['vtp_password'] == proposed['vtp_password']:
                commands.append(['no vtp password'])
            else:
                module.fail_json(msg="Proposed vtp password doesn't match "
                                 "current vtp password. It cannot be "
                                 "removed when state=absent. If you are "
                                 "trying to change the vtp password, use "
                                 "state=present.")
        else:
            if not existing.get('domain'):
                module.fail_json(msg='Cannot remove a vtp password '
                                 'before vtp domain is set.')

            elif existing['vtp_password'] != ('\\'):
                commands.append(['no vtp password'])

    elif state == 'present':
        if delta:
            if not existing.get('domain'):
                module.fail_json(msg='Cannot set vtp password '
                                 'before vtp domain is set.')

            else:
                commands.append(['vtp password {0}'.format(vtp_password)])

    cmds = flatten_list(commands)
    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            changed = True
            load_config(module, cmds)
            end_state = get_vtp_config(module)
            if 'configure' in cmds:
                cmds.pop(0)

    results = {}
    results['proposed'] = proposed
    results['existing'] = existing
    results['end_state'] = end_state
    results['updates'] = cmds
    results['changed'] = changed
    results['warnings'] = warnings

    module.exit_json(**results)
Beispiel #27
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)
Beispiel #28
0
def main():
    argument_spec = dict(
        interface=dict(required=True, type='str'),
        description=dict(required=False, type='str'),
        host_reachability=dict(required=False, type='bool'),
        global_ingress_replication_bgp=dict(required=False, type='bool'),
        global_suppress_arp=dict(required=False, type='bool'),
        global_mcast_group_L2=dict(required=False, type='str'),
        global_mcast_group_L3=dict(required=False, type='str'),
        shutdown=dict(required=False, type='bool'),
        source_interface=dict(required=False, type='str'),
        source_interface_hold_down_time=dict(required=False, type='str'),
        state=dict(choices=['present', 'absent'],
                   default='present',
                   required=False),
    )

    argument_spec.update(nxos_argument_spec)

    mutually_exclusive = [('global_ingress_replication_bgp',
                           'global_mcast_group_L2')]

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

    warnings = list()
    result = {'changed': False, 'commands': [], 'warnings': warnings}

    state = module.params['state']

    args = PARAM_TO_COMMAND_KEYMAP.keys()

    existing = get_existing(module, args)
    proposed_args = dict((k, v) for k, v in module.params.items()
                         if v is not None and k in args)
    proposed = {}
    for key, value in proposed_args.items():
        if key != 'interface':
            if str(value).lower() == 'default':
                value = PARAM_TO_DEFAULT_KEYMAP.get(key)
                if value is None:
                    if key in BOOL_PARAMS:
                        value = False
                    else:
                        value = 'default'
            if str(existing.get(key)).lower() != str(value).lower():
                proposed[key] = value

    candidate = CustomNetworkConfig(indent=3)

    if proposed.get('global_suppress_arp'):
        gsa_tcam_check(module)
    if state == 'present':
        if not existing:
            warnings.append("The proposed NVE interface did not exist. "
                            "It's recommended to use nxos_interface to create "
                            "all logical interfaces.")
        state_present(module, existing, proposed, candidate)
    elif state == 'absent' and existing:
        state_absent(module, existing, proposed, candidate)

    if candidate:
        candidate = candidate.items_text()
        result['commands'] = candidate
        result['changed'] = True
        load_config(module, candidate)

    module.exit_json(**result)
def main():
    """ 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", elements="str"),
        associated_interfaces=dict(type="list", elements="str"),
        vlan_state=dict(choices=["active", "suspend"],
                        required=False,
                        default="active"),
        mapped_vni=dict(required=False),
        delay=dict(default=10, type="int"),
        state=dict(choices=["present", "absent"],
                   default="present",
                   required=False),
        admin_state=dict(choices=["up", "down"], required=False, default="up"),
        mode=dict(default="ce", choices=["ce", "fabricpath"]),
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec["vlan_id"] = dict(required=True, type="int")

    # 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,
    )

    warnings = list()
    result = {"changed": False}
    if warnings:
        result["warnings"] = warnings

    have = map_config_to_obj(module)
    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)
        result["commands"] = commands

    if commands:
        if not module.check_mode:
            load_config(module, commands)
        result["changed"] = True

    if want:
        check_declarative_intent_params(want, module, result)

    module.exit_json(**result)
Beispiel #30
0
def main():
    argument_spec = dict(
        interface=dict(required=True, type="str"),
        ospf=dict(required=True, type="str"),
        area=dict(required=True, type="str"),
        bfd=dict(
            choices=["enable", "disable", "default"],
            required=False,
            type="str",
        ),
        cost=dict(required=False, type="str"),
        hello_interval=dict(required=False, type="str"),
        dead_interval=dict(required=False, type="str"),
        passive_interface=dict(required=False, type="bool"),
        network=dict(required=False,
                     type="str",
                     choices=["broadcast", "point-to-point"]),
        message_digest=dict(required=False, type="bool"),
        message_digest_key_id=dict(required=False, type="str"),
        message_digest_algorithm_type=dict(required=False,
                                           type="str",
                                           choices=["md5", "default"]),
        message_digest_encryption_type=dict(
            required=False,
            type="str",
            choices=["cisco_type_7", "3des", "default"],
        ),
        message_digest_password=dict(required=False, type="str", no_log=True),
        state=dict(choices=["present", "absent"],
                   default="present",
                   required=False),
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_together=[[
            "message_digest_key_id",
            "message_digest_algorithm_type",
            "message_digest_encryption_type",
            "message_digest_password",
        ]],
        supports_check_mode=True,
    )

    # Normalize interface input data.
    #
    # * For port-channel and loopback interfaces expection is all lower case names.
    # * All other interfaces the expectation is an uppercase leading character
    #   followed by lower case characters.
    #
    if re.match(r"(port-channel|loopback)", module.params["interface"], re.I):
        module.params["interface"] = module.params["interface"].lower()
    else:
        module.params["interface"] = module.params["interface"].capitalize()

    warnings = list()
    result = {"changed": False, "commands": [], "warnings": warnings}

    for param in [
            "message_digest_encryption_type",
            "message_digest_algorithm_type",
            "message_digest_password",
    ]:
        if (module.params[param] == "default"
                and module.params["message_digest_key_id"] != "default"):
            module.exit_json(
                msg=
                "Use message_digest_key_id=default to remove an existing authentication configuration"
            )

    state = module.params["state"]
    args = PARAM_TO_COMMAND_KEYMAP.keys()

    existing = get_existing(module, args)
    proposed_args = dict((k, v) for k, v in module.params.items()
                         if v is not None and k in args)

    proposed = {}
    for key, value in proposed_args.items():
        if key != "interface":
            if str(value).lower() == "true":
                value = True
            elif str(value).lower() == "false":
                value = False
            elif str(value).lower() == "default":
                value = "default"
            elif key == "bfd":
                value = str(value).lower()
            if existing.get(key) or (not existing.get(key) and value):
                proposed[key] = value
            elif ("passive_interface" in key and existing.get(key) is None
                  and value is False):
                proposed[key] = value

    proposed["area"] = normalize_area(proposed["area"], module)
    if "hello_interval" in proposed and proposed["hello_interval"] == "10":
        proposed["hello_interval"] = "default"

    candidate = CustomNetworkConfig(indent=3)
    if state == "present":
        state_present(module, existing, proposed, candidate)
    elif (state == "absent" and existing.get("ospf") == proposed["ospf"]
          and existing.get("area") == proposed["area"]):
        state_absent(module, existing, proposed, candidate)

    if candidate:
        candidate = candidate.items_text()
        if not module.check_mode:
            load_config(module, candidate)
        result["changed"] = True
        result["commands"] = candidate

    module.exit_json(**result)