Beispiel #1
0
def main():
    argument_spec = dict(
        vrf=dict(required=True),
        afi=dict(required=True, choices=['ipv4', 'ipv6']),
        route_target_both_auto_evpn=dict(required=False, type='bool'),
        state=dict(choices=['present', 'absent'], default='present'),
        safi=dict(choices=['unicast', 'multicast'], removed_in_version="2.4"),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    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)
Beispiel #2
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        http=dict(aliases=['enable_http'], type='bool'),
        http_port=dict(type='int'),
        https=dict(aliases=['enable_https'], type='bool'),
        https_port=dict(type='int'),
        sandbox=dict(aliases=['enable_sandbox'], type='bool'),
        state=dict(default='present', choices=['started', 'stopped', 'present', 'absent'])
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

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

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

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

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

    module.exit_json(**result)
Beispiel #3
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        banner=dict(required=True, choices=['exec', 'motd']),
        text=dict(),
        state=dict(default='present', choices=['present', 'absent'])
    )

    argument_spec.update(nxos_argument_spec)

    required_if = [('state', 'present', ('text',))]

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

    warnings = list()

    check_args(module, warnings)

    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings
    want = map_params_to_obj(module)
    have = map_config_to_obj(module)
    commands = map_obj_to_commands(want, have, module)
    result['commands'] = commands

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

    module.exit_json(**result)
def main():
    argument_spec = dict(
        interface=dict(required=True, type='str'),
        description=dict(required=False, type='str'),
        host_reachability=dict(required=False, type='bool'),
        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)

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

    warnings = list()
    result = {'changed': False, 'commands': [], 'warnings': warnings}
    check_args(module, 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 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)
Beispiel #5
0
def main():
    argument_spec = dict(
        system_mode_maintenance=dict(required=False, type='bool'),
        system_mode_maintenance_dont_generate_profile=dict(required=False,
                                                           type='bool'),
        system_mode_maintenance_timeout=dict(required=False, type='str'),
        system_mode_maintenance_shutdown=dict(required=False, type='bool'),
        system_mode_maintenance_on_reload_reset_reason=dict(required=False,
                                                            choices=['hw_error', 'svc_failure', 'kern_failure',
                                                                     'wdog_timeout', 'fatal_error', 'lc_failure',
                                                                     'match_any', 'manual_reload']),
        state=dict(choices=['absent', 'present', 'default'],
                   default='present', required=False)
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[[
                               'system_mode_maintenance',
                               'system_mode_maintenance_dont_generate_profile',
                               'system_mode_maintenance_timeout',
                               'system_mode_maintenance_shutdown',
                               'system_mode_maintenance_on_reload_reset_reason'
                           ]],
                           required_one_of=[[
                               'system_mode_maintenance',
                               'system_mode_maintenance_dont_generate_profile',
                               'system_mode_maintenance_timeout',
                               'system_mode_maintenance_shutdown',
                               'system_mode_maintenance_on_reload_reset_reason'
                           ]],
                           supports_check_mode=True)

    warnings = list()

    state = module.params['state']
    mode = get_system_mode(module)
    commands = get_commands(module, state, mode)
    changed = False
    if commands:
        if module.check_mode:
            module.exit_json(changed=True, commands=commands)
        else:
            load_config(module, commands)
            changed = True

    result = {}
    result['changed'] = changed
    if module._verbosity > 0:
        final_system_mode = get_system_mode(module)
        result['final_system_mode'] = final_system_mode
        result['updates'] = commands

    result['warnings'] = warnings

    module.exit_json(**result)
