Ejemplo n.º 1
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)
Ejemplo n.º 2
0
def main():
    argument_spec = dict(
        ssm_range=dict(required=True, type='str'),
    )

    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}

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

    args = PARAM_TO_COMMAND_KEYMAP.keys()

    existing = get_existing(module, args)
    proposed = dict((k, v) for k, v in module.params.items()
                    if k in args and v != existing[k])

    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)
Ejemplo n.º 3
0
def main():
    argument_spec = dict(
        anycast_gateway_mac=dict(required=True, type='str'),
    )

    argument_spec.update(nxos_argument_spec)

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

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

    args = PARAM_TO_COMMAND_KEYMAP.keys()

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

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

    if candidate:
        candidate = candidate.items_text()
        result['commands'] = candidate

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

    module.exit_json(**result)
Ejemplo n.º 4
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'
    ]

    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 != 'rp_address':
            if str(value).lower() == 'true':
                value = True
            elif str(value).lower() == 'false':
                value = False

            if existing.get(key) != value:
                proposed[key] = value

    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
        load_config(module, candidate)

    module.exit_json(**result)
Ejemplo n.º 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()
    check_args(module, warnings)


    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)
Ejemplo n.º 6
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)
Ejemplo n.º 7
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'),

        include_defaults=dict(default=False),
        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)


    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':
        if desired['flush_routes'] and not current['flush_routes']:
            commands.append('ip igmp flush-routes')
        if desired['enforce_rtr_alert'] and not current['enforce_rtr_alert']:
            commands.append('ip igmp enforce-router-alert')

    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']:
        run_commands(module, 'restart igmp')

    module.exit_json(**result)
Ejemplo n.º 8
0
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'),
        include_defaults=dict(default=False),
        config=dict()
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)


    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)
Ejemplo n.º 9
0
def set_boot_options(module, image_name, kickstart=None):
    """Set boot variables
    like system image and kickstart image.
    Args:
        The main system image file name.
    Keyword Args: many implementors may choose
        to supply a kickstart parameter to specify a kickstart image.
    """
    commands = ['terminal dont-ask']
    if kickstart is None:
        commands.append('install all nxos %s' % image_name)
    else:
        commands.append(
            'install all system %s kickstart %s' % (image_name, kickstart))
    load_config(module, commands)
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
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'),
        lookup_source=dict(),
        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)
Ejemplo n.º 12
0
def main():
    argument_spec = dict(
        feature=dict(type='str', required=True),
        state=dict(choices=['enabled', 'disabled'], default='enabled'),

        # deprecated in Ans2.3
        include_defaults=dict(),
        config=dict(),
        save=dict()
    )

    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)

    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:
            if not module.check_mode:
                load_config(module, cmds)
            results['changed'] = True

    results['commands'] = cmds
    module.exit_json(**results)
Ejemplo n.º 13
0
def main():
    argument_spec = dict(
        ospf=dict(required=True, type='str'),
        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']
    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)
Ejemplo n.º 14
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'),

        # deprecated (Ansible 2.3) arguments
        config=dict(),

        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)
Ejemplo n.º 15
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'),
        purge=dict(default=False, type='bool')
    )

    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)
Ejemplo n.º 16
0
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)
Ejemplo n.º 17
0
def main():
    argument_spec = dict(
        nv_overlay_evpn=dict(required=True, type='bool'),

        # deprecated in Ans2.3
        include_defaults=dict(),
        config=dict(),
        save=dict()
    )

    argument_spec.update(nxos_argument_spec)

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

    result = {'changed': False}

    warnings = list()
    check_args(module, warnings)
    if warnings:
        result['warnings'] = warnings

    config = get_config(module)
    commands = list()

    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)
