Esempio n. 1
0
def main():
    """ main entry point for module execution
    """
    argument_spec = dict(
        count=dict(type="int", default=5),
        dest=dict(type="str", required=True),
        source=dict(),
        interface=dict(),
        ttl=dict(type='int'),
        size=dict(type='int'),
        interval=dict(type='int'),
        state=dict(type="str", choices=["absent", "present"], default="present"),
    )

    argument_spec.update(junos_argument_spec)

    module = AnsibleModule(argument_spec=argument_spec)

    count = module.params["count"]
    dest = module.params["dest"]
    source = module.params["source"]
    size = module.params["size"]
    ttl = module.params["ttl"]
    interval = module.params["interval"]
    interface = module.params['interface']
    warnings = list()

    results = {'changed': False}
    if warnings:
        results["warnings"] = warnings

    results["commands"] = build_ping(dest, count, size, interval, source, ttl, interface)
    conn = get_connection(module)

    ping_results = conn.get(results["commands"])

    rtt_info, rate_info = None, None
    for line in ping_results.split("\n"):
        if line.startswith('round-trip'):
            rtt_info = line
        if line.startswith('%s packets transmitted' % count):
            rate_info = line

    if rtt_info:
        rtt = parse_rtt(rtt_info)
        for k, v in rtt.items():
            if rtt[k] is not None:
                rtt[k] = float(v)
        results["rtt"] = rtt

    pkt_loss, rx, tx = parse_rate(rate_info)
    results["packet_loss"] = str(pkt_loss) + "%"
    results["packets_rx"] = int(rx)
    results["packets_tx"] = int(tx)

    validate_results(module, pkt_loss, results)

    module.exit_json(**results)
Esempio n. 2
0
def load_config(module, config, commit=False):
    conn = get_connection(module)
    try:
        resp = conn.edit_config(to_list(config) + ['top'], commit)
    except ConnectionError as exc:
        module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))

    diff = resp.get('diff', '')
    return to_text(diff, errors='surrogate_then_replace').strip()
Esempio n. 3
0
def map_config_to_obj(module):
    conn = get_connection(module)
    out = conn.get(command='show configuration system services netconf')
    if out is None:
        module.fail_json(msg='unable to retrieve current config')
    config = str(out).strip()

    obj = {'state': 'absent'}
    if 'ssh' in config:
        obj.update({'state': 'present', 'netconf_port': parse_port(config)})
    return obj
Esempio n. 4
0
def load_config(module, config, commit=False):
    conn = get_connection(module)

    conn.edit_config(to_list(config) + ['top'])
    diff = conn.compare_configuration()
    if diff:
        if commit:
            commit_configuration(module)

        else:
            discard_changes(module)

    return str(diff).strip()
Esempio n. 5
0
def map_config_to_obj(module):
    conn = get_connection(module)
    out = conn.get(command='show configuration system services netconf')
    if out is None:
        module.fail_json(msg='unable to retrieve current config')
    config = str(out).strip()

    obj = {'state': 'absent'}
    if 'ssh' in config:
        obj.update({
            'state': 'present',
            'netconf_port': parse_port(config)
        })
    return obj
Esempio n. 6
0
def handle_purge(module, want):
    want_users = [item['name'] for item in want]
    element = Element('system')
    login = SubElement(element, 'login')

    conn = get_connection(module)
    reply = conn.execute_rpc(tostring(Element('get-configuration')), ignore_warning=False)
    users = reply.xpath('configuration/system/login/user/name')
    if users:
        for item in users:
            name = item.text
            if name not in want_users and name != 'root':
                user = SubElement(login, 'user', {'operation': 'delete'})
                SubElement(user, 'name').text = name
    if element.xpath('/system/login/user/name'):
        return element
Esempio n. 7
0
def load_config(module, config, commit=False):
    conn = get_connection(module)
    try:
        conn.edit_config(to_list(config) + ['top'])
        diff = conn.compare_configuration()
    except ConnectionError as exc:
        module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))

    if diff:
        if commit:
            commit_configuration(module)

        else:
            discard_changes(module)

    return to_text(diff, errors='surrogate_then_replace').strip()
Esempio n. 8
0
def handle_purge(module, want):
    want_users = [item['name'] for item in want]
    element = Element('system')
    login = SubElement(element, 'login')

    conn = get_connection(module)
    reply = conn.execute_rpc(tostring(Element('get-configuration')), ignore_warning=False)
    users = reply.xpath('configuration/system/login/user/name')
    if users:
        for item in users:
            name = item.text
            if name not in want_users and name != 'root':
                user = SubElement(login, 'user', {'operation': 'delete'})
                SubElement(user, 'name').text = name
    if element.xpath('/system/login/user/name'):
        return element
