Example #1
0
def main():
    """ Main entry point for Ansible module execution
    """
    argument_spec = dict(hostname=dict(),
                         domain_name=dict(),
                         domain_search=dict(type='list'),
                         name_servers=dict(type='list'),
                         lookup_source=dict(),
                         lookup_enabled=dict(type='bool'),
                         state=dict(choices=['present', 'absent'],
                                    default='present'))

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

    result = {'changed': False}

    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['changed'] = True

    module.exit_json(**result)
Example #2
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        hostname=dict(),
        domain_name=dict(),
        domain_list=dict(type='list'),

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

        # { server: <str>; vrf: <str> }
        name_servers=dict(type='list'),
        state=dict(default='present', choices=['present', 'absent']))

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

    result = {'changed': False}

    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)
Example #3
0
def main():
    argument_spec = dict(
        host_name=dict(type='str'),
        domain_name=dict(type='str'),
        domain_search=dict(type='list'),
        name_server=dict(type='list'),
        state=dict(type='str',
                   default='present',
                   choices=['present', 'absent']),
    )

    module = LocalAnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        mutually_exclusive=[('domain_name', 'domain_search')],
    )

    result = {'changed': False}
    want = dict(module.params)
    have = config_to_dict(module)

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

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

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

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

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

    result = {'changed': False}

    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)
Example #5
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(_raw_params=dict())

    module = LocalAnsibleModule(argument_spec=argument_spec,
                                supports_check_mode=False)

    if str(module.params['_raw_params']).strip() == '':
        module.fail_json(rc=256, msg='no command given')

    result = {'changed': True}

    rc, out, err = module.exec_command(module.params['_raw_params'])

    try:
        out = module.from_json(out)
    except ValueError:
        if out:
            out = str(out).strip()
            result['stdout_lines'] = out.split('\n')

    result.update({'rc': rc, 'stdout': out, 'stderr': str(err).strip()})

    module.exit_json(**result)
Example #6
0
def main():
    """main entry point for module execution
    """
    argument_spec = dict(
        src=dict(type='path'),
        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact',
                                            'none']),
        replace=dict(default='line', choices=['line', 'block', 'config']),

        # this argument is deprecated in favor of setting match: none
        # it will be removed in a future version
        force=dict(default=False, type='bool'),
        config=dict(),
        backup=dict(type='bool', default=False),
        comment=dict(default=DEFAULT_COMMIT_COMMENT),
    )

    argument_spec.update(_transitional_argument_spec())

    mutually_exclusive = [('lines', 'src')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines']),
                   ('replace', 'config', ['src'])]

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

    if module.params['force'] is True:
        module.params['match'] = 'none'

    warnings = list()
    check_args(module, warnings)

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

    if module.params['backup']:
        result['__backup__'] = get_config(module)

    run(module, result)

    module.exit_json(**result)
Example #7
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        src=dict(),
        force=dict(default=False, type='bool'),
        include_defaults=dict(default=True, type='bool'),
        backup=dict(default=False, type='bool'),
        config=dict(),
    )

    # Removed the use of provider arguments in 2.3 due to network_cli
    # connection plugin.  To be removed in 2.5
    argument_spec.update(_transitional_argument_spec())

    mutually_exclusive = [('config', 'backup'), ('config', 'force')]

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

    warnings = check_args(module)

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

    candidate = NetworkConfig(contents=module.params['src'], indent=1)

    result = {'changed': False}

    if module.params['backup']:
        result['__backup__'] = get_config()

    if not module.params['force']:
        contents = get_current_config(module)
        configobj = NetworkConfig(contents=contents, indent=1)
        commands = candidate.difference(configobj)
        commands = dumps(commands, 'commands').split('\n')
        commands = [str(c).strip() for c in commands if c]
    else:
        commands = [c.strip() for c in str(candidate).split('\n')]

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

    result['updates'] = commands

    module.exit_json(**result)
Example #8
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(vrfs=dict(type='list'),
                         name=dict(),
                         description=dict(),
                         rd=dict(),
                         interfaces=dict(type='list'),
                         purge=dict(type='bool', default=False),
                         state=dict(default='present',
                                    choices=['present', 'absent']))

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

    module = LocalAnsibleModule(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_vrfs = [x['name'] for x in want]
        have_vrfs = [x['name'] for x in have]
        for item in set(have_vrfs).difference(want_vrfs):
            cmd = 'no vrf definition %s' % item
            if cmd not in commands:
                commands.append(cmd)

    result['commands'] = commands

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

    module.exit_json(**result)
Example #9
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        http=dict(aliases=['enable_http'], type='bool'),
        http_port=dict(type='int'),
        https=dict(aliases=['enable_https'], type='bool'),
        https_port=dict(type='int'),
        local_http=dict(aliases=['enable_local_http'], type='bool'),
        local_http_port=dict(type='int'),
        socket=dict(aliases=['enable_socket'], type='bool'),
        vrf=dict(default='default'),
        state=dict(default='started', choices=['stopped', 'started']),
    )

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

    result = {'changed': False}

    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

    collect_facts(module, result)

    module.exit_json(**result)
