Exemplo n.º 1
0
def run_module():
    # define the available arguments/parameters that a user can pass to
    # the module
    module_args = dict(
        network=dict(type='str', required=True),
        snapshot=dict(type='str', required=True),
        session=dict(type='dict', required=True),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
        summary='',
        ansible_facts={},
    )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    if not pybatfish_found:
        module.fail_json(msg='Python module Pybatfish is required')

    if module.check_mode:
        return result

    network = module.params['network']
    snapshot = module.params['snapshot']
    session_params = module.params.get('session', {})

    try:
        session = create_session(**session_params)
    except Exception as e:
        message = 'Failed to establish session with Batfish service: {}'.format(
            e)
        module.fail_json(msg=message, **result)
        return

    try:
        session.set_network(network)
        session.set_snapshot(snapshot)
    except Exception as e:
        message = 'Failed to set snapshot: {}'.format(e)
        module.fail_json(msg=message, **result)

    result['summary'] = "Snapshot set to '{}' on network '{}'".format(
        snapshot, network)
    result['result'] = {
        'network': network,
        'snapshot': snapshot,
    }
    result['ansible_facts']['bf_snapshot'] = snapshot
    result['ansible_facts']['bf_network'] = network
    module.exit_json(**result)
Exemplo n.º 2
0
def run_module():
    # define the available arguments/parameters that a user can pass to
    # the module
    module_args = dict(
        host=dict(type='str', required=True),
        name=dict(type='str', required=False, default='default'),
        parameters=dict(type='dict', required=False),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
        session='',
        summary='',
        ansible_facts={},
    )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    if not pybatfish_found:
        module.fail_json(msg='Python module Pybatfish is required')

    if module.check_mode:
        return result

    host = module.params['host']
    name = module.params['name']
    parameters = module.params['parameters']

    if parameters is None:
        parameters = {}
    parameters['host'] = host

    # Allow a few retries in case the service isn't ready yet
    retry_time = 0
    while True:
        try_start_time = datetime.now()
        try:
            create_session(**parameters)
            break
        except Exception as session_e:
            if retry_time < _MAX_RETRY_TIME:
                try_time = (datetime.now() - try_start_time).seconds
                sleep_time = max(_RETRY_DELAY - try_time,
                                 1)  # sleep at least 1 second
                time.sleep(sleep_time)
                retry_time += try_time + sleep_time
            else:
                message = 'Failed to establish session with Batfish service: {}'.format(
                    session_e)
                module.fail_json(msg=message, **result)

    # Overall status of command execution
    result['summary'] = "Session established to '{}' ({})".format(host, name)
    result['session'] = parameters
    result['changed'] = True
    result['ansible_facts']['bf_session'] = parameters
    module.exit_json(**result)
Exemplo n.º 3
0
def run_module():
    # define the available arguments/parameters that a user can pass to
    # the module
    module_args = dict(
        assertions=dict(type='list', required=False, default='.*'),
        network=dict(type='str', required=True),
        snapshot=dict(type='str', required=True),
        session=dict(type='dict', required=True),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
        result='',
        summary='',
    )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    if not pybatfish_found:
        module.fail_json(msg='Python module Pybatfish is required')

    assertions = module.params.get('assertions')
    session_params = module.params.get('session')
    network = module.params.get('network')
    snapshot = module.params.get('snapshot')

    issues = [i for i in [get_assertion_issues(a) for a in assertions] if i]
    if any(issues):
        message = ('{} of {} assertions are malformed'.format(
            len(issues), len(assertions)) + ', no assertions run')
        result['result'] = issues
        module.fail_json(msg=message, **result)

    if module.check_mode:
        module.exit_json(**result)

    results = []
    failed = []
    summary = 'Assertion(s) completed successfully'

    try:
        session = create_session(**session_params)
    except Exception as e:
        message = 'Failed to establish session with Batfish service: {}'.format(
            e)
        module.fail_json(msg=message, **result)
        return

    try:
        set_snapshot(session=session, network=network, snapshot=snapshot)
    except Exception as e:
        message = 'Failed to set snapshot: {}'.format(e)
        module.fail_json(msg=message, **result)
        return

    for assertion in assertions:
        status = 'Pass'
        try:
            assert_result = run_assertion(session, assertion)
            if assert_result != ASSERT_PASS_MESSAGE:
                failed.append(assert_result)
                status = 'Fail'
        except Exception as e:
            assert_result = str(e)
            failed.append(assert_result)
            status = 'Error'

        results.append({
            'name': assertion['name'],
            'type': assertion['type'],
            'status': status,
            'details': assert_result,
        })
    if failed:
        summary = '{} of {} assertions failed'.format(len(failed),
                                                      len(assertions))

    result['summary'] = summary
    result['result'] = results
    # Indicate failure to Ansible in the case of failed assert(s)
    if failed:
        module.fail_json(msg=summary, **result)

    module.exit_json(**result)