Ejemplo n.º 18
0
def main():
    argument_spec = dict(
        state=dict(choices=['enabled', 'disabled'], default='enabled'),
        group=dict(choices=['aaa', 'bridge', 'callhome', 'cfs', 'config',
                            'entity', 'feature-control', 'hsrp',
                            'license', 'link', 'lldp', 'ospf', 'pim', 'rf',
                            'rmon', 'snmp', 'storm-control', 'stpx',
                            '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)
Ejemplo n.º 19
0
def main():
    argument_spec = dict(
        prefix=dict(required=True, type='str'),
        next_hop=dict(required=True, type='str'),
        vrf=dict(type='str', default='default'),
        tag=dict(type='str'),
        route_name=dict(type='str'),
        pref=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()
    check_args(module, warnings)
    result = dict(changed=False, warnings=warnings)

    prefix = normalize_prefix(module, module.params['prefix'])

    candidate = CustomNetworkConfig(indent=3)
    reconcile_candidate(module, candidate, prefix)

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

    module.exit_json(**result)
Ejemplo n.º 20
0
def main():
    argument_spec = dict(
        aggressive=dict(required=False, choices=['enabled', 'disabled']),
        msg_time=dict(required=False, type='str'),
        reset=dict(required=False, type='bool'),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                                required_one_of=[['aggressive', 'msg_time', 'reset']],
                                supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)


    aggressive = module.params['aggressive']
    msg_time = module.params['msg_time']
    reset = module.params['reset']
    state = module.params['state']

    if (aggressive or reset) and state == 'absent':
        module.fail_json(msg="It's better to use state=present when "
                             "configuring or unconfiguring aggressive mode "
                             "or using reset flag. state=absent is just for "
                             "when using msg_time param.")

    if msg_time:
        try:
            msg_time_int = int(msg_time)
            if msg_time_int < 7 or msg_time_int > 90:
                raise ValueError
        except ValueError:
            module.fail_json(msg='msg_time must be an integer'
                                 'between 7 and 90')

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

    existing = get_udld_global(module)
    end_state = existing

    delta = set(proposed.items()).difference(existing.items())
    changed = False

    commands = []
    if state == 'present':
        if delta:
            command = get_commands_config_udld_global(dict(delta), reset)
            commands.append(command)

    elif state == 'absent':
        common = set(proposed.items()).intersection(existing.items())
        if common:
            command = get_commands_remove_udld_global(dict(common))
            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_udld_global(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)
Ejemplo n.º 21
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'),
        afi=dict(required=True, type='str'),
        safi=dict(required=True, type='str'),
        additional_paths_receive=dict(required=False,
                                      type='str',
                                      choices=['enable', 'disable',
                                               'inherit']),
        additional_paths_send=dict(required=False,
                                   type='str',
                                   choices=['enable', 'disable', 'inherit']),
        advertise_map_exist=dict(required=False, type='list'),
        advertise_map_non_exist=dict(required=False, type='list'),
        allowas_in=dict(required=False, type='bool'),
        allowas_in_max=dict(required=False, type='str'),
        as_override=dict(required=False, type='bool'),
        default_originate=dict(required=False, type='bool'),
        default_originate_route_map=dict(required=False, type='str'),
        filter_list_in=dict(required=False, type='str'),
        filter_list_out=dict(required=False, type='str'),
        max_prefix_limit=dict(required=False, type='str'),
        max_prefix_interval=dict(required=False, type='str'),
        max_prefix_threshold=dict(required=False, type='str'),
        max_prefix_warning=dict(required=False, type='bool'),
        next_hop_self=dict(required=False, type='bool'),
        next_hop_third_party=dict(required=False, type='bool'),
        prefix_list_in=dict(required=False, type='str'),
        prefix_list_out=dict(required=False, type='str'),
        route_map_in=dict(required=False, type='str'),
        route_map_out=dict(required=False, type='str'),
        route_reflector_client=dict(required=False, type='bool'),
        send_community=dict(
            required=False,
            choices=['none', 'both', 'extended', 'standard', 'default']),
        soft_reconfiguration_in=dict(required=False,
                                     type='str',
                                     choices=['enable', 'always', 'inherit']),
        soo=dict(required=False, type='str'),
        suppress_inactive=dict(required=False, type='bool'),
        unsuppress_map=dict(required=False, type='str'),
        weight=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,
        mutually_exclusive=[['advertise_map_exist', 'advertise_map_non_exist'],
                            ['max_prefix_interval', 'max_prefix_warning']],
        supports_check_mode=True,
    )

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

    state = module.params['state']
    for key in [
            'max_prefix_interval', 'max_prefix_warning', 'max_prefix_threshold'
    ]:
        if module.params[key] and not module.params['max_prefix_limit']:
            module.fail_json(msg='max_prefix_limit is required when using %s' %
                             key)
    if module.params['vrf'] == 'default' and module.params['soo']:
        module.fail_json(msg='SOO is only allowed in non-default VRF')

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

    for param in ['advertise_map_exist', 'advertise_map_non_exist']:
        if module.params[param] == ['default']:
            module.params[param] = 'default'

    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']:
            if not isinstance(value, list):
                if str(value).lower() == 'true':
                    value = True
                elif str(value).lower() == 'false':
                    value = False
                elif str(value).lower() == 'default':
                    if key in BOOL_PARAMS:
                        value = False
                    else:
                        value = '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, existing, candidate)

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

    module.exit_json(**result)
Ejemplo n.º 22
0
def main():
    argument_spec = dict(
        snmp_host=dict(required=True, type='str'),
        community=dict(type='str'),
        udp=dict(type='str'),
        version=dict(choices=['v2c', 'v3'], default='v2c'),
        src_intf=dict(type='str'),
        v3=dict(choices=['noauth', 'auth', 'priv']),
        vrf_filter=dict(type='str'),
        vrf=dict(type='str'),
        snmp_type=dict(choices=['trap', 'inform'], default='trap'),
        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)



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

    state = module.params['state']

    if snmp_type == 'inform' and version != 'v3':
        module.fail_json(msg='inform requires snmp v3')

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

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

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

    existing = get_snmp_host(snmp_host, module)

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

    args = dict(
        community=community,
        snmp_host=snmp_host,
        udp=udp,
        version=version,
        src_intf=src_intf,
        vrf_filter=vrf_filter,
        v3=v3,
        vrf=vrf,
        snmp_type=snmp_type
        )

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

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

    changed = False
    commands = []
    end_state = existing

    if state == 'absent':
        if existing:
            command = remove_snmp_host(snmp_host, existing)
            commands.append(command)
    elif state == 'present':
        if delta:
            command = config_snmp_host(delta, proposed, existing, module)
            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_snmp_host(snmp_host, module)
            if 'configure' in cmds:
                cmds.pop(0)

    if store:
        existing['vrf_filter'] = store

    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)
Ejemplo n.º 23
0
def main():
    argument_spec = dict(
        vrf=dict(required=True),
        description=dict(default=None, required=False),
        vni=dict(required=False, type='str'),
        rd=dict(required=False, type='str'),
        admin_state=dict(default='up', choices=['up', 'down'], required=False),
        state=dict(default='present', choices=['present', 'absent'], required=False),
        include_defaults=dict(default=False),
        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)

    vrf = module.params['vrf']
    admin_state = module.params['admin_state'].lower()
    description = module.params['description']
    rd = module.params['rd']
    vni = module.params['vni']
    state = module.params['state']

    if vrf == 'default':
        module.fail_json(msg='cannot use default as name of a VRF')
    elif len(vrf) > 32:
        module.fail_json(msg='VRF name exceeded max length of 32', vrf=vrf)

    existing = get_vrf(vrf, module)
    args = dict(vrf=vrf, description=description, vni=vni,
                admin_state=admin_state, rd=rd)

    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 existing:
            command = ['no vrf context {0}'.format(vrf)]
            commands.extend(command)

    elif state == 'present':
        if not existing:
            command = get_commands_to_config_vrf(delta, vrf)
            commands.extend(command)
        elif delta:
            command = get_commands_to_config_vrf(delta, vrf)
            commands.extend(command)

    if state == 'present' and commands:
        if proposed.get('vni'):
            if existing.get('vni') and existing.get('vni') != '':
                commands.insert(1, 'no vni {0}'.format(existing['vni']))

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

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

    results['commands'] = commands

    module.exit_json(**results)
Ejemplo n.º 24
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'),
                         include_defaults=dict(default=False),
                         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)

    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)