Example #10
0
def main():
    argument_spec = dict(
        src=dict(type='path'),
        lines=dict(type='list'),

        match=dict(default='line', choices=['line', 'none']),

        comment=dict(default=DEFAULT_COMMENT),

        config=dict(),

        backup=dict(type='bool', default=False),
        save=dict(type='bool', default=False),
    )

    mutually_exclusive = [('lines', 'src')]

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

    result = dict(changed=False, warnings=[])

    if module.params['backup']:
        result['__backup__'] = get_config(module=module)

    if any((module.params['src'], module.params['lines'])):
        run(module, result)

    if module.params['save']:
        if not module.check_mode:
            run_commands(module, ['save'])
        result['changed'] = True

    module.exit_json(**result)
Example #11
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(users=dict(type='list', no_log=True),
                         username=dict(),
                         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(),
                         purge=dict(type='bool', default=False),
                         state=dict(default='present',
                                    choices=['present', 'absent']))

    mutually_exclusive = [('username', 'users')]

    module = LocalAnsibleModule(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['username'] for x in want]
        have_users = [x['username'] 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)
Example #12
0
def main():
    spec = dict(
        # { command: <str>, output: <str>, prompt: <str>, response: <str> }
        commands=dict(type='list', required=True),
        wait_for=dict(type='list', aliases=['waitfor']),
        match=dict(default='all', choices=['all', 'any']),
        retries=dict(default=10, type='int'),
        interval=dict(default=1, type='int'))

    module = LocalAnsibleModule(argument_spec=spec, supports_check_mode=True)

    warnings = list()
    commands = parse_commands(module, warnings)

    wait_for = module.params['wait_for'] or list()
    conditionals = [Conditional(c) for c in wait_for]

    retries = module.params['retries']
    interval = module.params['interval']
    match = module.params['match']

    while retries > 0:
        responses = run_commands(module, commands)

        for item in list(conditionals):
            if item(responses):
                if match == 'any':
                    conditionals = list()
                    break
                conditionals.remove(item)

        if not conditionals:
            break

        time.sleep(interval)
        retries -= 1

    if conditionals:
        failed_conditions = [item.raw for item in conditionals]
        msg = 'One or more conditional statements have not be satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    result = {
        'changed': False,
        'stdout': responses,
        'warnings': warnings,
        'stdout_lines': list(to_lines(responses))
    }

    module.exit_json(**result)
Example #13
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        src=dict(type='path'),
        lines=dict(aliases=['commands'], type='list'),
        parents=dict(type='list'),
        before=dict(type='list'),
        after=dict(type='list'),
        match=dict(default='line', choices=['line', 'strict', 'exact',
                                            'none']),
        replace=dict(default='line', choices=['line', 'block']),
        multiline_delimiter=dict(default='@'),

        # this argument is deprecated (2.2) in favor of setting match: none
        # it will be removed in a future version
        force=dict(default=False, type='bool'),
        config=dict(),
        defaults=dict(type='bool', default=False),
        backup=dict(type='bool', default=False),
        save=dict(type='bool', default=False),
    )

    argument_spec.update(_transitional_argument_spec())

    mutually_exclusive = [('lines', 'src')]

    required_if = [('match', 'strict', ['lines']),
                   ('match', 'exact', ['lines']),
                   ('replace', 'block', ['lines'])]

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

    if module.params['force'] is True:
        module.params['match'] = 'none'

    warnings = list()
    check_args(module, warnings)

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

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

        candidate, want_banners = get_candidate(module)

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

        banners = diff_banners(want_banners, have_banners)

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

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

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

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

            # send the configuration commands to the device and merge
            # them with the current running config
            if not module.check_mode:
                if commands:
                    load_config(module, commands)
                if banners:
                    load_banners(module, banners)

            result['changed'] = True

    if module.params['backup']:
        result['__backup__'] = get_config()

    if module.params['save']:
        if not module.check_mode:
            run_commands(module, ['copy running-config startup-config'])
        result['changed'] = True

    module.exit_json(**result)
Example #14
0
def main():
    spec = dict(
        gather_subset=dict(default=['!config'], type='list')
    )

    module = LocalAnsibleModule(argument_spec=spec, supports_check_mode=True)

    gather_subset = module.params['gather_subset']

    runable_subsets = set()
    exclude_subsets = set()

    for subset in gather_subset:
        if subset == 'all':
            runable_subsets.update(VALID_SUBSETS)
            continue

        if subset.startswith('!'):
            subset = subset[1:]
            if subset == 'all':
                exclude_subsets.update(VALID_SUBSETS)
                continue
            exclude = True
        else:
            exclude = False

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Bad subset')

        if exclude:
            exclude_subsets.add(subset)
        else:
            runable_subsets.add(subset)

    if not runable_subsets:
        runable_subsets.update(VALID_SUBSETS)

    runable_subsets.difference_update(exclude_subsets)
    runable_subsets.add('default')

    facts = dict()
    facts['gather_subset'] = list(runable_subsets)

    instances = list()
    for key in runable_subsets:
        instances.append(FACT_SUBSETS[key]())

    try:
        for inst in instances:
            commands = inst.commands()
            responses = run_commands(module, commands)
            results = dict(zip(commands, responses))
            inst.populate(results)
            facts.update(inst.facts)
    except Exception:
        module.exit_json(out=module.from_json(results))

    ansible_facts = dict()
    for key, value in iteritems(facts):
        key = 'ansible_net_%s' % key
        ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts)