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()
    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)
Esempio n. 2
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',
                'any_other', 'maintenance'
            ]),
        state=dict(choices=['absent', 'present', 'default'],
                   default='present',
                   required=False))

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

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

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

    result['warnings'] = warnings

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

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

    if stratum and master is False:
        if stratum != 8:
            module.fail_json(msg='master MUST be True when stratum is changed')

    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 master and not current['master']:
            commands.append('ntp master')
        elif master is False and current['master']:
            commands.append('no ntp master')
        if stratum and stratum != current['stratum']:
            commands.append('ntp master %s' % stratum)

        if logging and not current['logging']:
            commands.append('ntp logging')
        elif logging is False and current['logging']:
            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)
def main():
    argument_spec = dict(
        echo_interface=dict(required=False, type='str'),
        echo_rx_interval=dict(required=False, type='int'),
        interval=dict(required=False, type='dict'),
        slow_timer=dict(required=False, type='int'),
        startup_timer=dict(required=False, type='int'),
        ipv4_echo_rx_interval=dict(required=False, type='int'),
        ipv4_interval=dict(required=False, type='dict'),
        ipv4_slow_timer=dict(required=False, type='int'),
        ipv6_echo_rx_interval=dict(required=False, type='int'),
        ipv6_interval=dict(required=False, type='dict'),
        ipv6_slow_timer=dict(required=False, type='int'),
        fabricpath_interval=dict(required=False, type='dict'),
        fabricpath_slow_timer=dict(required=False, type='int'),
        fabricpath_vlan=dict(required=False, type='int'),
    )
    argument_spec.update(nxos_argument_spec)
    module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
    warnings = list()

    cmd_ref = NxosCmdRef(module, BFD_CMD_REF)
    cmd_ref.get_existing()
    cmd_ref.get_playvals()
    cmds = reorder_cmds(cmd_ref.get_proposed())

    result = {'changed': False, 'commands': cmds, 'warnings': warnings,
              'check_mode': module.check_mode}
    if cmds:
        result['changed'] = True
        if not module.check_mode:
            load_config(module, cmds)

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

    aggregate_spec = deepcopy(element_spec)

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

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

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

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

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

    result = {'changed': False}

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

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

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

    result['commands'] = commands

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

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

    module.exit_json(**result)
Esempio n. 6
0
def main():
    argument_spec = dict(
        bfd=dict(required=False, type='str', choices=['enable', 'disable']),
        ssm_range=dict(required=False, type='list', default=[]),
    )

    argument_spec.update(nxos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)
    warnings = list()
    result = {'changed': False, 'commands': [], 'warnings': warnings}

    params = module.params
    args = [k for k in PARAM_TO_COMMAND_KEYMAP.keys() if params[k] is not None]

    # SSM syntax check
    if 'ssm_range' in args:
        for item in params['ssm_range']:
            if re.search('none|default', item):
                break
            if len(item.split('.')) != 4:
                module.fail_json(msg="Valid ssm_range values are multicast addresses "
                                     "or the keyword 'none' or the keyword 'default'.")

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

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

        elif key == 'bfd':
            if value != existing.get('bfd', 'disable'):
                proposed[key] = value

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

    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)
Esempio n. 7
0
def main():
    argument_spec = dict(
        name=dict(required=False, type='str'),
        interface=dict(required=True),
        direction=dict(required=True, choices=['egress', 'ingress']),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

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

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

    proposed = dict(name=name, interface=interface, direction=direction)

    existing = check_for_acl_int_present(module, name, interface, direction)

    cmds = []
    commands = []
    if state == 'present':
        if not existing:
            command = apply_acl(proposed)
            if command:
                commands.append(command)

    elif state == 'absent':
        if existing:
            command = remove_acl(proposed)
            if command:
                commands.append(command)

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

    results['commands'] = cmds

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

    argument_spec.update(nxos_argument_spec)

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

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

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

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

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

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

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

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

    state = module.params['state']

    commands = list()

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

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

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

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

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

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

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

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

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

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

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

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

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

    result['warnings'] = warnings

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

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

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

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

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

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

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

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

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

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

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    version = module.params['version']

    existing = get_vtp_config(module)
    end_state = existing

    args = dict(version=version)

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

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

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

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

    module.exit_json(**results)
def check_install_in_progress(module, commands, opts):
    for attempt in range(20):
        data = parse_show_install(load_config(module, commands, True, opts))
        if data['install_in_progress']:
            sleep(1)
            continue
        break
    return data
Esempio n. 14
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(type='str', aliases=['vrf']),
        description=dict(type='str'),
        vni=dict(type='str'),
        rd=dict(type='str'),
        admin_state=dict(type='str', default='up', choices=['up', 'down']),
        interfaces=dict(type='list'),
        associated_interfaces=dict(type='list'),
        delay=dict(type='int', default=10),
        state=dict(type='str',
                   default='present',
                   choices=['present', 'absent']),
    )

    aggregate_spec = deepcopy(element_spec)

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

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

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

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

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

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

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

    if commands and not module.check_mode:
        responses = load_config(module,
                                commands,
                                opts={'catch_clierror': True})
        vrf_error_check(module, commands, responses)
        result['changed'] = True

    check_declarative_intent_params(want, module, element_spec, result)

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

    aggregate_spec = deepcopy(element_spec)

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

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

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

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

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

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

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

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

    module.exit_json(**result)
