def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        dest=dict(
            type='str',
            choices=['on', 'host', 'console', 'monitor', 'buffered', 'trap']),
        name=dict(type='str'),
        size=dict(type='int'),
        facility=dict(type='str'),
        level=dict(type='str',
                   default='debugging',
                   choices=[
                       'emergencies', 'alerts', 'critical', 'errors',
                       'warnings', 'notifications', 'informational',
                       'debugging'
                   ]),
        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(ios_argument_spec)

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

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

    device_info = get_capabilities(module)
    os_version = device_info['device_info']['network_os_version']

    warnings = list()

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

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

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

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

    module.exit_json(**result)
Exemple #2
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        prefix=dict(type='str'),
        mask=dict(type='str'),
        next_hop=dict(type='str'),
        vrf=dict(type='str'),
        interface=dict(type='str'),
        name=dict(type='str', aliases=['description']),
        admin_distance=dict(type='str'),
        track=dict(type='str'),
        tag=dict(tag='str'),
        state=dict(default='present', choices=['present', 'absent'])
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['prefix'] = 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(ios_argument_spec)

    required_one_of = [['aggregate', 'prefix']]
    required_together = [['prefix', 'mask']]
    mutually_exclusive = [['aggregate', 'prefix']]

    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, required_together=required_together)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands(want, have)
    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
    """
    element_spec = dict(name=dict(),
                        interfaces=dict(type='list'),
                        associated_interfaces=dict(type='list'),
                        delay=dict(default=10, type='int'),
                        rd=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),
                         purge=dict(default=False, type='bool'))

    argument_spec.update(element_spec)
    argument_spec.update(eos_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(module)

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

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    check_declarative_intent_params(want, module, result)

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        dest=dict(type='str', choices=['host', 'console', 'monitor', 'buffered', 'file']),
        name=dict(type='str'),
        size=dict(type='int'),
        vrf=dict(type='str', default='default'),
        facility=dict(type='str', default='local7'),
        hostnameprefix=dict(type='str'),
        level=dict(type='str', default='informational', aliases=['severity'],
                   choices=['emergencies', 'alerts', 'critical', 'errors', 'warning',
                            'notifications', 'informational', 'debugging']),
        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)

    mutually_exclusive = [('dest', 'facility', 'hostnameprefix')]

    required_if = [('dest', 'host', ['name']),
                   ('dest', 'file', ['name']),
                   ('dest', 'buffered', ['size']),
                   ('dest', 'console', ['level']),
                   ('dest', 'monitor', ['level'])]

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

    argument_spec.update(element_spec)
    argument_spec.update(iosxr_argument_spec)

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

    config_object = None
    if is_cliconf(module):
        # Commenting the below cliconf deprecation support call for Ansible 2.9 as it'll be continued to be supported
        # module.deprecate("cli support for 'iosxr_interface' is deprecated. Use transport netconf instead",
        #                  version='2.9')
        config_object = CliConfiguration(module)
    elif is_netconf(module):
        config_object = NCConfiguration(module)

    if config_object:
        result = config_object.run()
    module.exit_json(**result)
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(),
                        full_name=dict(),
                        level=dict(aliases=['role']),
                        configured_password=dict(no_log=True),
                        update_password=dict(default='always',
                                             choices=['on_create', 'always']),
                        state=dict(default='present',
                                   choices=['present', 'absent']))

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

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

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

    argument_spec.update(element_spec)
    argument_spec.update(vyos_argument_spec)

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

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

    want = map_params_to_obj(module)
    have = config_to_dict(module)
    commands = spec_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):
            commands.append('delete system login user %s' % item)

    result['commands'] = commands

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

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        group=dict(type='int'),
        mode=dict(choices=['active', 'on', 'passive', 'auto', 'desirable']),
        members=dict(type='list'),
        state=dict(default='present', choices=['present', 'absent']))

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

    required_one_of = [['group', 'aggregate']]
    required_together = [['members', 'mode']]
    mutually_exclusive = [['group', 'aggregate']]

    # 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,
                                        required_together=required_together),
                         purge=dict(default=False, type='bool'))

    argument_spec.update(element_spec)
    argument_spec.update(ios_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec,
                           required_one_of=required_one_of,
                           required_together=required_together,
                           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:
            load_config(module, commands)
        result['changed'] = True

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        dest=dict(choices=DEST_GROUP),
        name=dict(),
        size=dict(type='int'),
        facility=dict(),
        level=dict(choices=LEVEL_GROUP),
        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(eos_argument_spec)

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

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

    warnings = list()

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

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

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

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        dest=dict(type='str', choices=['console', 'file', 'global', 'host', 'user']),
        name=dict(type='str'),
        facility=dict(type='str'),
        level=dict(type='str'),
        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(vyos_argument_spec)
    required_if = [('dest', 'host', ['name', 'facility', 'level']),
                   ('dest', 'file', ['name', 'facility', 'level']),
                   ('dest', 'user', ['name', 'facility', 'level']),
                   ('dest', 'console', ['facility', 'level']),
                   ('dest', 'global', ['facility', 'level'])]

    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, required_if=required_if)
    have = config_to_dict(module)

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

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

    module.exit_json(**result)
def main():
    element_spec = dict(
        prefix=dict(type='str', aliases=['address']),
        next_hop=dict(type='str'),
        vrf=dict(type='str', default='default'),
        tag=dict(type='str'),
        route_name=dict(type='str'),
        pref=dict(type='str', aliases=['admin_distance']),
        state=dict(choices=['absent', 'present'], default='present'),
        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():
    """ main entry point for module execution
    """
    element_spec = dict(address=dict(type='str', aliases=['prefix']),
                        next_hop=dict(type='str'),
                        vrf=dict(type='str', default='default'),
                        admin_distance=dict(default=1, type='int'),
                        state=dict(default='present',
                                   choices=['present', 'absent']))

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['address'] = 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(eos_argument_spec)

    required_one_of = [['aggregate', 'address']]
    required_together = [['address', 'next_hop']]
    mutually_exclusive = [['aggregate', 'address']]

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

    address = module.params['address']
    if address is not None:
        prefix = address.split('/')[-1]

    if address and prefix:
        if '/' not in address or not validate_ip_address(
                address.split('/')[0]):
            module.fail_json(
                msg='{0} is not a valid IP address'.format(address))

        if not validate_prefix(prefix):
            module.fail_json(
                msg='Length of prefix should be between 0 and 32 bits')

    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:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    module.exit_json(**result)
Exemple #12
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(name=dict(),
                        description=dict(),
                        rd=dict(type='list'),
                        interfaces=dict(type='list'),
                        target=dict(type='list'),
                        state=dict(default='present',
                                   choices=['present', 'absent']),
                        active=dict(default=True, type='bool'),
                        table_label=dict(default=True, type='bool'))

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

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

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

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

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

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

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

    if warnings:
        result['warnings'] = warnings

    top = 'routing-instances/instance'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('name', {
            'xpath': 'name',
            'is_key': True
        }),
        ('description', 'description'),
        ('type', 'instance-type'),
        ('rd', 'route-distinguisher/rd-type'),
        ('interfaces', 'interface/name'),
        ('target', 'vrf-target/community'),
        ('table_label', {
            'xpath': 'vrf-table-label',
            'tag_only': True
        }),
    ])

    params = to_param_list(module)
    requests = list()

    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        item['type'] = 'vrf'

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
Exemple #13
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(name=dict(),
                        configured_password=dict(no_log=True),
                        nopassword=dict(type='bool'),
                        update_password=dict(default='always',
                                             choices=['on_create', 'always']),
                        privilege=dict(type='int'),
                        role=dict(),
                        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(eos_argument_spec)
    mutually_exclusive = [('name', 'aggregate')]

    module = AnsibleModule(argument_spec=argument_spec,
                           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(update_objects(want, have), module)

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

    result['commands'] = commands

    # the eos 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:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        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']),
                        admin=dict(type='bool', default=False),
                        public_key=dict(),
                        public_key_contents=dict(),
                        group=dict(aliases=['role']),
                        groups=dict(type='list', elements='dict'),
                        state=dict(default='present',
                                   choices=['present', 'absent']))
    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

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

    mutually_exclusive = [('name', 'aggregate'),
                          ('public_key', 'public_key_contents'),
                          ('group', 'groups')]

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

    argument_spec.update(element_spec)
    argument_spec.update(iosxr_argument_spec)

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

    if (module.params['public_key_contents'] or module.params['public_key']):
        if not HAS_B64:
            module.fail_json(
                msg='library base64 is required but does not appear to be '
                'installed. It can be installed using `pip install base64`')
        if paramiko is None:
            module.fail_json(
                msg='library paramiko is required but does not appear to be '
                'installed. It can be installed using `pip install paramiko`')

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

    config_object = None
    if is_cliconf(module):
        # Commenting the below cliconf deprecation support call for Ansible 2.9 as it'll be continued to be supported
        # module.deprecate("cli support for 'iosxr_interface' is deprecated. Use transport netconf instead",
        #                  version='2.9')
        config_object = CliConfiguration(module, result)
    elif is_netconf(module):
        config_object = NCConfiguration(module, result)

    if config_object:
        result = config_object.run()

    if module.params['public_key_contents'] or module.params['public_key']:
        pubkey_object = PublicKeyManager(module, result)
        result = pubkey_object.run()

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(name=dict(),
                        full_name=dict(),
                        role=dict(choices=ROLES),
                        encrypted_password=dict(no_log=True),
                        sshkey=dict(),
                        state=dict(choices=['present', 'absent'],
                                   default='present'),
                        active=dict(type='bool', default=True))

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

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

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

    argument_spec.update(element_spec)
    argument_spec.update(junos_argument_spec)

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

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

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

    want = map_params_to_obj(module)
    ele = map_obj_to_ele(module, want)

    purge_request = None
    if module.params['purge']:
        purge_request = handle_purge(module, want)

    with locked_config(module):
        if purge_request:
            load_config(module,
                        tostring(purge_request),
                        warnings,
                        action='replace')
        diff = load_config(module, tostring(ele), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
def main():
    element_spec = dict(pkg=dict(type='str'),
                        file_system=dict(type='str', default='bootflash'),
                        state=dict(choices=['absent', 'present'],
                                   default='present'))

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['pkg'] = 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)

    required_one_of = [['pkg', 'aggregate']]
    mutually_exclusive = [['pkg', 'aggregate']]

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

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

    aggregate = module.params.get('aggregate')
    objects = []
    if aggregate:
        for item in aggregate:
            for key in item:
                if item.get(key) is None:
                    item[key] = module.params[key]

            d = item.copy()
            objects.append(d)
    else:
        objects.append({
            'pkg': module.params['pkg'],
            'file_system': module.params['file_system'],
            'state': module.params['state']
        })

    for obj in objects:
        if obj['state'] == 'present':
            remote_exists = remote_file_exists(module,
                                               obj['pkg'],
                                               file_system=obj['file_system'])

            if not remote_exists:
                module.fail_json(
                    msg="The requested package doesn't exist on the device")

        cmds = install_remove_rpm(module, obj['pkg'], obj['file_system'],
                                  obj['state'])

        if cmds:
            results['changed'] = True
            results['commands'].extend(cmds)

    module.exit_json(**results)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(dest=dict(choices=['console', 'host', 'file', 'user']),
                        name=dict(),
                        facility=dict(),
                        level=dict(),
                        rotate_frequency=dict(type='int'),
                        size=dict(type='int'),
                        files=dict(type='int'),
                        src_addr=dict(),
                        state=dict(default='present',
                                   choices=['present', 'absent']),
                        active=dict(default=True, type='bool'))

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

    required_if = [('dest', 'host', ['name', 'facility', 'level']),
                   ('dest', 'file', ['name', 'facility', 'level']),
                   ('dest', 'user', ['name', 'facility', 'level']),
                   ('dest', 'console', ['facility', 'level'])]

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

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

    if warnings:
        result['warnings'] = warnings

    params = to_param_list(module)

    requests = list()
    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        module._check_required_if(required_if, param)

        item = param.copy()
        dest = item.get('dest')
        if dest == 'console' and item.get('name'):
            module.fail_json(msg="%s and %s are mutually exclusive" %
                             ('console', 'name'))

        top = 'system/syslog'
        is_facility_key = False
        field_top = None
        if dest:
            if dest == 'console':
                field_top = dest
                is_facility_key = True
            else:
                field_top = dest + '/contents'
                is_facility_key = False

        param_to_xpath_map = collections.OrderedDict()
        param_to_xpath_map.update([
            ('name', {
                'xpath': 'name',
                'is_key': True,
                'top': dest
            }),
            ('facility', {
                'xpath': 'name',
                'is_key': is_facility_key,
                'top': field_top
            }),
            ('size', {
                'xpath': 'size',
                'leaf_only': True,
                'is_key': True,
                'top': 'archive'
            }),
            ('files', {
                'xpath': 'files',
                'leaf_only': True,
                'is_key': True,
                'top': 'archive'
            }),
            ('rotate_frequency', {
                'xpath': 'log-rotate-frequency',
                'leaf_only': True
            }),
        ])

        if item.get('level'):
            param_to_xpath_map['level'] = {
                'xpath': item.get('level'),
                'tag_only': True,
                'top': field_top
            }

        validate_param_values(module, param_to_xpath_map, param=item)

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    diff = None
    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    hashed_password_spec = dict(type=dict(type='int', required=True),
                                value=dict(no_log=True, required=True))

    element_spec = dict(name=dict(),
                        configured_password=dict(no_log=True),
                        hashed_password=dict(no_log=True,
                                             type='dict',
                                             options=hashed_password_spec),
                        nopassword=dict(type='bool'),
                        update_password=dict(default='always',
                                             choices=['on_create', 'always']),
                        password_type=dict(default='secret',
                                           choices=['secret', 'password']),
                        privilege=dict(type='int'),
                        view=dict(aliases=['role']),
                        sshkey=dict(type='list'),
                        state=dict(default='present',
                                   choices=['present', 'absent']))
    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

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

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

    argument_spec.update(element_spec)
    argument_spec.update(ios_argument_spec)

    mutually_exclusive = [('name', 'aggregate'),
                          ('nopassword', 'hashed_password',
                           'configured_password')]

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

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

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

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

    if module.params['purge']:
        want_users = [x['name'] for x in want]
        have_users = [x['name'] for x in have]
        for item in set(have_users).difference(want_users):
            if item != 'admin':
                commands.append(user_del_cmd(item))

    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
    """
    element_spec = dict(
        name=dict(),
        configured_password=dict(no_log=True),
        update_password=dict(default='always', choices=['on_create', 'always']),
        roles=dict(type='list', aliases=['role']),
        sshkey=dict(),
        state=dict(default='present', choices=['present', 'absent'])
    )

    aggregate_spec = deepcopy(element_spec)

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

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

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

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

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

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

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

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

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

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

    result['commands'] = commands

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

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

    module.exit_json(**result)
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        address=dict(aliases=['prefix']),
        next_hop=dict(),
        preference=dict(type='int', aliases=['admin_distance']),
        qualified_next_hop=dict(type='str'),
        qualified_preference=dict(type='int'),
        state=dict(default='present', choices=['present', 'absent']),
        active=dict(default=True, type='bool')
    )

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['address'] = 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(junos_argument_spec)

    required_one_of = [['aggregate', 'address']]
    mutually_exclusive = [['aggregate', 'address']]

    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

    top = 'routing-options/static/route'

    param_to_xpath_map = collections.OrderedDict()
    param_to_xpath_map.update([
        ('address', {'xpath': 'name', 'is_key': True}),
        ('next_hop', 'next-hop'),
        ('preference', 'preference/metric-value'),
        ('qualified_next_hop', {'xpath': 'name', 'top': 'qualified-next-hop'}),
        ('qualified_preference', {'xpath': 'preference', 'top': 'qualified-next-hop'})
    ])

    params = to_param_list(module)
    requests = list()

    for param in params:
        # if key doesn't exist in the item, get it from module.params
        for key in param:
            if param.get(key) is None:
                param[key] = module.params[key]

        item = param.copy()
        if item['state'] == 'present':
            if not item['address'] and item['next_hop']:
                module.fail_json(msg="parameters are required together: ['address', 'next_hop']")

        want = map_params_to_obj(module, param_to_xpath_map, param=item)
        requests.append(map_obj_to_ele(module, want, top, param=item))

    with locked_config(module):
        for req in requests:
            diff = load_config(module, tostring(req), warnings, action='merge')

        commit = not module.check_mode
        if diff:
            if commit:
                commit_configuration(module)
            else:
                discard_changes(module)
            result['changed'] = True

            if module._diff:
                result['diff'] = {'prepared': diff}

    module.exit_json(**result)