Ejemplo n.º 25
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)
            load_config(module, candidate)
            results['changed'] = True
            results['commands'] = candidate.items_text()
    else:
        results['commands'] = []
    module.exit_json(**results)
Ejemplo n.º 26
0
def main():
    argument_spec = dict(vrf=dict(required=True, type='str'),
                         safi=dict(required=True,
                                   type='str',
                                   choices=['unicast', 'multicast']),
                         afi=dict(required=True,
                                  type='str',
                                  choices=['ipv4', 'ipv6']),
                         route_target_both_auto_evpn=dict(required=False,
                                                          type='bool'),
                         m_facts=dict(required=False,
                                      default=False,
                                      type='bool'),
                         state=dict(choices=['present', 'absent'],
                                    default='present',
                                    required=False),
                         include_defaults=dict(default=False),
                         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)

    state = module.params['state']

    args = ['vrf', 'safi', 'afi', 'route_target_both_auto_evpn']

    existing = invoke('get_existing', module, args)
    end_state = existing
    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:
                    value = 'default'
            if existing.get(key) or (not existing.get(key) and value):
                proposed[key] = value

    result = {}
    if state == 'present' or (state == 'absent' and existing):
        candidate = CustomNetworkConfig(indent=3)
        invoke('state_%s' % state, module, existing, proposed, candidate)

        try:
            response = load_config(module, candidate)
            result.update(response)
        except ShellError:
            exc = get_exception()
            module.fail_json(msg=str(exc))
    else:
        result['updates'] = []

    if module._verbosity > 0:
        end_state = invoke('get_existing', module, args)
        result['end_state'] = end_state
        result['existing'] = existing
        result['proposed'] = proposed_args

    if WARNINGS:
        result['warnings'] = WARNINGS

    module.exit_json(**result)
Ejemplo n.º 27
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, default='management'),
                         peer_gw=dict(required=True, type='bool'),
                         auto_recovery=dict(required=True, type='bool'),
                         delay_restore=dict(required=False, type='str'),
                         state=dict(choices=['absent', 'present'],
                                    default='present'),
                         include_defaults=dict(default=False),
                         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)

    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_src and pkl_dest and pkl_vrf):
        # if only the source or dest is set, it'll fail and ask to set the
        # other
        if pkl_src or pkl_dest:
            module.fail_json(msg='source AND dest IP for pkl are required at '
                             'this time (although source is technically not '
                             ' required by the device.)')

        args.pop('pkl_src')
        args.pop('pkl_dest')
        args.pop('pkl_vrf')

    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)
    changed = False
    existing = get_vpc(module)
    end_state = existing

    commands = []
    if state == 'present':
        delta = set(proposed.items()).difference(existing.items())
        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('no vpc domain {0}'.format(domain))

    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_vpc(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)
