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(
        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)
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)
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)
示例#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', '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(
        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)
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)
示例#8
0
def main():
    argument_spec = dict(flush_routes=dict(type='bool'),
                         enforce_rtr_alert=dict(type='bool'),
                         restart=dict(type='bool', default=False),
                         state=dict(choices=['present', 'default'],
                                    default='present'))

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    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)
示例#9
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)
示例#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()

    version = module.params['version']

    existing = get_vtp_config(module)
    end_state = existing

    args = dict(version=version)

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

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

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

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

    module.exit_json(**results)
def main():
    """ 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)
示例#12
0
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
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)
示例#15
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)
示例#16
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():
    """ 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)
示例#18
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        state=dict(default='present',
                   choices=['present', 'absent', 'enabled', 'disabled']))

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    result = {'changed': False}

    if warnings:
        result['warnings'] = warnings

    HAS_LLDP = has_lldp(module)

    commands = []

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

    result['commands'] = commands

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

        result['changed'] = True

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

    argument_spec.update(nxos_argument_spec)

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

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

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

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

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

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

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

    results['commands'] = cmds
    module.exit_json(**results)
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 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)
示例#22
0
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
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()
    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)
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 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')
示例#26
0
def main():
    argument_spec = dict(
        state=dict(choices=['enabled', 'disabled'], default='enabled'),
        group=dict(choices=['aaa', 'bfd', 'bgp', 'bridge', 'callhome', 'cfs', 'config',
                            'eigrp', 'entity', 'feature-control', 'generic', 'hsrp',
                            'license', 'link', 'lldp', 'mmode', 'ospf', 'pim',
                            'rf', 'rmon', 'snmp', 'storm-control', 'stpx',
                            'switchfabric', 'syslog', 'sysmgr', 'system', 'upgrade',
                            'vtp', 'all'],
                   required=True),
    )

    argument_spec.update(nxos_argument_spec)

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

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

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

    existing = get_snmp_traps(group, module)

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

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

    module.exit_json(**results)
示例#27
0
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
示例#28
0
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
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'),
        disable_peer_as_check=dict(required=False, type='bool'),
        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'],
                            [
                                'default_originate',
                                'default_originate_route_map'
                            ], ['allowas_in', 'allowas_in_max']],
        supports_check_mode=True,
    )

    warnings = list()
    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'
                elif key == 'send_community' and str(value).lower() == 'none':
                    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()
        if not module.check_mode:
            load_config(module, candidate)
        result['changed'] = True
        result['commands'] = candidate
    else:
        result['commands'] = []

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

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

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

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

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

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

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

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

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

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

    module.exit_json(**results)