Beispiel #6
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(aliases=['vrf']),
        description=dict(),
        vni=dict(type=str),
        rd=dict(type=str),
        admin_state=dict(default='up', choices=['up', 'down']),
        interfaces=dict(type='list'),
        associated_interfaces=dict(type='list'),
        delay=dict(default=10, type='int'),
        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),
        purge=dict(default=False, type='bool')
    )

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

    required_one_of = [['name', 'aggregate']]
    mutually_exclusive = [['name', 'aggregate']]
    module = AnsibleModule(argument_spec=argument_spec,
                           required_one_of=required_one_of,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

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

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

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

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

    check_declarative_intent_params(want, module, element_spec, result)

    module.exit_json(**result)
Beispiel #7
0
def main():
    argument_spec = dict(
        vni=dict(required=True, type='str'),
        route_distinguisher=dict(required=False, type='str'),
        route_target_both=dict(required=False, type='list'),
        route_target_import=dict(required=False, type='list'),
        route_target_export=dict(required=False, type='list'),
        state=dict(choices=['present', 'absent'], default='present', required=False)
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)
    results = dict(changed=False, warnings=warnings)

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

    proposed = {}
    for key, value in proposed_args.items():
        if key != 'vni':
            if value == 'true':
                value = True
            elif value == 'false':
                value = False
            if existing.get(key) != value:
                proposed[key] = value

    if state == 'present':
        commands, parents = state_present(module, existing, proposed)
    elif state == 'absent' and existing:
        commands, parents = state_absent(module, existing, proposed)

    if commands:
            candidate = CustomNetworkConfig(indent=3)
            candidate.add(commands, parents=parents)
            candidate = candidate.items_text()
            load_config(module, candidate)
            results['changed'] = True
            results['commands'] = candidate
    else:
        results['commands'] = []
    module.exit_json(**results)
Beispiel #8
0
def main():
    argument_spec = dict(
        flush_routes=dict(type='bool'),
        enforce_rtr_alert=dict(type='bool'),
        restart=dict(type='bool', default=False),
        state=dict(choices=['present', 'default'], default='present')
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    current = get_current(module)
    desired = get_desired(module)

    state = module.params['state']
    restart = module.params['restart']

    commands = list()

    if state == 'default':
        if current['flush_routes']:
            commands.append('no ip igmp flush-routes')
        if current['enforce_rtr_alert']:
            commands.append('no ip igmp enforce-router-alert')

    elif state == 'present':
        ldict = {'flush_routes': 'flush-routes', 'enforce_rtr_alert': 'enforce-router-alert'}
        for arg in ['flush_routes', 'enforce_rtr_alert']:
            if desired[arg] and not current[arg]:
                commands.append('ip igmp {0}'.format(ldict.get(arg)))
            elif current[arg] and not desired[arg]:
                commands.append('no ip igmp {0}'.format(ldict.get(arg)))

    result = {'changed': False, 'updates': commands, 'warnings': warnings}

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

    if module.params['restart']:
        cmd = {'command': 'restart igmp', 'output': 'text'}
        run_commands(module, cmd)

    module.exit_json(**result)
def main():
    element_spec = dict(
        prefix=dict(type='str', aliases=['address']),
        next_hop=dict(type='str'),
        vrf=dict(type='str', default='default'),
        tag=dict(type='str'),
        route_name=dict(type='str'),
        pref=dict(type='str', aliases=['admin_distance']),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['prefix'] = dict(required=True)
    aggregate_spec['next_hop'] = dict(required=True)

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

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

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

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

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

    want = map_params_to_obj(module)
    for w in want:
        prefix = normalize_prefix(module, w['prefix'])
        candidate = CustomNetworkConfig(indent=3)
        reconcile_candidate(module, candidate, prefix, w)

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

    module.exit_json(**result)
def main():
    argument_spec = dict(
        version=dict(type='str', choices=['1', '2'], required=True),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    version = module.params['version']

    existing = get_vtp_config(module)
    end_state = existing

    args = dict(version=version)

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

    commands = []
    if delta:
        commands.append(['vtp version {0}'.format(version)])

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

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

    module.exit_json(**results)
def main():
    argument_spec = dict(
        commands=dict(required=False, type='list'),
        mode=dict(required=True, choices=['maintenance', 'normal']),
        state=dict(choices=['absent', 'present'], default='present')
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    state = module.params['state']
    commands = module.params['commands'] or []

    if state == 'absent' and commands:
        module.fail_json(msg='when state is absent, no command can be used.')

    existing = invoke('get_existing', module)
    end_state = existing
    changed = False

    result = {}
    cmds = []
    if state == 'present' or (state == 'absent' and existing):
        cmds = invoke('state_%s' % state, module, existing, commands)

        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            if cmds:
                load_config(module, cmds)
                changed = True
                end_state = invoke('get_existing', module)

    result['changed'] = changed
    if module._verbosity > 0:
        end_state = invoke('get_existing', module)
        result['end_state'] = end_state
        result['existing'] = existing
        result['proposed'] = commands
        result['updates'] = cmds

    result['warnings'] = warnings

    module.exit_json(**result)
Beispiel #12
0
def main():
    argument_spec = dict(
        ssm_range=dict(required=True, type='list'),
    )

    argument_spec.update(nxos_argument_spec)

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

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

    ssm_range_list = module.params['ssm_range']
    for item in ssm_range_list:
        splitted_ssm_range = item.split('.')
        if len(splitted_ssm_range) != 4 and item != 'none' and item != 'default':
            module.fail_json(msg="Valid ssm_range values are multicast addresses "
                                 "or the keyword 'none' or the keyword 'default'.")

    args = PARAM_TO_COMMAND_KEYMAP.keys()

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

    proposed = {}
    for key, value in proposed_args.items():
        if key == 'ssm_range':
            if value[0] == 'default':
                if existing.get(key):
                    proposed[key] = 'default'
            else:
                v = sorted(set([str(i) for i in value]))
                ex = sorted(set([str(i) for i in existing.get(key)]))
                if v != ex:
                    proposed[key] = ' '.join(str(s) for s in v)

    candidate = CustomNetworkConfig(indent=3)
    get_commands(module, existing, proposed, candidate)

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

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),
        ipv4=dict(),
        ipv6=dict(),
        state=dict(default='present', choices=['present', 'absent'])
    )

    aggregate_spec = deepcopy(element_spec)

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

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

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

    required_one_of = [['name', 'aggregate']]
    mutually_exclusive = [['name', 'aggregate']]
    module = AnsibleModule(argument_spec=argument_spec,
                           required_one_of=required_one_of,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

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

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

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

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

    module.exit_json(**result)
Beispiel #14
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        hostname=dict(),
        domain_lookup=dict(type='bool'),

        # { name: <str>, vrf: <str> }
        domain_name=dict(type='list'),

        # {name: <str>, vrf: <str> }
        domain_search=dict(type='list'),

        # { server: <str>; vrf: <str> }
        name_servers=dict(type='list'),

        system_mtu=dict(type='int'),
        state=dict(default='present', choices=['present', 'absent'])
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

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

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

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

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

    module.exit_json(**result)
Beispiel #15
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        state=dict(default='present',
                   choices=['present', 'absent',
                            'enabled', 'disabled'])
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    HAS_LLDP = has_lldp(module)

    commands = []

    if module.params['state'] == 'absent' and HAS_LLDP:
        commands.append('no feature lldp')
    elif module.params['state'] == 'present' and not HAS_LLDP:
        commands.append('feature lldp')

    result['commands'] = commands

    if commands:
        # On N35 A8 images, some features return a yes/no prompt
        # on enablement or disablement. Bypass using terminal dont-ask
        commands.insert(0, 'terminal dont-ask')
        if not module.check_mode:
            load_config(module, commands)

        result['changed'] = True

    module.exit_json(**result)
Beispiel #16
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        dest=dict(choices=DEST_GROUP),
        name=dict(),
        facility=dict(),
        dest_level=dict(type='int', aliases=['level']),
        facility_level=dict(type='int'),
        state=dict(default='present', choices=['present', 'absent']),
        aggregate=dict(type='list')
    )

    argument_spec.update(nxos_argument_spec)

    required_if = [('dest', 'logfile', ['name'])]

    module = AnsibleModule(argument_spec=argument_spec,
                           required_if=required_if,
                           required_together=[['facility', 'facility_level']],
                           supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)

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

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

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

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

    module.exit_json(**result)
Beispiel #17
0
def main():
    argument_spec = dict(
        feature=dict(type='str', required=True),
        state=dict(choices=['enabled', 'disabled'], default='enabled')
    )

    argument_spec.update(nxos_argument_spec)

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

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

    feature = validate_feature(module)
    state = module.params['state'].lower()

    available_features = get_available_features(feature, module)
    if feature not in available_features:
        module.fail_json(
            msg='Invalid feature name.',
            features_currently_supported=available_features,
            invalid_feature=feature)
    else:
        existstate = available_features[feature]

        existing = dict(state=existstate)
        proposed = dict(state=state)
        results['changed'] = False

        cmds = get_commands(proposed, existing, state, module)

        if cmds:
            # On N35 A8 images, some features return a yes/no prompt
            # on enablement or disablement. Bypass using terminal dont-ask
            cmds.insert(0, 'terminal dont-ask')
            if not module.check_mode:
                load_config(module, cmds)
            results['changed'] = True

    results['commands'] = cmds
    module.exit_json(**results)
Beispiel #18
0
def main():
    argument_spec = dict(
        ospf=dict(required=True, type='str'),
        state=dict(choices=['present', 'absent'], default='present', required=False)
    )

    argument_spec.update(nxos_argument_spec)

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

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

    state = module.params['state']
    ospf = str(module.params['ospf'])

    existing = get_existing(module)
    proposed = dict(ospf=ospf)

    if not existing:
        existing_list = []
    else:
        existing_list = existing['ospf']

    candidate = CustomNetworkConfig(indent=3)
    if state == 'present' and ospf not in existing_list:
        state_present(module, proposed, candidate)
    if state == 'absent' and ospf in existing_list:
        state_absent(module, proposed, candidate)

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

    else:
        result['commands'] = []
    module.exit_json(**result)
def main():
    argument_spec = dict(
        nv_overlay_evpn=dict(required=True, type='bool'),
    )

    argument_spec.update(nxos_argument_spec)

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

    result = {'changed': False}

    warnings = list()
    if warnings:
        result['warnings'] = warnings

    config = get_config(module)
    commands = list()

    info = get_capabilities(module).get('device_info', {})
    os_platform = info.get('network_os_platform', '')

    if '3K' in os_platform:
        module.fail_json(msg='This module is not supported on Nexus 3000 series')

    if module.params['nv_overlay_evpn'] is True:
        if 'nv overlay evpn' not in config:
            commands.append('nv overlay evpn')
    elif 'nv overlay evpn' in config:
        commands.append('no nv overlay evpn')

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

    result['commands'] = commands

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

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)
    results = {'changed': False, 'commands': [], 'warnings': warnings}

    location = module.params['location']
    state = module.params['state']

    existing = get_snmp_location(module)
    commands = []

    if state == 'absent':
        if existing and existing['location'] == location:
            commands.append('no snmp-server location')
    elif state == 'present':
        if not existing or existing['location'] != location:
            commands.append('snmp-server location {0}'.format(location))

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

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

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

    warnings = list()
    check_args(module, warnings)

    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} {2}'.format(
                    snapshot1, snapshot2, 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 | include {}'.format(
                    module.params['snapshot_name'])
                content = execute_show_command(command, module)[0]
                if content:
                    write_on_file(content, module.params['snapshot_name'],
                                  module)

    module.exit_json(**result)
Beispiel #23
0
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'),
        associated_interfaces=dict(type='list'),
        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(choices=['ce', 'fabricpath'], required=False),
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['vlan_id'] = dict(required=True)

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

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

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

    required_one_of = [['vlan_id', 'aggregate', 'vlan_range']]
    mutually_exclusive = [['vlan_id', 'aggregate'],
                          ['vlan_range', 'name'],
                          ['vlan_id', 'vlan_range']]

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

    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 #24