Ejemplo n.º 28
0
def main():
    argument_spec = dict(
        server_type=dict(type='str', choices=['radius', 'tacacs'], required=True),
        global_key=dict(type='str'),
        encrypt_type=dict(type='str', choices=['0', '7']),
        deadtime=dict(type='str'),
        server_timeout=dict(type='str'),
        directed_request=dict(type='str', choices=['enabled', 'disabled', 'default']),
        state=dict(choices=['default', '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}

    server_type = module.params['server_type']
    global_key = module.params['global_key']
    encrypt_type = module.params['encrypt_type']
    deadtime = module.params['deadtime']
    server_timeout = module.params['server_timeout']
    directed_request = module.params['directed_request']
    state = module.params['state']

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

    args = dict(server_type=server_type, global_key=global_key,
                encrypt_type=encrypt_type, deadtime=deadtime,
                server_timeout=server_timeout, directed_request=directed_request)

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

    existing = get_aaa_server_info(server_type, module)

    commands = []
    if state == 'present':
        if deadtime:
            try:
                if int(deadtime) < 0 or int(deadtime) > 1440:
                    raise ValueError
            except ValueError:
                module.fail_json(
                    msg='deadtime must be an integer between 0 and 1440')

        if server_timeout:
            try:
                if int(server_timeout) < 1 or int(server_timeout) > 60:
                    raise ValueError
            except ValueError:
                module.fail_json(
                    msg='server_timeout must be an integer between 1 and 60')

        delta = dict(set(proposed.items()).difference(
            existing.items()))
        if delta:
            command = config_aaa_server(delta, server_type)
            if command:
                commands.append(command)

    elif state == 'default':
        for key, value in proposed.items():
            if key != 'server_type' and value != 'default':
                module.fail_json(
                    msg='Parameters must be set to "default"'
                        'when state=default')
        command = default_aaa_server(existing, proposed, server_type)
        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)
Ejemplo n.º 29
0
def main():
    argument_spec = dict(vlan_id=dict(required=False, type='str'),
                         vlan_range=dict(required=False),
                         name=dict(required=False),
                         vlan_state=dict(choices=['active', 'suspend'],
                                         required=False),
                         mapped_vni=dict(required=False, type='str'),
                         state=dict(choices=['present', 'absent'],
                                    default='present',
                                    required=False),
                         admin_state=dict(choices=['up', 'down'],
                                          required=False),
                         include_defaults=dict(default=False),
                         config=dict(),
                         save=dict(type='bool', default=False))

    argument_spec.update(nxos_argument_spec)

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[['vlan_range', 'name'],
                                               ['vlan_id', 'vlan_range']],
                           supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)

    warnings = list()
    check_args(module, warnings)

    vlan_range = module.params['vlan_range']
    vlan_id = module.params['vlan_id']
    name = module.params['name']
    vlan_state = module.params['vlan_state']
    admin_state = module.params['admin_state']
    mapped_vni = module.params['mapped_vni']
    state = module.params['state']

    changed = False

    if vlan_id:
        if not vlan_id.isdigit():
            module.fail_json(msg='vlan_id must be a valid VLAN ID')

    args = dict(name=name,
                vlan_state=vlan_state,
                admin_state=admin_state,
                mapped_vni=mapped_vni)

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

    proposed_vlans_list = numerical_sort(
        vlan_range_to_list(vlan_id or vlan_range))
    existing_vlans_list = numerical_sort(get_list_of_vlans(module))
    commands = []
    existing = {}

    if vlan_range:
        if state == 'present':
            # These are all of the VLANs being proposed that don't
            # already exist on the switch
            vlans_delta = list(
                set(proposed_vlans_list).difference(existing_vlans_list))
            commands = build_commands(vlans_delta, state)
        elif state == 'absent':
            # VLANs that are common between what is being proposed and
            # what is on the switch
            vlans_common = list(
                set(proposed_vlans_list).intersection(existing_vlans_list))
            commands = build_commands(vlans_common, state)
    else:
        existing = get_vlan(vlan_id, module)
        if state == 'absent':
            if existing:
                commands = ['no vlan ' + vlan_id]
        elif state == 'present':
            if (existing.get('mapped_vni') == '0'
                    and proposed.get('mapped_vni') == 'default'):
                proposed.pop('mapped_vni')
            delta = dict(set(proposed.items()).difference(existing.items()))
            if delta or not existing:
                commands = get_vlan_config_commands(delta, vlan_id)

    end_state = existing
    end_state_vlans_list = existing_vlans_list

    if commands:
        if existing.get('mapped_vni') and state != 'absent':
            if (existing.get('mapped_vni') != proposed.get('mapped_vni')
                    and existing.get('mapped_vni') != '0'
                    and proposed.get('mapped_vni') != 'default'):
                commands.insert(1, 'no vn-segment')
        if module.check_mode:
            module.exit_json(changed=True, commands=commands)
        else:
            load_config(module, commands)
            changed = True
            end_state_vlans_list = numerical_sort(get_list_of_vlans(module))
            if 'configure' in commands:
                commands.pop(0)
            if vlan_id:
                end_state = get_vlan(vlan_id, module)

    results = {
        'commands': commands,
        'updates': commands,
        'changed': changed,
        'warnings': warnings
    }

    if module._debug:
        results.update({
            'proposed_vlans_list': proposed_vlans_list,
            'existing_vlans_list': existing_vlans_list,
            'proposed': proposed,
            'existing': existing,
            'end_state': end_state,
            'end_state_vlans_list': end_state_vlans_list
        })

    module.exit_json(**results)
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'),
        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=['cleartext', '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='str'),
        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'),
        m_facts=dict(required=False, default=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,
                                required_together=[['timer_bgp_hold',
                                            'timer_bgp_keepalive']],
                                supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)


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

    args =  [
        'asn',
        'capability_negotiation',
        'connected_check',
        'description',
        'dynamic_capability',
        'ebgp_multihop',
        'local_as',
        'log_neighbor_changes',
        'low_memory_exempt',
        'maximum_peers',
        'neighbor',
        'pwd',
        'pwd_type',
        'remote_as',
        'remove_private_as',
        'shutdown',
        'suppress_4_byte_as',
        'timers_keepalive',
        'timers_holdtime',
        'transport_passive_only',
        'update_source',
        'vrf'
    ]

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

    end_state = existing
    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)
                if value is None:
                    value = 'default'
            if existing.get(key) or (not existing.get(key) and value):
                proposed[key] = value

    result = {}
    if state == 'present' or (state == 'absent' and existing):
        candidate = CustomNetworkConfig(indent=3)
        invoke('state_%s' % state, module, existing, proposed, candidate)

        try:
            response = load_config(module, candidate)
            result.update(response)
        except ShellError:
            exc = get_exception()
            module.fail_json(msg=str(exc))
    else:
        result['updates'] = []

    result['connected'] = module.connected
    if module._verbosity > 0:
        end_state = invoke('get_existing', module, args)
        result['end_state'] = end_state
        result['existing'] = existing
        result['proposed'] = proposed_args

    if WARNINGS:
        result['warnings'] = WARNINGS

    module.exit_json(**result)
Ejemplo n.º 31
0
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),
        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,
                           required_together=[[
                               'message_digest_key_id',
                               'message_digest_algorithm_type',
                               'message_digest_encryption_type',
                               'message_digest_password'
                           ]],
                           supports_check_mode=True)

    if not module.params['interface'].startswith('loopback'):
        module.params['interface'] = module.params['interface'].capitalize()

    warnings = list()
    check_args(module, 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 = [
        'interface', 'ospf', 'area', 'cost', 'hello_interval', 'dead_interval',
        'passive_interface', 'message_digest', 'message_digest_key_id',
        'message_digest_algorithm_type', 'message_digest_encryption_type',
        'message_digest_password'
    ]

    existing = invoke('get_existing', module, args)
    end_state = existing
    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) or (not existing.get(key) and value):
                proposed[key] = value

    proposed['area'] = normalize_area(proposed['area'], module)
    result = {}
    if (state == 'present'
            or (state == 'absent' and existing.get('ospf') == proposed['ospf']
                and existing.get('area') == proposed['area'])):

        candidate = CustomNetworkConfig(indent=3)
        invoke('state_%s' % state, module, existing, proposed, candidate)

        try:
            response = load_config(module, candidate)
            result.update(response)
        except ShellError:
            exc = get_exception()
            module.fail_json(msg=str(exc))
    else:
        result['updates'] = []

    if module._verbosity > 0:
        end_state = invoke('get_existing', module, args)
        result['end_state'] = end_state
        result['existing'] = existing
        result['proposed'] = proposed_args

    result['warnings'] = warnings

    module.exit_json(**result)
Ejemplo n.º 32
0
def main():
    argument_spec = dict(
        group=dict(required=True, type='str'),
        interface=dict(required=True),
        priority=dict(required=False, type='str'),
        preempt=dict(required=False, type='bool'),
        vip=dict(required=False, type='str'),
        admin_state=dict(required=False, type='str',
                                choices=['shutdown', 'no shutdown'],
                                default='no shutdown'),
        authentication=dict(required=False, type='str'),
        state=dict(choices=['absent', 'present'],
                       required=False, default='present'),
        include_defaults=dict(default=False),
        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)


    state = module.params['state']
    interface = module.params['interface'].lower()
    group = module.params['group']
    priority = module.params['priority']
    preempt = module.params['preempt']
    vip = module.params['vip']
    authentication = module.params['authentication']
    admin_state = module.params['admin_state']

    transport = module.params['transport']

    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 transport == 'cli'):
        if is_default(interface, module) == 'DNE':
            module.fail_json(msg='That interface does not exist yet. Create '
                                 'it first.', interface=interface)
        if intf_type == 'loopback':
            module.fail_json(msg="Loopback interfaces don't support VRRP.",
                             interface=interface)

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

    args = dict(group=group, priority=priority, preempt=preempt,
                vip=vip, authentication=authentication,
                admin_state=admin_state)

    proposed = dict((k, v) for k, v in args.items() if v is not None)
    existing = get_existing_vrrp(interface, group, module, name)

    changed = False
    end_state = existing
    commands = []

    if state == 'present':
        delta = dict(
            set(proposed.items()).difference(existing.items()))
        if delta:
            command = get_commands_config_vrrp(delta, group)
            commands.append(command)

    elif state == 'absent':
        if existing:
            commands.append(['no vrrp {0}'.format(group)])

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

    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_existing_vrrp(interface, group, module, name)
            if 'configure' in cmds:
                cmds.pop(0)

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

    module.exit_json(**results)
Ejemplo n.º 33
0
def apply_patch(module, commands):
    for command in commands:
        load_config(module, [command])
        time.sleep(5)
Ejemplo n.º 34
0
def main():

    argument_spec = dict(
        interface=dict(required=False,),
        admin_state=dict(default='up', choices=['up', 'down'], required=False),
        description=dict(required=False, default=None),
        mode=dict(choices=['layer2', 'layer3'], required=False),
        interface_type=dict(required=False, choices=['loopback', 'portchannel', 'svi', 'nve']),
        ip_forward=dict(required=False, choices=['enable', 'disable']),
        fabric_forwarding_anycast_gateway=dict(required=False, type='bool'),
        state=dict(choices=['absent', 'present', 'default'], default='present', required=False)
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=[['interface', 'interface_type']],
                           supports_check_mode=True)

    warnings = list()
    check_args(module, warnings)

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

    interface = module.params['interface']
    interface_type = module.params['interface_type']
    admin_state = module.params['admin_state']
    description = module.params['description']
    mode = module.params['mode']
    ip_forward = module.params['ip_forward']
    fabric_forwarding_anycast_gateway = module.params['fabric_forwarding_anycast_gateway']
    state = module.params['state']

    if interface:
        interface = interface.lower()
        intf_type = get_interface_type(interface)
        normalized_interface = normalize_interface(interface)

        if normalized_interface == 'Vlan1' and state == 'absent':
            module.fail_json(msg='ERROR: CANNOT REMOVE VLAN 1!')

        if intf_type == 'nve':
            if description or mode:
                module.fail_json(msg='description and mode params are not '
                                     'supported in this module. Use '
                                     'nxos_vxlan_vtep instead.')
        if (ip_forward or fabric_forwarding_anycast_gateway) and intf_type != 'svi':
            module.fail_json(msg='The ip_forward and '
                                 'fabric_forwarding_anycast_gateway features '
                                 ' are only available for SVIs.')
        args = dict(interface=interface, admin_state=admin_state,
                    description=description, mode=mode, ip_forward=ip_forward,
                    fabric_forwarding_anycast_gateway=fabric_forwarding_anycast_gateway)

        if intf_type == 'unknown':
            module.fail_json(msg='unknown interface type found-1',
                             interface=interface)

        existing, is_default = smart_existing(module, intf_type, normalized_interface)
        proposed = get_proposed(existing, normalized_interface, args)
    else:
        intf_type = normalized_interface = interface_type
        proposed = dict(interface_type=interface_type)

    commands = []
    if interface:
        delta = dict()

        if state == 'absent':
            if intf_type in ['svi', 'loopback', 'portchannel', 'nve']:
                if is_default != 'DNE':
                    cmds = ['no interface {0}'.format(normalized_interface)]
                    commands.append(cmds)
            elif intf_type in ['ethernet']:
                if is_default is False:
                    cmds = ['default interface {0}'.format(normalized_interface)]
                    commands.append(cmds)
        elif state == 'present':
            if not existing:
                cmds = get_interface_config_commands(proposed, normalized_interface, existing)
                commands.append(cmds)
            else:
                delta = dict(set(proposed.items()).difference(existing.items()))
                if delta:
                    cmds = get_interface_config_commands(delta, normalized_interface, existing)
                    commands.append(cmds)
        elif state == 'default':
            if is_default is False:
                cmds = ['default interface {0}'.format(normalized_interface)]
                commands.append(cmds)
            elif is_default == 'DNE':
                module.exit_json(msg='interface you are trying to default does not exist')
    elif interface_type:
        if state == 'present':
            module.fail_json(msg='The interface_type param can be used only with state absent.')

        existing = get_interfaces_dict(module)[interface_type]
        cmds = get_interface_type_removed_cmds(existing)
        commands.append(cmds)

    cmds = flatten_list(commands)
    end_state = existing

    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            load_config(module, cmds)
            results['changed'] = True
            if module.params['interface']:
                if delta.get('mode'):
                    # 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.
                    admin_state = delta.get('admin_state') or admin_state
                    c1 = 'interface {0}'.format(normalized_interface)
                    c2 = get_admin_state(delta, normalized_interface, admin_state)
                    cmds2 = [c1, c2]
                    load_config(module, cmds2)
                    cmds.extend(cmds2)
                end_state, is_default = smart_existing(module, intf_type,
                                                       normalized_interface)
            else:
                end_state = get_interfaces_dict(module)[interface_type]
            cmds = [cmd for cmd in cmds if cmd != 'configure']

    results['commands'] = cmds

    module.exit_json(**results)