Exemplo n.º 4
0
def run_module():
    # define the available arguments/parameters that a user can pass to
    # the module
    module_args = dict(
        network=dict(type='str', required=True),
        snapshot=dict(type='str', required=True),
        contact_info=dict(type='str', required=False),
        dry_run=dict(type='bool', required=False, default=True),
        netconan_config=dict(type='str', required=False),
        session=dict(type='dict', required=True),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
        summary='',
    )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    if not pybatfish_found:
        module.fail_json(msg='Python module Pybatfish is required')

    if module.check_mode:
        return result

    network = module.params['network']
    snapshot = module.params['snapshot']
    contact_info = module.params.get('contact_info')
    netconan_config = module.params.get('netconan_config')
    dry_run = module.params['dry_run']
    session_params = module.params.get('session', {})

    try:
        session = create_session(**session_params)
    except Exception as e:
        message = 'Failed to establish session with Batfish service: {}'.format(
            e)
        module.fail_json(msg=message, **result)
        return

    try:
        session.set_network(network)
        session.set_snapshot(snapshot)
    except Exception as e:
        message = 'Failed to find snapshot {} in network {}: {}'.format(
            snapshot, network, e)
        module.fail_json(msg=message, **result)

    if netconan_config:
        if not os.path.isfile(netconan_config):
            message = 'Specified netconan_config is invalid. Must specify a file.'
            module.fail_json(msg=message, **result)

    try:
        upload_result = session.upload_diagnostics(
            dry_run=dry_run,
            netconan_config=netconan_config,
            contact_info=contact_info)
        if dry_run:
            summary = 'Diagnostics for snapshot {} on network {} written to temporary directory: {}'.format(
                snapshot, network, upload_result)
        else:
            summary = 'Diagnostics for snapshot {} on network {} uploaded successfully.'.format(
                snapshot, network)
    except Exception as e:
        message = 'Failed to upload diagnostics: {}'.format(e)
        module.fail_json(msg=message, **result)
        return

    result['summary'] = summary
    module.exit_json(**result)
Exemplo n.º 5
0
def run_module():
    # define the available arguments/parameters that a user can pass to
    # the module
    module_args = dict(
        nodes=dict(type='str', required=False, default='.*'),
        network=dict(type='str', required=True),
        snapshot=dict(type='str', required=True),
        output_directory=dict(type='str', required=False),
        session=dict(type='dict', required=True),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
        result='',
        summary='',
    )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True
    )

    if not pybatfish_found:
        module.fail_json(msg='Python module Pybatfish is required')

    if module.check_mode:
        return result

    output_directory = module.params['output_directory']
    nodes = module.params['nodes']
    session_params = module.params.get('session', {})
    network = module.params.get('network')
    snapshot = module.params.get('snapshot')

    try:
        session = create_session(**session_params)
    except Exception as e:
        message = 'Failed to establish session with Batfish service: {}'.format(
            e)
        module.fail_json(msg=message, **result)
        return

    try:
        set_snapshot(session=session, network=network, snapshot=snapshot)
    except Exception as e:
        message = 'Failed to set snapshot: {}'.format(e)
        module.fail_json(msg=message, **result)
        return

    try:
        facts = session.extract_facts(nodes=nodes,
                                      output_directory=output_directory)
        if not get_node_count(facts):
            result['warnings'] = [
                'No nodes found matching node specifier "{}". See here for details on how to use node specifiers: {}'.format(
                    nodes, NODE_SPECIFIER_INSTRUCTIONS_URL)]
    except Exception as e:
        message = 'Failed to extract facts: {}'.format(e)
        module.fail_json(msg=message, **result)
        return

    summary = "Got facts for nodes: '{}'".format(nodes)
    if output_directory:
        summary += ', wrote facts to directory: {}'.format(output_directory)

    # Overall status of command execution
    result['summary'] = summary
    result['result'] = facts
    module.exit_json(**result)
Exemplo n.º 6
0
def run_module():
    # define the available arguments/parameters that a user can pass to
    # the module
    module_args = dict(
        network=dict(type='str', required=True),
        snapshot=dict(type='str', required=True),
        expected_facts=dict(type='str', required=True),
        session=dict(type='dict', required=True),
    )

    # seed the result dict in the object
    # we primarily care about changed and state
    # change is if this module effectively modified the target
    # state will include any data that you want your module to pass back
    # for consumption, for example, in a subsequent task
    result = dict(
        changed=False,
        result='',
        summary='',
    )

    # the AnsibleModule object will be our abstraction working with Ansible
    # this includes instantiation, a couple of common attr would be the
    # args/params passed to the execution, as well as if the module
    # supports check mode
    module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)

    if not pybatfish_found:
        module.fail_json(msg='Python module Pybatfish is required')

    if module.check_mode:
        return result

    input_directory = module.params['expected_facts']
    session_params = module.params.get('session', {})
    network = module.params.get('network')
    snapshot = module.params.get('snapshot')

    try:
        session = create_session(**session_params)
    except Exception as e:
        message = 'Failed to establish session with Batfish service: {}'.format(
            e)
        module.fail_json(msg=message, **result)
        return

    try:
        set_snapshot(session=session, network=network, snapshot=snapshot)
    except Exception as e:
        message = 'Failed to set snapshot: {}'.format(e)
        module.fail_json(msg=message, **result)
        return

    try:
        failures = session.validate_facts(expected_facts=input_directory)
    except Exception as e:
        message = 'Failed to validate facts: {}'.format(e)
        module.fail_json(msg=message, **result)
        return

    summary = 'Actual facts match expected facts'
    if failures:
        summary = 'Validation failed for the following nodes: {}.'.format(
            list(failures.keys()))

    # Overall status of command execution
    result['summary'] = summary
    result['result'] = failures
    # Indicate failure to Ansible in the case of failed validation
    if failures:
        module.fail_json(msg=summary, **result)

    module.exit_json(**result)