0
def reboot(module):
    cmds = 'terminal dont-ask ; reload'
    opts = {'ignore_timeout': True}
    load_config(module, cmds, False, opts)
Beispiel #25
0
def main():
    argument_spec = dict(
        group=dict(required=True, type='str'),
        mode=dict(required=False,
                  choices=['on', 'active', 'passive'],
                  default='on',
                  type='str'),
        min_links=dict(required=False, default=None, type='str'),
        members=dict(required=False, default=None, type='list'),
        force=dict(required=False,
                   default='false',
                   type='str',
                   choices=['true', 'false']),
        state=dict(required=False,
                   choices=['absent', 'present'],
                   default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

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

    group = str(module.params['group'])
    mode = module.params['mode']
    min_links = module.params['min_links']
    members = module.params['members']
    state = module.params['state']

    if str(module.params['force']).lower() == 'true':
        force = True
    elif module.params['force'] == 'false':
        force = False

    if ((min_links or mode) and (not members and state == 'present')):
        module.fail_json(msg='"members" is required when state=present and '
                         '"min_links" or "mode" are provided')

    args = ['group', 'members', 'min_links', 'mode']

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

    commands = []

    if state == 'absent' and existing:
        commands = state_absent(module, existing, proposed)
    elif state == 'present':
        commands = state_present(module, existing, proposed, interface_exist,
                                 force, warnings)

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

    results['commands'] = cmds
    module.exit_json(**results)
Beispiel #26
0
def main():
    argument_spec = dict(
        user=dict(required=True, type='str'),
        group=dict(type='str', required=True),
        pwd=dict(type='str'),
        privacy=dict(type='str'),
        authentication=dict(choices=['md5', 'sha']),
        encrypt=dict(type='bool'),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           required_together=[['authentication', 'pwd'],
                                              ['encrypt', 'privacy']],
                           supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)
    results = {'changed': False, 'commands': [], 'warnings': warnings}

    user = module.params['user']
    group = module.params['group']
    pwd = module.params['pwd']
    privacy = module.params['privacy']
    encrypt = module.params['encrypt']
    authentication = module.params['authentication']
    state = module.params['state']

    if privacy and encrypt:
        if not pwd and authentication:
            module.fail_json(msg='pwd and authentication must be provided '
                             'when using privacy and encrypt')

    if group and group not in get_snmp_groups(module):
        module.fail_json(msg='group not configured yet on switch.')

    existing = get_snmp_user(user, module)

    if existing:
        if group not in existing['group']:
            existing['group'] = None
        else:
            existing['group'] = group

    commands = []

    if state == 'absent' and existing:
        commands.append(remove_snmp_user(user))

    elif state == 'present':
        new = False
        reset = False

        args = dict(user=user,
                    pwd=pwd,
                    group=group,
                    privacy=privacy,
                    encrypt=encrypt,
                    authentication=authentication)
        proposed = dict((k, v) for k, v in args.items() if v is not None)

        if not existing:
            if encrypt:
                proposed['encrypt'] = 'aes-128'
            commands.append(config_snmp_user(proposed, user, reset, new))

        elif existing:
            if encrypt and not existing['encrypt'].startswith('aes'):
                reset = True
                proposed['encrypt'] = 'aes-128'

            elif encrypt:
                proposed['encrypt'] = 'aes-128'

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

            if delta.get('pwd'):
                delta['authentication'] = authentication

            if delta:
                delta['group'] = group

            command = config_snmp_user(delta, user, reset, new)
            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(
        vrf=dict(required=True),
        interface=dict(type='str', required=True),
        state=dict(default='present', choices=['present', 'absent'], required=False),
    )

    argument_spec.update(nxos_argument_spec)

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

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

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

    device_info = get_capabilities(module)
    network_api = device_info.get('network_api', 'nxapi')

    current_vrfs = get_vrf_list(module)
    if vrf not in current_vrfs:
        warnings.append("The VRF is not present/active on the device. "
                        "Use nxos_vrf to fix this.")

    intf_type = get_interface_type(interface)
    if (intf_type != 'ethernet' and network_api == 'cliconf'):
        if is_default(interface, module) == 'DNE':
            module.fail_json(msg="interface does not exist on switch. Verify "
                                 "switch platform or create it first with "
                                 "nxos_interface if it's a logical interface")

    mode = get_interface_mode(interface, intf_type, module)
    if mode == 'layer2':
        module.fail_json(msg='Ensure interface is a Layer 3 port before '
                             'configuring a VRF on an interface. You can '
                             'use nxos_interface')

    proposed = dict(interface=interface, vrf=vrf)

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

    if not existing['vrf']:
        pass
    elif vrf != existing['vrf'] and state == 'absent':
        module.fail_json(msg='The VRF you are trying to remove '
                             'from the interface does not exist '
                             'on that interface.',
                         interface=interface, proposed_vrf=vrf,
                         existing_vrf=existing['vrf'])

    commands = []
    if existing:
        if state == 'absent':
            if existing and vrf == existing['vrf']:
                command = 'no vrf member {0}'.format(vrf)
                commands.append(command)

        elif state == 'present':
            if existing['vrf'] != vrf:
                command = 'vrf member {0}'.format(vrf)
                commands.append(command)

    if commands:
        commands.insert(0, 'interface {0}'.format(interface))

    if commands:
        if module.check_mode:
            module.exit_json(changed=True, commands=commands)
        else:
            load_config(module, commands)
            changed = True
            changed_vrf = get_interface_info(interface, module)
            end_state = dict(interface=interface, vrf=changed_vrf)
            if 'configure' in commands:
                commands.pop(0)

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

    module.exit_json(**results)
Beispiel #28
0
def main():
    argument_spec = dict(
        rp_address=dict(required=True, type='str'),
        group_list=dict(required=False, type='str'),
        prefix_list=dict(required=False, type='str'),
        route_map=dict(required=False, type='str'),
        bidir=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,
                           mutually_exclusive=[['group_list', 'route_map'],
                                               ['group_list', 'prefix_list'],
                                               ['route_map', 'prefix_list']],
                           supports_check_mode=True)

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

    state = module.params['state']

    args = ['rp_address', 'group_list', 'prefix_list', 'route_map', 'bidir']

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

    if module.params['group_list']:
        existing = get_existing(module, args, True)
        proposed = get_proposed(proposed_args, existing)

    else:
        existing = get_existing(module, args, False)
        proposed = get_proposed(proposed_args, existing)

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

    if candidate:
        candidate = candidate.items_text()
        result['commands'] = candidate
        result['changed'] = True
        msgs = load_config(module, candidate, True)
        if msgs:
            for item in msgs:
                if item:
                    if isinstance(item, dict):
                        err_str = item['clierror']
                    else:
                        err_str = item
                    if 'No policy was configured' in err_str:
                        if state == 'absent':
                            addr = module.params['rp_address']
                            new_cmd = 'no ip pim rp-address {0}'.format(addr)
                            load_config(module, new_cmd)

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

    aggregate_spec = deepcopy(element_spec)

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

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

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

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

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

    warnings = list()
    if module.params['password'] and not module.params['configured_password']:
        warnings.append(
            'The "password" argument is used to authenticate the current connection. '
            + 'To set a user password use "configured_password" instead.')

    result = {'changed': False}
    result['warnings'] = 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:
            load_config(module, commands)
        result['changed'] = True

    module.exit_json(**result)
def main():
    argument_spec = dict(
        interface=dict(required=True, type='str'),
        ospf=dict(required=True, type='str'),
        area=dict(required=True, 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'),
        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']),
        message_digest_encryption_type=dict(required=False,
                                            type='str',
                                            choices=['cisco_type_7', '3des']),
        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()
    check_args(module, warnings)
    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':
            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'
            if existing.get(key) or (not existing.get(key) and value):
                proposed[key] = value

    proposed['area'] = normalize_area(proposed['area'], module)

    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()
        load_config(module, candidate)
        result['changed'] = True
        result['commands'] = candidate

    module.exit_json(**result)
Beispiel #31
0
def main():
    argument_spec = dict(
        asn=dict(required=True, type='str'),
        vrf=dict(required=False, type='str', default='default'),
        neighbor=dict(required=True, type='str'),
        description=dict(required=False, type='str'),
        bfd=dict(required=False, type='str', choices=['enable', 'disable']),
        capability_negotiation=dict(required=False, type='bool'),
        connected_check=dict(required=False, type='bool'),
        dynamic_capability=dict(required=False, type='bool'),
        ebgp_multihop=dict(required=False, type='str'),
        local_as=dict(required=False, type='str'),
        log_neighbor_changes=dict(required=False, type='str', choices=['enable', 'disable', 'inherit']),
        low_memory_exempt=dict(required=False, type='bool'),
        maximum_peers=dict(required=False, type='str'),
        pwd=dict(required=False, type='str'),
        pwd_type=dict(required=False, type='str', choices=['3des', 'cisco_type_7', 'default']),
        remote_as=dict(required=False, type='str'),
        remove_private_as=dict(required=False, type='str', choices=['enable', 'disable', 'all', 'replace-as']),
        shutdown=dict(required=False, type='bool'),
        suppress_4_byte_as=dict(required=False, type='bool'),
        timers_keepalive=dict(required=False, type='str'),
        timers_holdtime=dict(required=False, type='str'),
        transport_passive_only=dict(required=False, type='bool'),
        update_source=dict(required=False, type='str'),
        state=dict(choices=['present', 'absent'], default='present', required=False)
    )
    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_together=[['timers_holdtime', 'timers_keepalive'], ['pwd', 'pwd_type']],
        supports_check_mode=True,
    )

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

    state = module.params['state']

    if module.params['pwd_type'] == 'default':
        module.params['pwd_type'] = '0'

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

    if existing.get('asn') and state == 'present':
        if existing['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)
    proposed = {}
    for key, value in proposed_args.items():
        if key not in ['asn', 'vrf', 'neighbor', 'pwd_type']:
            if str(value).lower() == 'default':
                value = PARAM_TO_DEFAULT_KEYMAP.get(key, 'default')
            if key == 'bfd':
                if existing.get('bfd', 'disable') != value:
                    proposed[key] = value
            elif 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, existing, proposed, 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)
Beispiel #32
0
def main():
    argument_spec = dict(
        interface=dict(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(choices=['prefix', 'routemap']),
        jp_type_in=dict(choices=['prefix', 'routemap']),
        border=dict(type='bool', default=False),
        neighbor_policy=dict(type='str'),
        neighbor_type=dict(choices=['prefix', 'routemap']),
        state=dict(choices=['present', 'absent', 'default'],
                   default='present'),
    )
    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)
    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']
    hello_interval = module.params['hello_interval']

    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)

    if hello_interval:
        proposed['hello_interval'] = str(proposed['hello_interval'] * 1000)

    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 #33
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 #34
0
def main():
    argument_spec = dict(
        domain=dict(required=True, type='str'),
        role_priority=dict(required=False, type='str'),
        system_priority=dict(required=False, type='str'),
        pkl_src=dict(required=False),
        pkl_dest=dict(required=False),
        pkl_vrf=dict(required=False),
        peer_gw=dict(required=False, type='bool'),
        auto_recovery=dict(required=False, type='bool'),
        delay_restore=dict(required=False, 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()
    check_args(module, warnings)
    results = {'changed': False, 'warnings': warnings}

    domain = module.params['domain']
    role_priority = module.params['role_priority']
    system_priority = module.params['system_priority']
    pkl_src = module.params['pkl_src']
    pkl_dest = module.params['pkl_dest']
    pkl_vrf = module.params['pkl_vrf']
    peer_gw = module.params['peer_gw']
    auto_recovery = module.params['auto_recovery']
    delay_restore = module.params['delay_restore']
    state = module.params['state']

    args = dict(domain=domain,
                role_priority=role_priority,
                system_priority=system_priority,
                pkl_src=pkl_src,
                pkl_dest=pkl_dest,
                pkl_vrf=pkl_vrf,
                peer_gw=peer_gw,
                auto_recovery=auto_recovery,
                delay_restore=delay_restore)

    if not pkl_dest:
        if pkl_src:
            module.fail_json(msg='dest IP for peer-keepalive is required'
                             ' when src IP is present')
        elif pkl_vrf:
            if pkl_vrf != 'management':
                module.fail_json(
                    msg='dest and src IP for peer-keepalive are required'
                    ' when vrf is present')
            else:
                module.fail_json(msg='dest IP for peer-keepalive is required'
                                 ' when vrf is present')
    if pkl_vrf:
        if pkl_vrf.lower() not in get_vrf_list(module):
            module.fail_json(msg='The VRF you are trying to use for the peer '
                             'keepalive link is not on device yet. Add it'
                             ' first, please.')
    proposed = dict((k, v) for k, v in args.items() if v is not None)
    existing = get_vpc(module)

    commands = []
    if state == 'present':
        delta = {}
        for key, value in proposed.items():
            if str(value).lower() == 'default':
                value = PARAM_TO_DEFAULT_KEYMAP.get(key)
            if existing.get(key) != value:
                delta[key] = value
        if delta:
            command = get_commands_to_config_vpc(module, delta, domain,
                                                 existing)
            commands.append(command)
    elif state == 'absent':
        if existing:
            if domain != existing['domain']:
                module.fail_json(msg="You are trying to remove a domain that "
                                 "does not exist on the device")
            else:
                commands.append('terminal dont-ask')
                commands.append('no vpc domain {0}'.format(domain))

    cmds = flatten_list(commands)
    results['commands'] = cmds

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

    module.exit_json(**results)
def main():
    argument_spec = dict(
        interface=dict(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(choices=['prefix', 'routemap']),
        jp_type_in=dict(choices=['prefix', 'routemap']),
        border=dict(type='bool', default=False),
        neighbor_policy=dict(type='str'),
        neighbor_type=dict(choices=['prefix', 'routemap']),
        state=dict(choices=['present', 'absent', 'default'], default='present'),
    )
    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)
    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']
    hello_interval = module.params['hello_interval']

    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)

    if hello_interval:
        proposed['hello_interval'] = str(proposed['hello_interval'] * 1000)

    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 #36
0
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'),
        maximum_paths=dict(required=False, type='str'),
        maximum_paths_ibgp=dict(required=False, type='str'),
        networks=dict(required=False, type='list'),
        next_hop_route_map=dict(required=False, type='str'),
        redistribute=dict(required=False, type='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()
    check_args(module, warnings)
    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()
        load_config(module, candidate)
        result['changed'] = True
        result['commands'] = candidate
    else:
        result['commands'] = []

    module.exit_json(**result)
def main():
    argument_spec = dict(
        interface=dict(required=True, type='str'),
        ospf=dict(required=True, type='str'),
        area=dict(required=True, 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'),
        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()
    check_args(module, warnings)
    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'
            if existing.get(key) or (not existing.get(key) and value):
                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()
        load_config(module, candidate)
        result['changed'] = True
        result['commands'] = candidate

    module.exit_json(**result)
Beispiel #38
0
def main():
    argument_spec = dict(
        group=dict(required=True, type='str'),
        interface=dict(required=True),
        version=dict(choices=['1', '2'], default='2', required=False),
        priority=dict(type='str', required=False),
        preempt=dict(type='str', choices=['disabled', 'enabled'], required=False),
        vip=dict(type='str', required=False),
        auth_type=dict(choices=['text', 'md5'], required=False),
        auth_string=dict(type='str', required=False),
        state=dict(choices=['absent', 'present'], required=False, default='present')
    )

    argument_spec.update(nxos_argument_spec)

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

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

    interface = module.params['interface'].lower()
    group = module.params['group']
    version = module.params['version']
    state = module.params['state']
    priority = module.params['priority']
    preempt = module.params['preempt']
    vip = module.params['vip']
    auth_type = module.params['auth_type']
    auth_string = module.params['auth_string']

    device_info = get_capabilities(module)
    network_api = device_info.get('network_api', 'nxapi')

    if state == 'present' and not vip:
        module.fail_json(msg='the "vip" param is required when state=present')

    for param in ['group', 'priority']:
        if module.params[param] is not None:
            validate_params(param, module)

    intf_type = get_interface_type(interface)
    if (intf_type != 'ethernet' and network_api == 'cliconf'):
        if is_default(interface, module) == 'DNE':
            module.fail_json(msg='That interface does not exist yet. Create '
                                 'it first.', interface=interface)
        if intf_type == 'loopback':
            module.fail_json(msg="Loopback interfaces don't support HSRP.",
                             interface=interface)

    mode = get_interface_mode(interface, intf_type, module)
    if mode == 'layer2':
        module.fail_json(msg='That interface is a layer2 port.\nMake it '
                             'a layer 3 port first.', interface=interface)

    if auth_type or auth_string:
        if not (auth_type and auth_string):
            module.fail_json(msg='When using auth parameters, you need BOTH '
                                 'auth_type AND auth_string.')

    args = dict(group=group, version=version, priority=priority,
                preempt=preempt, vip=vip, auth_type=auth_type,
                auth_string=auth_string)

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

    existing = get_hsrp_group(group, interface, module)

    # This will enforce better practice with md5 and hsrp version.
    if proposed.get('auth_type', None) == 'md5':
        if proposed['version'] == '1':
            module.fail_json(msg="It's recommended to use HSRP v2 "
                                 "when auth_type=md5")

    elif not proposed.get('auth_type', None) and existing:
        if (proposed['version'] == '1' and
                existing['auth_type'] == 'md5'):
            module.fail_json(msg="Existing auth_type is md5. It's recommended "
                                 "to use HSRP v2 when using md5")

    commands = []
    if state == 'present':
        delta = dict(
            set(proposed.items()).difference(existing.items()))
        if delta:
            command = get_commands_config_hsrp(delta, interface, args)
            commands.extend(command)

    elif state == 'absent':
        if existing:
            command = get_commands_remove_hsrp(group, interface)
            commands.extend(command)

    if commands:
        if module.check_mode:
            module.exit_json(**results)
        else:
            load_config(module, commands)

            # validate IP
            if network_api == 'cliconf' and state == 'present':
                commands.insert(0, 'config t')
                body = run_commands(module, commands)
                validate_config(body, vip, module)

            results['changed'] = True

            if 'configure' in commands:
                commands.pop(0)

    results['commands'] = commands
    module.exit_json(**results)
def main():
    """ main entry point for module execution
    """
    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()
    nxos_check_args(module, warnings)

    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 #40
0
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(interface=dict(required=True),
                         addr=dict(required=False),
                         version=dict(required=False,
                                      choices=['v4', 'v6'],
                                      default='v4'),
                         mask=dict(type='str', required=False),
                         dot1q=dict(required=False, default=0, type='int'),
                         tag=dict(required=False, default=0, type='int'),
                         state=dict(required=False,
                                    default='present',
                                    choices=['present', 'absent']),
                         allow_secondary=dict(required=False,
                                              default=False,
                                              type='bool'))

    argument_spec.update(nxos_argument_spec)

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

    if not HAS_IPADDRESS:
        module.fail_json(
            msg=
            "ipaddress is required for this module. Run 'pip install ipaddress' for install."
        )

    warnings = list()

    addr = module.params['addr']
    version = module.params['version']
    mask = module.params['mask']
    dot1q = module.params['dot1q']
    tag = module.params['tag']
    allow_secondary = module.params['allow_secondary']
    interface = module.params['interface'].lower()
    state = module.params['state']

    intf_type = get_interface_type(interface)
    validate_params(addr, interface, mask, dot1q, tag, allow_secondary,
                    version, state, intf_type, module)

    mode = get_interface_mode(interface, intf_type, module)
    if mode == 'layer2':
        module.fail_json(msg='That interface is a layer2 port.\nMake it '
                         'a layer 3 port first.',
                         interface=interface)

    existing = get_ip_interface(interface, version, module)

    dot1q_tag = get_dot1q_id(interface, module)
    if dot1q_tag > 1:
        existing['dot1q'] = dot1q_tag

    args = dict(addr=addr,
                mask=mask,
                dot1q=dot1q,
                tag=tag,
                interface=interface,
                allow_secondary=allow_secondary)
    proposed = dict((k, v) for k, v in args.items() if v is not None)
    commands = []
    changed = False
    end_state = existing

    commands = ['interface {0}'.format(interface)]
    if state == 'absent':
        if existing['addresses']:
            if find_same_addr(existing, addr, mask):
                command = get_remove_ip_config_commands(
                    interface, addr, mask, existing, version)
                commands.append(command)
        if 'dot1q' in existing and existing['dot1q'] > 1:
            command = 'no encapsulation dot1Q {0}'.format(existing['dot1q'])
            commands.append(command)
    elif state == 'present':
        if not find_same_addr(
                existing, addr, mask, full=True, tag=tag, version=version):
            command = get_config_ip_commands(proposed, interface, existing,
                                             version)
            commands.append(command)
        if 'dot1q' not in existing and (
                intf_type in ['ethernet', 'portchannel'] and "." in interface):
            command = 'encapsulation dot1Q {0}'.format(proposed['dot1q'])
            commands.append(command)
    if len(commands) < 2:
        del commands[0]
    cmds = flatten_list(commands)
    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            load_config(module, cmds)
            changed = True
            end_state = get_ip_interface(interface, version, module)
            if 'configure' in cmds:
                cmds.pop(0)

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

    module.exit_json(**results)
Beispiel #42
0
def main():
    argument_spec = dict(
        mtu=dict(type='str'),
        interface=dict(type='str'),
        sysmtu=dict(type='str'),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           required_together=[['mtu', 'interface']],
                           supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)

    interface = module.params['interface']
    mtu = module.params['mtu']
    sysmtu = module.params['sysmtu']
    state = module.params['state']

    if sysmtu and (interface or mtu):
        module.fail_json(msg='Proper usage-- either just use the sysmtu param '
                         'or use interface AND mtu params')

    if interface:
        intf_type = get_interface_type(interface)
        if intf_type != 'ethernet':
            if is_default(interface, module) == 'DNE':
                module.fail_json(msg='Invalid interface.  It does not exist '
                                 'on the switch.')

        existing = get_mtu(interface, module)
    else:
        existing = get_system_mtu(module)

    if interface and mtu:
        if intf_type == 'loopback':
            module.fail_json(msg='Cannot set MTU for loopback interface.')
        mode = get_interface_mode(interface, intf_type, module)
        if mode == 'layer2':
            if intf_type in ['ethernet', 'portchannel']:
                if mtu not in [existing['sysmtu'], '1500']:
                    module.fail_json(msg='MTU on L2 interfaces can only be set'
                                     ' to the system default (1500) or '
                                     'existing sysmtu value which is '
                                     ' {0}'.format(existing['sysmtu']))
        elif mode == 'layer3':
            if intf_type in ['ethernet', 'portchannel', 'svi']:
                if ((int(mtu) < 576 or int(mtu) > 9216)
                        or ((int(mtu) % 2) != 0)):
                    module.fail_json(msg='Invalid MTU for Layer 3 interface'
                                     'needs to be an even number between'
                                     '576 and 9216')
    if sysmtu:
        if ((int(sysmtu) < 576 or int(sysmtu) > 9216
             or ((int(sysmtu) % 2) != 0))):
            module.fail_json(msg='Invalid MTU- needs to be an even '
                             'number between 576 and 9216')

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

    changed = False
    end_state = existing
    commands = []

    if state == 'present':
        if delta:
            command = get_commands_config_mtu(delta, interface)
            commands.append(command)

    elif state == 'absent':
        common = set(proposed.items()).intersection(existing.items())
        if common:
            command = get_commands_remove_mtu(dict(common), interface)
            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)
            if interface:
                end_state = get_mtu(interface, module)
            else:
                end_state = get_system_mtu(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 #43
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'),
        passive_interface=dict(required=False, type='bool'),
        state=dict(choices=['present', 'absent'], default='present', required=False),
        include_defaults=dict(default=True),
        config=dict(),
        save=dict(type='bool', default=False)
    )

    argument_spec.update(nxos_argument_spec)

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

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

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

    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()
        load_config(module, candidate)
        result['changed'] = True
        result['commands'] = candidate

    else:
        result['commands'] = []
    module.exit_json(**result)
Beispiel #44
0
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)
Beispiel #45
0
def main():
    argument_spec = dict(portchannel=dict(required=True, type='str'),
                         vpc=dict(required=False, type='str'),
                         peer_link=dict(required=False, type='bool'),
                         state=dict(choices=['absent', 'present'],
                                    default='present'))

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[['vpc', 'peer_link']],
                           supports_check_mode=True)

    warnings = list()
    commands = []
    check_args(module, warnings)
    results = {'changed': False, 'warnings': warnings}

    portchannel = module.params['portchannel']
    vpc = module.params['vpc']
    peer_link = module.params['peer_link']
    state = module.params['state']

    args = {'portchannel': portchannel, 'vpc': vpc, 'peer-link': peer_link}
    active_peer_link = None

    if portchannel not in get_portchannel_list(module):
        if not portchannel.isdigit() or int(
                portchannel) not in get_portchannel_list(module):
            module.fail_json(msg="The portchannel you are trying to make a"
                             " VPC or PL is not created yet. "
                             "Create it first!")
    if vpc:
        mapping = get_existing_portchannel_to_vpc_mappings(module)

        if vpc in mapping and portchannel != mapping[vpc].strip('Po'):
            module.fail_json(msg="This vpc is already configured on "
                             "another portchannel. Remove it first "
                             "before trying to assign it here. ",
                             existing_portchannel=mapping[vpc])

        for vpcid, existing_pc in mapping.items():
            if portchannel == existing_pc.strip('Po') and vpcid != vpc:
                module.fail_json(msg="This portchannel already has another"
                                 " VPC configured. Remove it first "
                                 "before assigning this one",
                                 existing_vpc=vpcid)

        if peer_link_exists(module):
            active_peer_link = get_active_vpc_peer_link(module)
            if active_peer_link[-2:] == portchannel:
                module.fail_json(msg="That port channel is the current "
                                 "PEER LINK. Remove it if you want it"
                                 " to be a VPC")
        config_value = vpc

    elif peer_link is not None:
        if peer_link_exists(module):
            active_peer_link = get_active_vpc_peer_link(module)[2::]
            if active_peer_link != portchannel:
                if peer_link:
                    module.fail_json(
                        msg="A peer link already exists on"
                        " the device. Remove it first",
                        current_peer_link='Po{0}'.format(active_peer_link))
        config_value = 'peer-link'

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

    if state == 'present':
        delta = dict(set(proposed.items()).difference(existing.items()))
        if delta:
            commands = state_present(portchannel, delta, config_value,
                                     existing)

    elif state == 'absent' and existing:
        commands = state_absent(portchannel, existing)

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

    results['commands'] = cmds
    module.exit_json(**results)
def main():
    element_spec = dict(
        name=dict(required=True, type='str'),
        pwwn=dict(type='str'),
        remove=dict(type='bool', default=False)
    )

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

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

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

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

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

    # Step 0.0: Validate syntax of name and pwwn
    #       Also validate syntax of rename arguments
    if da is not None:
        for eachdict in da:
            name = eachdict['name']
            pwwn = eachdict['pwwn']
            remove = eachdict['remove']
            if pwwn is not None:
                pwwn = pwwn.lower()
            if not remove:
                if pwwn is None:
                    module.fail_json(
                        msg='This device alias name ' +
                        str(name) +
                        ' which needs to be added, doenst have pwwn specified . Please specify a valid pwwn')
                if not isNameValid(name):
                    module.fail_json(msg='This pwwn name is invalid : ' + str(name) +
                                     '. Note that name cannot be more than 64 chars and it should start with a letter')
                if not isPwwnValid(pwwn):
                    module.fail_json(msg='This pwwn is invalid : ' + str(pwwn) + '. Please check that its a valid pwwn')
    if rename is not None:
        for eachdict in rename:
            oldname = eachdict['old_name']
            newname = eachdict['new_name']
            if not isNameValid(oldname):
                module.fail_json(msg='This pwwn name is invalid : ' + str(oldname) +
                                 '. Note that name cannot be more than 64 chars and it should start with a letter')
            if not isNameValid(newname):
                module.fail_json(msg='This pwwn name is invalid : ' + str(newname) +
                                 '. Note that name cannot be more than 64 chars and it should start with a letter')

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

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

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

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

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

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

    cmds = flatten_list(commands)

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

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

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

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

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

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

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

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

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

    result['messages'] = messages
    result['commands'] = commands_to_execute
    result['warnings'] = warnings
    module.exit_json(**result)
Beispiel #47
0
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))

    argument_spec.update(nxos_argument_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 + " " + 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 #48
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()
    check_args(module, warnings)
    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)
def main():
    argument_spec = dict(
        portchannel=dict(required=True, type='str'),
        vpc=dict(required=False, type='str'),
        peer_link=dict(required=False, type='bool'),
        state=dict(choices=['absent', 'present'], default='present')
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[['vpc', 'peer_link']],
                           supports_check_mode=True)

    warnings = list()
    commands = []
    check_args(module, warnings)
    results = {'changed': False, 'warnings': warnings}

    portchannel = module.params['portchannel']
    vpc = module.params['vpc']
    peer_link = module.params['peer_link']
    state = module.params['state']

    args = {'portchannel': portchannel, 'vpc': vpc, 'peer-link': peer_link}
    active_peer_link = None

    if portchannel not in get_portchannel_list(module):
        if not portchannel.isdigit() or int(portchannel) not in get_portchannel_list(module):
            module.fail_json(msg="The portchannel you are trying to make a"
                                 " VPC or PL is not created yet. "
                                 "Create it first!")
    if vpc:
        mapping = get_existing_portchannel_to_vpc_mappings(module)

        if vpc in mapping and portchannel != mapping[vpc].strip('Po'):
            module.fail_json(msg="This vpc is already configured on "
                                 "another portchannel. Remove it first "
                                 "before trying to assign it here. ",
                             existing_portchannel=mapping[vpc])

        for vpcid, existing_pc in mapping.items():
            if portchannel == existing_pc.strip('Po') and vpcid != vpc:
                module.fail_json(msg="This portchannel already has another"
                                     " VPC configured. Remove it first "
                                     "before assigning this one",
                                 existing_vpc=vpcid)

        if peer_link_exists(module):
            active_peer_link = get_active_vpc_peer_link(module)
            if active_peer_link[-2:] == portchannel:
                module.fail_json(msg="That port channel is the current "
                                     "PEER LINK. Remove it if you want it"
                                     " to be a VPC")
        config_value = vpc

    elif peer_link is not None:
        if peer_link_exists(module):
            active_peer_link = get_active_vpc_peer_link(module)[2::]
            if active_peer_link != portchannel:
                if peer_link:
                    module.fail_json(msg="A peer link already exists on"
                                         " the device. Remove it first",
                                     current_peer_link='Po{0}'.format(active_peer_link))
        config_value = 'peer-link'

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

    if state == 'present':
        delta = dict(set(proposed.items()).difference(existing.items()))
        if delta:
            commands = state_present(portchannel, delta, config_value, existing)

    elif state == 'absent' and existing:
        commands = state_absent(portchannel, existing)

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

    results['commands'] = cmds
    module.exit_json(**results)
Beispiel #50
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        src=dict(type='path'),
        replace_src=dict(),
        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact',
                                            'none']),
        replace=dict(default='line', choices=['line', 'block', 'config']),
        running_config=dict(aliases=['config']),
        intended_config=dict(),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save_when=dict(choices=['always', 'never', 'modified'],
                       default='never'),
        diff_against=dict(choices=['running', 'startup', 'intended']),
        diff_ignore_lines=dict(type='list'),

        # save is deprecated as of ans2.4, use save_when instead
        save=dict(default=False, type='bool', removed_in_version='2.4'),

        # force argument deprecated in ans2.2
        force=dict(default=False, type='bool', removed_in_version='2.2'))

    argument_spec.update(nxos_argument_spec)

    mutually_exclusive = [('lines', 'src', 'replace_src'), ('parents', 'src'),
                          ('save', 'save_when')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('replace', 'config', ['replace_src']),
                   ('diff_against', 'intended', ['intended_config'])]

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

    warnings = list()
    nxos_check_args(module, warnings)

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

    config = None

    info = get_capabilities(module).get('device_info', {})
    os_platform = info.get('network_os_platform', '')

    if module.params['replace'] == 'config':
        if '9K' not in os_platform:
            module.fail_json(
                msg=
                'replace: config is supported only for Nexus 9K series switches'
            )

    if module.params['replace_src']:
        if module.params['replace'] != 'config':
            module.fail_json(
                msg='replace: config is required with replace_src')

    if module.params['backup'] or (module._diff and
                                   module.params['diff_against'] == 'running'):
        contents = get_config(module)
        config = NetworkConfig(indent=2, contents=contents)
        if module.params['backup']:
            result['__backup__'] = contents

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

        candidate = get_candidate(module)

        if match != 'none' and replace != 'config':
            config = get_running_config(module, config)
            path = module.params['parents']
            configobjs = candidate.difference(config,
                                              match=match,
                                              replace=replace,
                                              path=path)
        else:
            configobjs = candidate.items

        if configobjs:
            commands = dumps(configobjs, 'commands').split('\n')

            if module.params['before']:
                commands[:0] = module.params['before']

            if module.params['after']:
                commands.extend(module.params['after'])

            result['commands'] = commands
            result['updates'] = commands

            if not module.check_mode:
                load_config(module, commands)

            result['changed'] = True

    running_config = None
    startup_config = None

    diff_ignore_lines = module.params['diff_ignore_lines']

    if module.params['save']:
        module.params['save_when'] = 'always'

    if module.params['save_when'] != 'never':
        output = execute_show_commands(
            module, ['show running-config', 'show startup-config'])

        running_config = NetworkConfig(indent=1,
                                       contents=output[0],
                                       ignore_lines=diff_ignore_lines)
        startup_config = NetworkConfig(indent=1,
                                       contents=output[1],
                                       ignore_lines=diff_ignore_lines)

        if running_config.sha1 != startup_config.sha1 or module.params[
                'save_when'] == 'always':
            result['changed'] = True
            if not module.check_mode:
                cmd = {
                    'command': 'copy running-config startup-config',
                    'output': 'text'
                }
                run_commands(module, [cmd])
            else:
                module.warn(
                    'Skipping command `copy running-config startup-config` '
                    'due to check_mode.  Configuration not copied to '
                    'non-volatile storage')

    if module._diff:
        if not running_config:
            output = execute_show_commands(module, 'show running-config')
            contents = output[0]
        else:
            contents = running_config.config_text

        # recreate the object in order to process diff_ignore_lines
        running_config = NetworkConfig(indent=1,
                                       contents=contents,
                                       ignore_lines=diff_ignore_lines)

        if module.params['diff_against'] == 'running':
            if module.check_mode:
                module.warn(
                    "unable to perform diff against running-config due to check mode"
                )
                contents = None
            else:
                contents = config.config_text

        elif module.params['diff_against'] == 'startup':
            if not startup_config:
                output = execute_show_commands(module, 'show startup-config')
                contents = output[0]
            else:
                contents = output[0]
                contents = startup_config.config_text

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

        if contents is not None:
            base_config = NetworkConfig(indent=1,
                                        contents=contents,
                                        ignore_lines=diff_ignore_lines)

            if running_config.sha1 != base_config.sha1:
                result.update({
                    'changed': True,
                    'diff': {
                        'before': str(base_config),
                        'after': str(running_config)
                    }
                })

    module.exit_json(**result)