Ejemplo n.º 35
0
def main():
    argument_spec = dict(
        snooping=dict(required=False, type='bool'),
        group_timeout=dict(required=False, type='str'),
        link_local_grp_supp=dict(required=False, type='bool'),
        report_supp=dict(required=False, type='bool'),
        v3_report_supp=dict(required=False, type='bool'),
        state=dict(choices=['present', 'default'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)
    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)
    end_state = existing

    commands = []
    if state == 'present':
        delta = dict(
            set(proposed.items()).difference(existing.items())
            )
        if delta:
            command = config_igmp_snooping(delta, existing)
            if command:
                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)
Ejemplo n.º 36
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() == '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:
                    if key in BOOL_PARAMS:
                        value = False
                    else:
                        value = 'default'
            if existing.get(key) != value:
                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)
Ejemplo n.º 37
0
def main():
    argument_spec = dict(
        interface=dict(required=True),
        sparse=dict(type='bool', default=True),
        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'),
        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':
        defaults = config_pim_interface_defaults(existing, jp_bidir, isauth)
        if defaults:
            commands.append(defaults)

    elif state == 'absent':
        if existing.get('sparse') is True:
            delta['sparse'] = False
            # defaults is a list of commands
            defaults = config_pim_interface_defaults(existing, jp_bidir, isauth)
            if defaults:
                commands.append(defaults)

            command = config_pim_interface(delta, existing, jp_bidir, isauth)
            commands.append(command)

    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)
Ejemplo n.º 38
0
def apply_patch(module, commands):
    for command in commands:
        load_config(module, [command])
        time.sleep(5)
        if 'failed' in response:
            module.fail_json(msg="Operation failed!", response=response)
Ejemplo n.º 39
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        aggregate=dict(type='list', no_log=True, aliases=['collection', 'users']),
        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(),

        purge=dict(type='bool', default=False),
        state=dict(default='present', choices=['present', 'absent'])
    )

    argument_spec.update(nxos_argument_spec)

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

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


    result = {'changed': False}

    warnings = 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.'
        )

    check_args(module, warnings)
    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':
                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)
Ejemplo n.º 40
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'),
        afi=dict(required=True, type='str'),
        safi=dict(required=True, type='str'),
        additional_paths_receive=dict(required=False, type='str', choices=['enable', 'disable', 'inherit']),
        additional_paths_send=dict(required=False, type='str', choices=['enable', 'disable', 'inherit']),
        advertise_map_exist=dict(required=False, type='list'),
        advertise_map_non_exist=dict(required=False, type='list'),
        allowas_in=dict(required=False, type='bool'),
        allowas_in_max=dict(required=False, type='str'),
        as_override=dict(required=False, type='bool'),
        default_originate=dict(required=False, type='bool'),
        default_originate_route_map=dict(required=False, type='str'),
        filter_list_in=dict(required=False, type='str'),
        filter_list_out=dict(required=False, type='str'),
        max_prefix_limit=dict(required=False, type='str'),
        max_prefix_interval=dict(required=False, type='str'),
        max_prefix_threshold=dict(required=False, type='str'),
        max_prefix_warning=dict(required=False, type='bool'),
        next_hop_self=dict(required=False, type='bool'),
        next_hop_third_party=dict(required=False, type='bool'),
        prefix_list_in=dict(required=False, type='str'),
        prefix_list_out=dict(required=False, type='str'),
        route_map_in=dict(required=False, type='str'),
        route_map_out=dict(required=False, type='str'),
        route_reflector_client=dict(required=False, type='bool'),
        send_community=dict(required=False, choices=['none', 'both', 'extended', 'standard', 'default']),
        soft_reconfiguration_in=dict(required=False, type='str', choices=['enable', 'always', 'inherit']),
        soo=dict(required=False, type='str'),
        suppress_inactive=dict(required=False, type='bool'),
        unsuppress_map=dict(required=False, type='str'),
        weight=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,
        mutually_exclusive=[['advertise_map_exist', 'advertise_map_non_exist'],
                            ['max_prefix_interval', 'max_prefix_warning']],
        supports_check_mode=True,
    )

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

    state = module.params['state']
    for key in ['max_prefix_interval', 'max_prefix_warning', 'max_prefix_threshold']:
        if module.params[key] and not module.params['max_prefix_limit']:
            module.fail_json(
                msg='max_prefix_limit is required when using %s' % key
            )
    if module.params['vrf'] == 'default' and module.params['soo']:
        module.fail_json(msg='SOO is only allowed in non-default VRF')

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

    for param in ['advertise_map_exist', 'advertise_map_non_exist']:
        if module.params[param] == ['default']:
            module.params[param] = 'default'

    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']:
            if not isinstance(value, list):
                if str(value).lower() == 'true':
                    value = True
                elif str(value).lower() == 'false':
                    value = False
                elif str(value).lower() == 'default':
                    if key in BOOL_PARAMS:
                        value = False
                    else:
                        value = '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, existing, candidate)

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

    module.exit_json(**result)