Esempio n. 9
0
def main():
    """entry point for module execution
    """
    argument_spec = dict(commands=dict(type='list'),
                         rpcs=dict(type='list'),
                         display=dict(choices=['text', 'json', 'xml', 'set'],
                                      aliases=['format', 'output']),
                         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'))

    argument_spec.update(junos_argument_spec)

    required_one_of = [('commands', 'rpcs')]

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

    warnings = list()
    conn = get_connection(module)
    capabilities = get_capabilities(module)

    if capabilities.get('network_api') == 'cliconf':
        if any((module.params['wait_for'], module.params['match'],
                module.params['rpcs'])):
            module.warn(
                'arguments wait_for, match, rpcs are not supported when using transport=cli'
            )
        commands = module.params['commands']

        output = list()
        display = module.params['display']
        for cmd in commands:
            # if display format is not mentioned in command, add the display format
            # from the modules params
            if ('display json' not in cmd) and ('display xml' not in cmd):
                if display and display != 'text':
                    cmd += ' | display {0}'.format(display)
            output.append(conn.get(command=cmd))

        lines = [out.split('\n') for out in output]
        result = {'changed': False, 'stdout': output, 'stdout_lines': lines}
        module.exit_json(**result)

    items = list()
    items.extend(parse_commands(module, warnings))
    items.extend(parse_rpcs(module))

    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 = rpc(module, items)
        transformed = list()
        output = list()
        for item, resp in zip(items, responses):
            if item['xattrs']['format'] == 'xml':
                if not HAS_JXMLEASE:
                    module.fail_json(
                        msg=
                        'jxmlease is required but does not appear to be installed. '
                        'It can be installed using `pip install jxmlease`')

                try:
                    json_resp = jxmlease.parse(resp)
                    transformed.append(json_resp)
                    output.append(json_resp)
                except:
                    raise ValueError(resp)
            else:
                transformed.append(resp)

        for item in list(conditionals):
            try:
                if item(transformed):
                    if match == 'any':
                        conditionals = list()
                        break
                    conditionals.remove(item)
            except FailedConditionalError:
                pass

        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 been satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

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

    if output:
        result['output'] = output

    module.exit_json(**result)
Esempio n. 10
0
def main():
    """entry point for module execution
    """
    argument_spec = dict(
        commands=dict(type='list'),
        rpcs=dict(type='list'),

        display=dict(choices=['text', 'json', 'xml', 'set'], aliases=['format', 'output']),

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

    argument_spec.update(junos_argument_spec)

    required_one_of = [('commands', 'rpcs')]

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

    warnings = list()
    conn = get_connection(module)
    capabilities = get_capabilities(module)

    if capabilities.get('network_api') == 'cliconf':
        if any((module.params['wait_for'], module.params['match'], module.params['rpcs'])):
            module.warn('arguments wait_for, match, rpcs are not supported when using transport=cli')
        commands = module.params['commands']

        output = list()
        display = module.params['display']
        for cmd in commands:
            # if display format is not mentioned in command, add the display format
            # from the modules params
            if ('display json' not in cmd) and ('display xml' not in cmd):
                if display and display != 'text':
                    cmd += ' | display {0}'.format(display)
            output.append(conn.get(command=cmd))

        lines = [out.split('\n') for out in output]
        result = {'changed': False, 'stdout': output, 'stdout_lines': lines}
        module.exit_json(**result)

    items = list()
    items.extend(parse_commands(module, warnings))
    items.extend(parse_rpcs(module))

    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 = rpc(module, items)
        transformed = list()
        output = list()
        for item, resp in zip(items, responses):
            if item['xattrs']['format'] == 'xml':
                if not HAS_JXMLEASE:
                    module.fail_json(msg='jxmlease is required but does not appear to be installed. '
                                         'It can be installed using `pip install jxmlease`')

                try:
                    json_resp = jxmlease.parse(resp)
                    transformed.append(json_resp)
                    output.append(json_resp)
                except:
                    raise ValueError(resp)
            else:
                transformed.append(resp)

        for item in list(conditionals):
            try:
                if item(transformed):
                    if match == 'any':
                        conditionals = list()
                        break
                    conditionals.remove(item)
            except FailedConditionalError:
                pass

        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 been satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

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

    if output:
        result['output'] = output

    module.exit_json(**result)
Esempio n. 11
0
def main():
    """ Main entry point for AnsibleModule
    """
    argument_spec = dict(
        gather_subset=dict(default=['!config'], type='list'),
        config_format=dict(default='text', choices=['xml', 'text', 'set', 'json']),
    )

    argument_spec.update(junos_argument_spec)

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

    get_connection(module)
    warnings = list()
    gather_subset = module.params['gather_subset']
    ofacts = False

    runable_subsets = set()
    exclude_subsets = set()

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

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

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Subset must be one of [%s], got %s' %
                             (', '.join(VALID_SUBSETS), 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](module))

    for inst in instances:
        inst.populate()
        facts.update(inst.facts)

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

    if ofacts:
        if HAS_PYEZ:
            ansible_facts.update(Facts(module).populate())
        else:
            warnings += ['junos-eznc is required to gather old style facts but does not appear to be installed. '
                         'It can be installed using `pip  install junos-eznc`']
    module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
Esempio n. 12
0
def main():
    """ Main entry point for AnsibleModule
    """
    argument_spec = dict(
        gather_subset=dict(default=['!config'], type='list'),
        config_format=dict(default='text',
                           choices=['xml', 'text', 'set', 'json']),
    )

    argument_spec.update(junos_argument_spec)

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

    get_connection(module)
    warnings = list()
    gather_subset = module.params['gather_subset']
    ofacts = False

    runable_subsets = set()
    exclude_subsets = set()

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

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

        if subset not in VALID_SUBSETS:
            module.fail_json(msg='Subset must be one of [%s], got %s' %
                             (', '.join(VALID_SUBSETS), 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](module))

    for inst in instances:
        inst.populate()
        facts.update(inst.facts)

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

    if ofacts:
        if HAS_PYEZ:
            ansible_facts.update(Facts(module).populate())
        else:
            warnings += [
                'junos-eznc is required to gather old style facts but does not appear to be installed. '
                'It can be installed using `pip  install junos-eznc`'
            ]
    module.exit_json(ansible_facts=ansible_facts, warnings=warnings)