Beispiel #51
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'),
        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()
    check_args(module, warnings)
    result = dict(changed=False, warnings=warnings)

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

    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()
        load_config(module, candidate)
        result['changed'] = True
        result['commands'] = candidate

    else:
        result['commands'] = []
    module.exit_json(**result)
Beispiel #52
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'),
        shutdown=dict(required=False, type='bool'),
        source_interface=dict(required=False, type='str'),
        source_interface_hold_down_time=dict(required=False, type='str'),
        m_facts=dict(required=False, default=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 = {'changed': False, 'commands': [], 'warnings': warnings}
    check_args(module, 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 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():
    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 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 #54
0
def main():
    argument_spec = dict(
        vni=dict(required=True, type='str'),
        route_distinguisher=dict(required=False, type='str'),
        route_target_both=dict(required=False, type='list'),
        route_target_import=dict(required=False, type='list'),
        route_target_export=dict(required=False, type='list'),
        state=dict(choices=['present', 'absent'], default='present', required=False),
        include_defaults=dict(default=True),
        config=dict(),
        save=dict(type='bool', default=False)
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)
    results = dict(changed=False, warnings=warnings)

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

    proposed = {}
    for key, value in proposed_args.items():
        if key != 'vni':
            if value == 'true':
                value = True
            elif value == 'false':
                value = False
            if existing.get(key) != value:
                proposed[key] = value

    if state == 'present':
        commands, parents = state_present(module, existing, proposed)
    elif state == 'absent' and existing:
        commands, parents = state_absent(module, existing, proposed)

    if commands:
        if (existing.get('route_distinguisher') and
                proposed.get('route_distinguisher')):
            if (existing['route_distinguisher'] != proposed['route_distinguisher'] and
                    proposed['route_distinguisher'] != 'default'):
                warnings.append('EVPN RD {0} was automatically removed. '
                                'It is highly recommended to use a task '
                                '(with default as value) to explicitly '
                                'unconfigure it.'.format(existing['route_distinguisher']))
                remove_commands = ['no rd {0}'.format(existing['route_distinguisher'])]

                candidate = CustomNetworkConfig(indent=3)
                candidate.add(remove_commands, parents=parents)
                load_config(module, candidate)
                results['changed'] = True
                results['commands'] = candidate.items_text()
                time.sleep(30)

        else:
            candidate = CustomNetworkConfig(indent=3)
            candidate.add(commands, parents=parents)
            candidate = candidate.items_text()
            load_config(module, candidate)
            results['changed'] = True
            results['commands'] = candidate
    else:
        results['commands'] = []
    module.exit_json(**results)
Beispiel #55
0
def main():
    argument_spec = dict(
        domain=dict(required=True, type='str'),
        role_priority=dict(required=False, type='str'),
        system_priority=dict(required=False, type='str'),
        pkl_src=dict(required=False),
        pkl_dest=dict(required=False),
        pkl_vrf=dict(required=False),
        peer_gw=dict(required=False, type='bool'),
        auto_recovery=dict(required=False, type='bool'),
        delay_restore=dict(required=False, 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()
    check_args(module, warnings)
    results = {'changed': False, 'warnings': warnings}

    domain = module.params['domain']
    role_priority = module.params['role_priority']
    system_priority = module.params['system_priority']
    pkl_src = module.params['pkl_src']
    pkl_dest = module.params['pkl_dest']
    pkl_vrf = module.params['pkl_vrf']
    peer_gw = module.params['peer_gw']
    auto_recovery = module.params['auto_recovery']
    delay_restore = module.params['delay_restore']
    state = module.params['state']

    args = dict(domain=domain, role_priority=role_priority,
                system_priority=system_priority, pkl_src=pkl_src,
                pkl_dest=pkl_dest, pkl_vrf=pkl_vrf, peer_gw=peer_gw,
                auto_recovery=auto_recovery,
                delay_restore=delay_restore)

    if not pkl_dest:
        if pkl_src:
            module.fail_json(msg='dest IP for peer-keepalive is required'
                                 ' when src IP is present')
        elif pkl_vrf:
            if pkl_vrf != 'management':
                module.fail_json(msg='dest and src IP for peer-keepalive are required'
                                     ' when vrf is present')
            else:
                module.fail_json(msg='dest IP for peer-keepalive is required'
                                     ' when vrf is present')
    if pkl_vrf:
        if pkl_vrf.lower() not in get_vrf_list(module):
            module.fail_json(msg='The VRF you are trying to use for the peer '
                                 'keepalive link is not on device yet. Add it'
                                 ' first, please.')
    proposed = dict((k, v) for k, v in args.items() if v is not None)
    existing = get_vpc(module)

    commands = []
    if state == 'present':
        delta = {}
        for key, value in proposed.items():
            if str(value).lower() == 'default':
                value = PARAM_TO_DEFAULT_KEYMAP.get(key)
            if existing.get(key) != value:
                delta[key] = value
        if delta:
            command = get_commands_to_config_vpc(module, delta, domain, existing)
            commands.append(command)
    elif state == 'absent':
        if existing:
            if domain != existing['domain']:
                module.fail_json(msg="You are trying to remove a domain that "
                                     "does not exist on the device")
            else:
                commands.append('terminal dont-ask')
                commands.append('no vpc domain {0}'.format(domain))

    cmds = flatten_list(commands)
    results['commands'] = cmds

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

    module.exit_json(**results)
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)
Beispiel #57
0
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)
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()
    check_args(module, warnings)

    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 '\\'
        if not existing['vtp_password'] or existing['vtp_password'] == '\\':
            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 #59
0
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)

    warnings = list()
    check_args(module, warnings)

    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} {2}'.format(snapshot1, snapshot2, 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']:
                command = 'show snapshot | include {}'.format(module.params['snapshot_name'])
                content = execute_show_command(command, module)[0]
                if content:
                    write_on_file(content, module.params['snapshot_name'], module)

    module.exit_json(**result)
def main():
    argument_spec = dict(
        interface=dict(required=True, type='str'),
        version=dict(required=False, type='str'),
        startup_query_interval=dict(required=False, type='str'),
        startup_query_count=dict(required=False, type='str'),
        robustness=dict(required=False, type='str'),
        querier_timeout=dict(required=False, type='str'),
        query_mrt=dict(required=False, type='str'),
        query_interval=dict(required=False, type='str'),
        last_member_qrt=dict(required=False, type='str'),
        last_member_query_count=dict(required=False, type='str'),
        group_timeout=dict(required=False, type='str'),
        report_llg=dict(type='bool'),
        immediate_leave=dict(type='bool'),
        oif_routemap=dict(required=False, type='str'),
        oif_prefix=dict(required=False, type='str', removed_in_version='2.10'),
        oif_source=dict(required=False, type='str', removed_in_version='2.10'),
        oif_ps=dict(required=False, type='raw'),
        restart=dict(type='bool', default=False),
        state=dict(choices=['present', 'absent', 'default'],
                   default='present')
    )

    argument_spec.update(nxos_argument_spec)
    mutually_exclusive = [('oif_ps', 'oif_prefix'),
                          ('oif_ps', 'oif_source'),
                          ('oif_ps', 'oif_routemap'),
                          ('oif_prefix', 'oif_routemap')]

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

    warnings = list()
    check_args(module, warnings)

    state = module.params['state']
    interface = module.params['interface']
    oif_prefix = module.params['oif_prefix']
    oif_source = module.params['oif_source']
    oif_routemap = module.params['oif_routemap']
    oif_ps = module.params['oif_ps']

    if oif_source and not oif_prefix:
        module.fail_json(msg='oif_prefix required when setting oif_source')
    elif oif_source and oif_prefix:
        oif_ps = [{'source': oif_source, 'prefix': oif_prefix}]
    elif not oif_source and oif_prefix:
        oif_ps = [{'prefix': oif_prefix}]

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

    existing = get_igmp_interface(module, interface)
    existing_copy = existing.copy()
    end_state = existing_copy

    if not existing.get('version'):
        module.fail_json(msg='pim needs to be enabled on the interface')

    existing_oif_prefix_source = existing.get('oif_prefix_source')
    # not json serializable
    existing.pop('oif_prefix_source')

    if oif_routemap and existing_oif_prefix_source:
        module.fail_json(msg='Delete static-oif configurations on this '
                             'interface if you want to use a routemap')

    if oif_ps and existing.get('oif_routemap'):
        module.fail_json(msg='Delete static-oif route-map configuration '
                             'on this interface if you want to config '
                             'static entries')

    args = [
        'version',
        'startup_query_interval',
        'startup_query_count',
        'robustness',
        'querier_timeout',
        'query_mrt',
        'query_interval',
        'last_member_qrt',
        'last_member_query_count',
        'group_timeout',
        'report_llg',
        'immediate_leave',
        'oif_routemap',
    ]

    changed = False
    commands = []
    proposed = dict((k, v) for k, v in module.params.items()
                    if v is not None and k in args)

    CANNOT_ABSENT = ['version', 'startup_query_interval',
                     'startup_query_count', 'robustness', 'querier_timeout',
                     'query_mrt', 'query_interval', 'last_member_qrt',
                     'last_member_query_count', 'group_timeout', 'report_llg',
                     'immediate_leave']

    if state == 'absent':
        for each in CANNOT_ABSENT:
            if each in proposed:
                module.fail_json(msg='only params: oif_prefix, oif_source, '
                                     'oif_ps, oif_routemap can be used when '
                                     'state=absent')

    # delta check for all params except oif_ps
    delta = dict(set(proposed.items()).difference(existing.items()))

    if oif_ps:
        if oif_ps == 'default':
            delta['oif_ps'] = []
        else:
            delta['oif_ps'] = oif_ps

    if state == 'present':
        if delta:
            command = config_igmp_interface(delta, existing, existing_oif_prefix_source)
            if command:
                commands.append(command)

    elif state == 'default':
        command = config_default_igmp_interface(existing, delta)
        if command:
            commands.append(command)
    elif state == 'absent':
        command = None
        if existing.get('oif_routemap') or existing_oif_prefix_source:
            command = config_remove_oif(existing, existing_oif_prefix_source)

        if command:
            commands.append(command)

        command = config_default_igmp_interface(existing, delta)
        if command:
            commands.append(command)

    cmds = []
    results = {}
    if commands:
        commands.insert(0, ['interface {0}'.format(interface)])
        cmds = flatten_list(commands)

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

    if module.params['restart']:
        cmd = {'command': 'restart igmp', 'output': 'text'}
        run_commands(module, cmd)

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

    module.exit_json(**results)