Ejemplo n.º 41
0
def main():
    argument_spec = dict(
        key_id=dict(required=True, type='str'),
        md5string=dict(required=True, type='str'),
        auth_type=dict(choices=['text', 'encrypt'], default='text'),
        trusted_key=dict(choices=['true', 'false'], default='false'),
        authentication=dict(choices=['on', 'off']),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

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

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

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

    existing = get_ntp_auth_info(key_id, module)
    end_state = existing

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

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

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

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

    module.exit_json(**results)
Ejemplo n.º 42
0
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'),
        oif_source=dict(required=False, type='str'),
        restart=dict(type='bool', default=False),
        state=dict(choices=['present', 'absent', 'default'],
                       default='present'),
        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)


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

    if oif_source:
        if not oif_prefix:
            module.fail_json(msg='oif_prefix required when setting oif_source')

    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 oif_prefix and oif_routemap:
        module.fail_json(msg='cannot use oif_prefix AND oif_routemap.'
                             '  select one.')

    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_prefix 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',
        'oif_prefix',
        'oif_source'
    ]

    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_routemap can be used when '
                                     'state=absent')

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

    # now check to see there is a delta for prefix and source command option
    found_both = False
    found_prefix = False

    if existing_oif_prefix_source:
        if oif_prefix and oif_source:
            for each in existing_oif_prefix_source:
                if (oif_prefix == each.get('prefix') and
                        oif_source == each.get('source')):
                    found_both = True
            if not found_both:
                delta['prefix'] = oif_prefix
                delta['source'] = oif_source
        elif oif_prefix:
            for each in existing_oif_prefix_source:
                if oif_prefix == each.get('prefix') and not each.get('source'):
                    found_prefix = True
            if not found_prefix:
                delta['prefix'] = oif_prefix

    if state == 'present':
        if delta:
            command = config_igmp_interface(delta, found_both, found_prefix)
            if command:
                commands.append(command)

    elif state == 'default':
        command = config_default_igmp_interface(existing, delta,
                                                found_both, found_prefix)
        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,
                                                found_both, found_prefix)
        if command:
            commands.append(command)

    if module.params['restart']:
        commands.append('restart igmp')

    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)

    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)
Ejemplo n.º 43
0
def main():
    argument_spec = dict(vrf=dict(required=True),
                         interface=dict(type='str', required=True),
                         state=dict(default='present',
                                    choices=['present', 'absent'],
                                    required=False),
                         include_defaults=dict(default=False),
                         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)

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

    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 module.params['transport'] == 'cli'):
        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 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 = {}
    results['proposed'] = proposed
    results['existing'] = existing
    results['end_state'] = end_state
    results['updates'] = commands
    results['changed'] = changed

    if WARNINGS:
        results['warnings'] = WARNINGS

    module.exit_json(**results)
Ejemplo n.º 44
0
def main():

    argument_spec = dict(
        interface=dict(required=True, type='str'),
        mode=dict(choices=['access', 'trunk'], required=False),
        access_vlan=dict(type='str', required=False),
        native_vlan=dict(type='str', required=False),
        trunk_vlans=dict(type='str', aliases=['trunk_add_vlans'], required=False),
        trunk_allowed_vlans=dict(type='str', required=False),
        state=dict(choices=['absent', 'present', 'unconfigured'], default='present')
    )

    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 = []
    results = {'changed': False}
    check_args(module, warnings)

    interface = module.params['interface']
    mode = module.params['mode']
    access_vlan = module.params['access_vlan']
    state = module.params['state']
    trunk_vlans = module.params['trunk_vlans']
    native_vlan = module.params['native_vlan']
    trunk_allowed_vlans = module.params['trunk_allowed_vlans']

    args = dict(interface=interface, 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)

    interface = interface.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(interface, 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(interface, 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(interface, 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(interface, existing, proposed, module)
            commands.append(command)
    elif state == 'unconfigured':
        is_default = is_switchport_default(existing)
        if not is_default:
            command = default_switchport_config(interface)
            commands.append(command)
    elif state == 'absent':
        command = remove_switchport_config_commands(interface, 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:
            results['changed'] = True
            load_config(module, cmds)
            if 'configure' in cmds:
                cmds.pop(0)

    results['commands'] = cmds
    results['warnings'] = warnings

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

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

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

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

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

    changed = False
    commands = []
    if state == 'present':
        if delta:
            command = get_commands_config_udld_interface1(
                delta, interface, module, existing)
            commands.append(command)
    elif state == 'absent':
        common = set(proposed.items()).intersection(existing.items())
        if common:
            command = get_commands_remove_udld_interface1(
                dict(common), interface, module, existing)
            commands.append(command)

    cmds = flatten_list(commands)
    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            changed = True
            # set the return_error to True for load_config
            msgs = load_config(module, cmds, True)
            # since there are multiple commands sent simultaneously
            # the output will have one error code for each command.
            # For commands which are successful, it is empty
            for item in msgs:
                if item:
                    err_str = ''
                    if isinstance(item, list) and item['msg']:
                        err_str = item['msg']
                    elif isinstance(item, str):
                        err_str = item
                    if 'rejecting a config that is valid only for' in err_str:
                        commands = []
                        if state == 'present':
                            command = get_commands_config_udld_interface2(
                                delta, interface, module, existing)
                        elif state == 'absent':
                            command = get_commands_remove_udld_interface2(
                                dict(common), interface, module, existing)
                        commands.append(command)

                        cmds = flatten_list(commands)
                        load_config(module, cmds)

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

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

    module.exit_json(**results)
Ejemplo n.º 46
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)

    module = AnsibleModule(
        argument_spec=argument_spec,
        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['dampening_routemap']:
        for param in DAMPENING_PARAMS:
            if module.params[param]:
                module.fail_json(msg='dampening_routemap cannot be used with'
                                     ' the {0} param'.format(param))

    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']:
        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)
Ejemplo n.º 47
0
def main():
    argument_spec = dict(
        interface=dict(required=True, type='str'),
        vni=dict(required=True, type='str'),
        assoc_vrf=dict(required=False, type='bool'),
        multicast_group=dict(required=False, type='str'),
        peer_list=dict(required=False, type='list'),
        suppress_arp=dict(required=False, type='bool'),
        ingress_replication=dict(required=False,
                                 type='str',
                                 choices=['bgp', 'static', 'default']),
        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 = {'changed': False, 'commands': [], 'warnings': warnings}

    if module.params['assoc_vrf']:
        mutually_exclusive_params = [
            'multicast_group', 'suppress_arp', 'ingress_replication'
        ]
        for param in mutually_exclusive_params:
            if module.params[param]:
                module.fail_json(msg='assoc_vrf cannot be used with '
                                 '{0} param'.format(param))
    if module.params['peer_list']:
        if module.params['ingress_replication'] != 'static':
            module.fail_json(msg='ingress_replication=static is required '
                             'when using peer_list param')
        else:
            peer_list = module.params['peer_list']
            if peer_list[0] == 'default':
                module.params['peer_list'] = 'default'
            else:
                stripped_peer_list = map(str.strip, peer_list)
                module.params['peer_list'] = stripped_peer_list

    state = module.params['state']
    args = PARAM_TO_COMMAND_KEYMAP.keys()
    existing, interface_exist = get_existing(module, args)

    if state == 'present':
        if not interface_exist:
            module.fail_json(
                msg=
                "The proposed NVE interface does not exist. Use nxos_interface to create it first."
            )
        elif interface_exist != module.params['interface']:
            module.fail_json(
                msg='Only 1 NVE interface is allowed on the switch.')
    elif state == 'absent':
        if interface_exist != module.params['interface']:
            module.exit_json(**result)
        elif existing and existing['vni'] != module.params['vni']:
            module.fail_json(
                msg="ERROR: VNI delete failed: Could not find vni node for {0}"
                .format(module.params['vni']),
                existing_vni=existing['vni'])

    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' and existing.get(key) != value:
            proposed[key] = value

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

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

    module.exit_json(**result)
Ejemplo n.º 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()))

    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)
Ejemplo n.º 49
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)

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

    warnings = list()
    check_args(module, warnings)

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

    CREATE_PARAMS = ['snapshot_name', 'description']
    ADD_PARAMS = ['section', 'show_command', 'row_id', 'element_key1']
    COMPARE_PARAMS = ['snapshot1', 'snapshot2', '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']))

    if action == 'create':
        for param in CREATE_PARAMS:
            if not module.params[param]:
                module.fail_json(msg='snapshot_name and description are '
                                 'required when action=create')
    elif action == 'add':
        for param in ADD_PARAMS:
            if not module.params[param]:
                module.fail_json(msg='section, show_command, row_id '
                                 'and element_key1 are required '
                                 'when action=add')
    elif action == 'compare':
        for param in COMPARE_PARAMS:
            if not module.params[param]:
                module.fail_json(msg='snapshot1 and snapshot2 are required '
                                 'when action=create')
    elif action == 'delete' and not module.params['snapshot_name']:
        module.fail_json(msg='snapshot_name is required when action=delete')

    existing_snapshots = invoke('get_existing', module)
    final_snapshots = existing_snapshots
    changed = False

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

    result = {}
    written_file = ''
    if module.check_mode and action != 'compare':
        module.exit_json(changed=True, commands=action_results)
    else:
        if action == 'compare':
            written_file = write_on_file(
                action_results, module.params['comparison_results_file'],
                module)
            result['updates'] = []
        else:
            if action_results:
                load_config(module, action_results)
                changed = True
                final_snapshots = invoke('get_existing', module)
                result['updates'] = action_results

                if (action == 'create'
                        and module.params['save_snapshot_locally']):
                    snapshot = get_snapshot(module)
                    written_file = write_on_file(
                        snapshot, module.params['snapshot_name'], module)

    result['changed'] = changed
    if module._verbosity > 0:
        end_state = invoke('get_existing', module)
        result['final_snapshots'] = final_snapshots
        result['existing_snapshots'] = existing_snapshots
        if written_file:
            result['report_file'] = written_file

    module.exit_json(**result)