Esempio n. 16
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        http=dict(aliases=['enable_http'], type='bool', default=True),
        http_port=dict(type='int', default=80),
        https=dict(aliases=['enable_https'], type='bool', default=False),
        https_port=dict(type='int', default=443),
        sandbox=dict(aliases=['enable_sandbox'], type='bool'),
        state=dict(default='present', choices=['started', 'stopped', 'present', 'absent']),
        ssl_strong_ciphers=dict(type='bool', default=False),
        tlsv1_0=dict(type='bool', default=True),
        tlsv1_1=dict(type='bool', default=False),
        tlsv1_2=dict(type='bool', default=False)
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    warning_msg = "Module nxos_nxapi currently defaults to configure 'http port 80'. "
    warning_msg += "Default behavior is changing to configure 'https port 443'"
    warning_msg += " when params 'http, http_port, https, https_port' are not set in the playbook"
    module.deprecate(msg=warning_msg, version="2.11")

    capabilities = get_capabilities(module)

    check_args(module, warnings, capabilities)

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

    commands = map_obj_to_commands(want, have, module, warnings, capabilities)

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

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

    module.exit_json(**result)
Esempio n. 17
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='str'),
        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()

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

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

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

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

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

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    HAS_LLDP = has_lldp(module)

    commands = []

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

    result['commands'] = commands

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

        result['changed'] = True

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

    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:
            msgs = load_config(module, commands, True)
            if msgs:
                for item in msgs:
                    if item:
                        if isinstance(item, dict):
                            err_str = item['clierror']
                        else:
                            err_str = item
                        if 'more than 40 lines' in err_str or 'buffer overflowed' in err_str:
                            load_config(module, commands)

        result['changed'] = True

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

    argument_spec.update(nxos_argument_spec)

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

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

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

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

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

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

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

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

    argument_spec.update(nxos_argument_spec)

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

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

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

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

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

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

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

    else:
        result['commands'] = []
    module.exit_json(**result)
def config_cmd_operation(module, cmd):
    iteration = 0
    while iteration < 10:
        msg = load_config(module, [cmd], True)
        if msg:
            if 'another install operation is in progress' in msg[0].lower(
            ) or 'failed' in msg[0].lower():
                time.sleep(2)
                iteration += 1
            else:
                return
        else:
            return
Esempio n. 23
0
def main():
    argument_spec = dict(
        nv_overlay_evpn=dict(required=True, type='bool'),
    )

    argument_spec.update(nxos_argument_spec)

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

    result = {'changed': False}

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

    config = get_config(module)
    commands = list()

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

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

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

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

    result['commands'] = commands

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

    argument_spec.update(nxos_argument_spec)

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

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

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

    existing = get_snmp_traps(group, module)

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

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

    module.exit_json(**results)
Esempio n. 25
0
def main():
    argument_spec = dict(
        contact=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()
    results = {'changed': False, 'commands': [], 'warnings': warnings}

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

    existing = get_snmp_contact(module)
    commands = []

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

    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)
Esempio n. 26
0
def vrf_error_check(module, commands, responses):
    """Checks for VRF config errors and executes a retry in some circumstances.
    """
    pattern = 'ERROR: Deletion of VRF .* in progress'
    if re.search(pattern, str(responses)):
        # Allow delay/retry for VRF changes
        time.sleep(15)
        responses = load_config(module,
                                commands,
                                opts={'catch_clierror': True})
        if re.search(pattern, str(responses)):
            module.fail_json(msg='VRF config (and retry) failure: %s ' %
                             responses)
        module.warn('VRF config delayed by VRF deletion - passed on retry')
def check_mode_nextgen(module, issu, image, kick=None):
    """Use the 'install all impact' command for check_mode"""
    opts = {'ignore_timeout': True}
    commands = build_install_cmd_set(issu, image, kick, 'impact')
    data = parse_show_install(load_config(module, commands, True, opts))
    # If an error is encountered when issu is 'desired' then try again
    # but set issu to 'no'
    if data['error'] and issu == 'desired':
        issu = 'no'
        commands = build_install_cmd_set(issu, image, kick, 'impact')
        # The system may be busy from the previous call to check_mode so loop
        # until it's done.
        data = check_install_in_progress(module, commands, opts)
    if data['server_error']:
        data['error'] = True
    data['upgrade_cmd'] = commands
    return data
def activate_reload(module, pkg, flag):
    iteration = 0
    if flag:
        cmd = 'install activate {0} forced'.format(pkg)
    else:
        cmd = 'install deactivate {0} forced'.format(pkg)
    opts = {'ignore_timeout': True}
    while iteration < 10:
        msg = load_config(module, [cmd], True, opts)
        if msg:
            if isinstance(msg[0], int):
                if msg[0] == -32603:
                    return cmd
            elif isinstance(msg[0], str):
                if 'another install operation is in progress' in msg[0].lower(
                ) or 'failed' in msg[0].lower():
                    time.sleep(2)
                    iteration += 1
Esempio n. 29
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(type='str', aliases=['interface']),
        mode=dict(choices=['access', 'trunk']),
        access_vlan=dict(type='str'),
        native_vlan=dict(type='str'),
        trunk_vlans=dict(type='str', aliases=['trunk_add_vlans']),
        trunk_allowed_vlans=dict(type='str'),
        state=dict(choices=['absent', 'present', 'unconfigured'], default='present')
    )

    aggregate_spec = deepcopy(element_spec)

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

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

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

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

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

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

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

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

        name = name.lower()

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

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

        current_mode = get_interface_mode(name, module)

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

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

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

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

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

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

            existing['trunk_vlans_list'] = existing_trunks_list
            proposed['trunk_vlans_list'] = trunk_vlans_list

        current_vlans = get_list_of_vlans(module)

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

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

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

    result['commands'] = cmds
    result['warnings'] = warnings

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

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

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

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

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

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

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

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

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

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

    module.exit_json(**result)