Ejemplo n.º 50
0
def main():
    argument_spec = dict(
        master=dict(required=False, type='bool'),
        stratum=dict(required=False, type='str', default='8'),
        logging=dict(required=False, type='bool'),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    check_args(module, warnings)

    master = module.params['master']
    stratum = module.params['stratum']
    logging = module.params['logging']
    state = module.params['state']

    if stratum:
        try:
            stratum_int = int(stratum)
            if stratum_int < 1 or stratum_int > 15:
                raise ValueError
        except ValueError:
            module.fail_json(msg='stratum must be an integer between 1 and 15')

    desired = {'master': master, 'stratum': stratum, 'logging': logging}
    current = get_current(module)

    result = {'changed': False}

    commands = list()

    if state == 'absent':
        if current['master']:
            commands.append('no ntp master')
        if current['logging']:
            commands.append('no ntp logging')

    elif state == 'present':
        if desired['master'] and desired['master'] != current['master']:
            if desired['stratum']:
                commands.append('ntp master %s' % stratum)
            else:
                commands.append('ntp master')
        elif desired['stratum'] and desired['stratum'] != current['stratum']:
            commands.append('ntp master %s' % stratum)

        if desired['logging'] and desired['logging'] != current['logging']:
            if desired['logging']:
                commands.append('ntp logging')
            else:
                commands.append('no ntp logging')


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

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

    result['warnings'] = warnings

    module.exit_json(**result)
Ejemplo n.º 51
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'),
        include_defaults=dict(default=False),
        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)


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

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

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

    result = {}
    commands = []
    if state == 'absent':
        if existing:
            commands.append(['no interface port-channel{0}'.format(group)])
    elif state == 'present':
        if not interface_exist:
            command = config_portchannel(proposed, mode, group)
            commands.append(command)
            commands.insert(0, 'interface port-channel{0}'.format(group))
            WARNINGS.append("The proposed port-channel interface did not "
                            "exist. It's recommended to use nxos_interface to "
                            "create all logical interfaces.")

        elif existing and interface_exist:
            if force:
                command = get_commands_to_remove_members(proposed, existing, module)
                commands.append(command)

            command = get_commands_to_add_members(proposed, existing, module)
            commands.append(command)

            mode_command = get_commands_if_mode_change(proposed, existing,
                                                       group, mode, module)

            commands.insert(0, mode_command)

            if min_links:
                command = get_commands_min_links(existing, proposed,
                                                 group, min_links, module)
                commands.append(command)

    cmds = flatten_list(commands)
    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            load_config(module, cmds)
            changed = True
            end_state, interface_exist = get_existing(module, args)
            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

    if WARNINGS:
        results['warnings'] = WARNINGS

    module.exit_json(**results)