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

    argument_spec.update(aireos_argument_spec)

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

    result = {'changed': False}

    warnings = list()
    check_args(module, warnings)
    commands = parse_commands(module, warnings)
    result['warnings'] = 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 been satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    result.update({
        'changed': False,
        'stdout': responses,
        'stdout_lines': list(to_lines(responses))
    })

    module.exit_json(**result)
Example #2
0
def main():

    command_spec = dict(command=dict(key=True), prompt=dict(), answer=dict())

    spec = dict(commands=dict(type='list',
                              elements='dict',
                              options=command_spec,
                              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'))

    spec.update(vyos_argument_spec)

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

    warnings = list()

    commands = parse_commands(module, warnings)

    wait_for = module.params['wait_for'] or list()
    try:
        conditionals = [Conditional(c) for c in wait_for]
    except AttributeError:
        exc = get_exception()
        module.fail_json(msg=str(exc))

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

    for _ in range(retries):
        responses = run_commands(module, commands)

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

            if not conditionals:
                break

            time.sleep(interval)

    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, falied_conditions=failed_conditions)

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

    module.exit_json(**result)
Example #3
0
def main():
    spec = dict(
        # { command: <str>, prompt: <str>, response: <str> }
        commands=dict(type='list', required=True),
        wait_for=dict(type='list'),
        match=dict(default='all', choices=['all', 'any']),
        retries=dict(default=10, type='int'),
        interval=dict(default=1, type='int'))

    spec.update(ocnos_argument_spec)

    module = AnsibleModule(argument_spec=spec, supports_check_mode=True)
    result = {'changed': False}

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

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

    # these commands are not supported in OcNOS VM
    notsupported_cmds = [
        "show hardware-information", "show system-information"
    ]

    while retries > 0:
        try:
            responses = run_commands(module, commands)
        except ConnectionError as exc:
            for ns_cmd in notsupported_cmds:
                if ns_cmd in str(exc):
                    commands = [cmd for cmd in commands if ns_cmd not in cmd]
        else:
            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 been satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    result.update({
        'changed': False,
        'stdout': responses,
        'stdout_lines': list(to_lines(responses))
    })

    module.exit_json(**result)
Example #4
0
def main():
    argument_spec = dict(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'))

    argument_spec.update(iosxr_argument_spec)
    argument_spec.update(command_spec)

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

    warnings = list()
    result = {'changed': False, 'warnings': warnings}
    commands = parse_commands(module, warnings)
    wait_for = module.params['wait_for'] or list()

    try:
        conditionals = [Conditional(c) for c in wait_for]
    except AttributeError as exc:
        module.fail_json(msg=to_text(exc))

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

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

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

    result.update({
        'stdout': responses,
        'stdout_lines': list(to_lines(responses)),
        'timestamps': timestamps
    })

    module.exit_json(**result)
def main():
    """main entry point for module execution
    """
    argument_spec = dict(
        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"),
    )

    argument_spec.update(ios_argument_spec)

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

    warnings = list()
    result = {"changed": False, "warnings": warnings}
    commands = parse_commands(module, warnings)
    wait_for = module.params["wait_for"] or list()

    try:
        conditionals = [Conditional(c) for c in wait_for]
    except AttributeError as exc:
        module.fail_json(msg=to_text(exc))

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

    result.update({
        "stdout": responses,
        "stdout_lines": list(to_lines(responses))
    })

    module.exit_json(**result)
Example #6
0
def main():
    """entry point for module execution
    """
    argument_spec = dict(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 = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

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

    wait_for = module.params['wait_for'] or list()
    try:
        conditionals = [Conditional(c) for c in wait_for]
    except AttributeError as exc:
        module.fail_json(msg=to_text(exc))

    commands = parse_commands(module, warnings)
    retries = module.params['retries']
    interval = module.params['interval']
    match = module.params['match']

    connection = Connection(module._socket_path)
    for attempt in range(retries):
        responses = []
        try:
            for command in commands:
                responses.append(connection.get(**command))
        except ConnectionError as exc:
            module.fail_json(msg=to_text(exc, errors='surrogate_then_replace'))

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

        if not conditionals:
            break

        time.sleep(interval)

    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.update({'stdout': responses, 'stdout_lines': to_lines(responses)})

    module.exit_json(**result)
    def execute(self):
        if self.want.normalized_commands:
            result = self.want.normalized_commands
        else:
            result = self.normalize_commands(self.want.raw_commands)
            self.want.update({'normalized_commands': result})
        if not result:
            return False
        self.notify_non_idempotent_commands(self.want.normalized_commands)

        commands = self.parse_commands()
        retries = self.want.retries
        conditionals = [Conditional(c) for c in self.want.wait_for]

        if self.module.check_mode:
            return

        while retries > 0:
            responses = self._execute(commands)
            self._check_known_errors(responses)
            for item in list(conditionals):
                if item(responses):
                    if self.want.match == 'any':
                        conditionals = list()
                        break
                    conditionals.remove(item)
            if not conditionals:
                break

            time.sleep(self.want.interval)
            retries -= 1
        else:
            failed_conditions = [item.raw for item in conditionals]
            errmsg = 'One or more conditional statements have not been satisfied.'
            raise FailedConditionsError(errmsg, failed_conditions)
        stdout_lines = self._to_lines(responses)
        changes = {
            'stdout': responses,
            'stdout_lines': stdout_lines,
            'executed_commands': self.commands
        }
        if self.want.warn:
            changes['warnings'] = self.warnings
        self.changes = Parameters(params=changes, module=self.module)
        if any(x for x in self.want.normalized_commands
               if x.startswith(self.changed_command_prefixes)):
            return True
        return False
Example #8
0
    def execute(self):
        warnings = list()
        changed = ('tmsh modify', 'tmsh create', 'tmsh delete')
        commands = self.parse_commands(warnings)
        wait_for = self.want.wait_for or list()
        retries = self.want.retries
        conditionals = [Conditional(c) for c in wait_for]

        if self.module.check_mode:
            return

        while retries > 0:
            if is_cli(self.module) and HAS_CLI_TRANSPORT:
                if self.is_tmsh():
                    for command in commands:
                        command['command'] = command['command'][4:].strip()
                responses = self._run_commands(self.module, commands)
            else:
                responses = self.execute_on_device(commands)

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

            if not conditionals:
                break

            time.sleep(self.want.interval)
            retries -= 1
        else:
            failed_conditions = [item.raw for item in conditionals]
            errmsg = 'One or more conditional statements have not been satisfied'
            raise FailedConditionsError(errmsg, failed_conditions)

        changes = {
            'stdout': responses,
            'stdout_lines': self._to_lines(responses)
        }
        if self.want.warn:
            changes['warnings'] = warnings
        self.changes = Parameters(params=changes, module=self.module)
        if any(x for x in self.want.user_commands if x.startswith(changed)):
            return True
        return False
Example #9
0
    def execute(self):
        warnings = list()

        commands = self.parse_commands(warnings)

        wait_for = self.want.wait_for or list()
        retries = self.want.retries

        conditionals = [Conditional(c) for c in wait_for]

        if self.module.check_mode:
            return

        while retries > 0:
            responses = self.execute_on_device(commands)

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

            if not conditionals:
                break

            time.sleep(self.want.interval)
            retries -= 1
        else:
            failed_conditions = [item.raw for item in conditionals]
            errmsg = 'One or more conditional statements have not been satisfied'
            raise FailedConditionsError(errmsg, failed_conditions)

        self.changes = Parameters({
            'stdout': responses,
            'stdout_lines': self._to_lines(responses),
            'warnings': warnings
        })
def main():
    spec = dict(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'),
                gather_subset=dict(default=['!config'], type='list'))

    spec.update(asa_argument_spec)

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

    warnings = list()
    check_args(module)

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

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

    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](module))

    for inst in instances:
        #results = dict()
        #results['result'] = inst.populate()
        #module.exit_json(**results)
        inst.populate()
        facts.update(inst.facts)
        warnings.extend(inst.warnings)

    ansible_facts = dict()
    for key, value in iteritems(facts):
        # this is to maintain capability with nxos_facts 2.1
        if key.startswith('_'):
            ansible_facts[key[1:]] = value
        else:
            key = 'ansible_net_%s' % key
            ansible_facts[key] = value

    module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
Example #11
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import absolute_import, division, print_function

__metaclass__ = type

from ansible.compat.tests import unittest
from ansible.module_utils.network.common.parsing import Conditional

test_results = ['result_1', 'result_2', 'result_3']
c1 = Conditional('result[1] == result_2')
c2 = Conditional('result[2] not == result_2')
c3 = Conditional('result[0] neq not result_1')


class TestNotKeyword(unittest.TestCase):
    def test_negate_instance_variable_assignment(self):
        assert c1.negate is False and c2.negate is True

    def test_key_value_instance_variable_assignment(self):
        c1_assignments = c1.key == 'result[1]' and c1.value == 'result_2'
        c2_assignments = c2.key == 'result[2]' and c2.value == 'result_2'
        assert c1_assignments and c2_assignments

    def test_conditionals_w_not_keyword(self):
        assert c1(test_results) and c2(test_results) and c3(test_results)
def main():
    '''
    Main entry point to the module
    '''

    argument_spec = dict(
        commands=dict(type='list', required=True),
        wait_for=dict(type='list', aliases=['waitfor']),
        match=dict(default='all', choices=['any', 'all']),
        retries=dict(default=10, type='int'),
        interval=dict(default=1, type='int'),
        output_file=dict(type='str', default=None),
        output_file_format=dict(type='str', default='json',
                                choices=['json', 'plain-text'])
    )

    argument_spec.update(aoscx_argument_spec)

    warnings = list()

    result = {'changed': False, 'warnings': warnings}
    module = AnsibleModule(
        argument_spec=argument_spec, supports_check_mode=True)

    commands = parse_commands(module, warnings)
    wait_for = module.params['wait_for'] or list()

    try:
        conditionals = [Conditional(c) for c in wait_for]
    except AttributeError as exc:
        module.fail_json(msg=to_text(exc))

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

    commands_list = []
    for command in commands:
        commands_list.append(command['command'])

    if module.params['output_file'] is not None:
        output_file_format = str(module.params['output_file_format'])
        if output_file_format == 'json':
            output_list = []
            for i, command in enumerate(commands_list):
                output_dict = {}
                output_dict['command'] = command
                output_dict['response'] = responses[i]
                output_list.append(output_dict)
            output_file = str(module.params['output_file'])
            with open(output_file, 'w') as output:
                json.dump(output_list, output, indent=4)
                output.write("\n")
        else:
            output_file = str(module.params['output_file'])
            with open(output_file, 'w') as output:
                for i, command in enumerate(commands_list):
                    output.write("command: ")
                    output.write(command)
                    output.write("\n")
                    output.write("response: ")
                    output.write(str(responses[i]))
                    output.write("\n")
                    output.write("------------------------------------------")
                    output.write("\n")

    result.update({
        'stdout': responses,
        'stdout_lines': list(to_lines(responses))
    })
    module.exit_json(**result)
Example #13
0
def main():
    spec = dict(commands=dict(type='list', required=True),
                wait_for=dict(type='list'),
                match=dict(default='all', choices=['all', 'any']),
                retries=dict(default=10, type='int'),
                interval=dict(default=1, type='int'))

    module = AnsibleModule(argument_spec=spec, supports_check_mode=False)
    warnings = list()
    result = {'changed': False, 'warnings': warnings}

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

    commands = parse_commands(module, warnings)
    commands = module.params['commands']
    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 been satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    for item in responses:
        if len(item) == 0:
            if module.check_mode:
                result.update({
                    'changed': False,
                    'stdout': responses,
                    'stdout_lines': list(to_lines(responses))
                })
            else:
                result.update({
                    'changed': True,
                    'stdout': responses,
                    'stdout_lines': list(to_lines(responses))
                })
        elif 'ERROR' in item:
            result.update({
                'failed': True,
                'stdout': responses,
                'stdout_lines': list(to_lines(responses))
            })
        else:
            result.update({
                'stdout': item,
                'stdout_lines': list(to_lines(responses))
            })

    module.exit_json(**result)
Example #14
0
def main():
    spec = dict(
        # { command: <str>, prompt: <str>, response: <str> }
        inside=dict(type='str', default=''),
        outside=dict(type='str', default=''),
        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'))

    spec.update(asa_argument_spec)

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

    result = {'changed': False}

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

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

    nats = []

    while retries > 0:
        if inside:
            inside_nat_command = ['show nat ' + inside]
            inside_response = run_commands(module, inside_nat_command)

            responses = inside_response[0].splitlines()

            for p in responses:
                if 'No matching NAT policy found' in p:
                    module.exit_json(msg=p)
            # Split the response to get the zone, and object names
                if 'Policies' in p or 'translate_hits' in p or len(p) < 6:
                    #module.fail_json(msg=p)
                    continue
                if p.split()[5] == 'dynamic':
                    zone = p.split()[1][1:-1]
                    source_object = p.split()[6]
                    outside_object = p.split()[8]
                    type = 'dynamic'
                elif p.split()[5] == 'static':
                    zone = p.split()[1][1:-1]
                    source_object = p.split()[6]
                    outside_object = p.split()[7]
                    type = 'static'

            # check if outside object is actually an IP address from section 2
                try:
                    IPAddress(outside_object).is_unicast()
                    outside_ip = outside_object

                except core.AddrFormatError:
                    outside_object_command = [
                        'show run object id ' + outside_object
                    ]
                    outside_object_response = run_commands(
                        module, outside_object_command)
                    outside_ip = outside_object_response[0].splitlines(
                    )[1].strip()

                if source_object == 'any':
                    inside_ip = source_object
                else:
                    inside_object_command = [
                        'show run object id ' + source_object
                    ]
                    inside_object_response = run_commands(
                        module, inside_object_command)
                    inside_ip = inside_object_response[0].splitlines(
                    )[1].strip()

                nats.append({
                    'type': type,
                    'zone': zone,
                    'source_object': source_object,
                    'outside_object': outside_object,
                    'outside_ip': outside_ip,
                    'inside_ip': inside_ip
                })

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

            if not conditionals:
                break

            time.sleep(interval)
            retries -= 1

        if outside:
            outside_nat_command = ['show nat translated ' + outside]
            outside_response = run_commands(module, outside_nat_command)

            responses = outside_response[0].splitlines()

            for p in responses:
                if 'No matching NAT policy found' in p:
                    module.exit_json(msg=p)
            # Split the response to get the zone, and object names
                if 'Policies' in p or 'translate_hits' in p or len(p) < 6:
                    #module.fail_json(msg=p)
                    continue
                if p.split()[5] == 'dynamic':
                    zone = p.split()[1][1:-1]
                    source_object = p.split()[6]
                    outside_object = p.split()[8]
                    type = 'dynamic'
                elif p.split()[5] == 'static':
                    zone = p.split()[1][1:-1]
                    source_object = p.split()[6]
                    outside_object = p.split()[7]
                    type = 'static'

            # check if outside object is actually an IP address from section 2
                try:
                    IPAddress(outside_object).is_unicast()
                    outside_ip = outside_object

                except core.AddrFormatError:
                    outside_object_command = [
                        'show run object id ' + outside_object
                    ]
                    outside_object_response = run_commands(
                        module, outside_object_command)
                    outside_ip = outside_object_response[0].splitlines(
                    )[1].strip()

                if source_object == 'any':
                    inside_ip = source_object
                else:
                    inside_object_command = [
                        'show run object id ' + source_object
                    ]
                    inside_object_response = run_commands(
                        module, inside_object_command)
                    inside_ip = inside_object_response[0].splitlines(
                    )[1].strip()

                nats.append({
                    'type': type,
                    'zone': zone,
                    'source_object': source_object,
                    'outside_object': outside_object,
                    'outside_ip': outside_ip,
                    'inside_ip': inside_ip
                })
            for item in list(conditionals):
                if item(outside_response):
                    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.update({'changed': False, 'results': nats})

    module.exit_json(**result)
Example #15
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)
            try:
                output.append(conn.get(command=cmd))
            except ConnectionError as exc:
                module.fail_json(
                    msg=to_text(exc, errors="surrogate_then_replace")
                )

        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 Exception:
                    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": list(to_lines(responses)),
    }

    if output:
        result["output"] = output

    module.exit_json(**result)
Example #16
0
def main():
    spec = dict(
        # { command: <str>, prompt: <str>, response: <str> }
        count=dict(type="int"),
        size=dict(type="size"),
        dest=dict(type="str", required=True),
        interface=dict(type="str"),
        data=dict(type="str"),
        timeout=dict(type="str"),
        validate=dict(type="bool"),
        state=dict(type="str",
                   choices=["absent", "present"],
                   default="present"),
        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'))

    spec.update(asa_argument_spec)

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

    result = {'changed': False}

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

    count = module.params['count']
    dest = module.params['dest']
    interface = module.params['interface']
    data = module.params['data']
    size = module.params['size']
    validate = module.params['validate']
    timeout = module.params['timeout']
    retries = module.params['retries']
    interval = module.params['interval']
    match = module.params['match']

    while retries > 0:
        cmds = []
        try:
            dest_ping = IPSet([IPNetwork(dest)])
            for dst in dest_ping:
                cmds.append(
                    build_ping(str(dst), count, interface, data, size, timeout,
                               validate))
        except core.AddrFormatError:
            cmds.append(
                build_ping(dest, count, interface, data, size, timeout,
                           validate))

        result["commands"] = cmds

        ping_results = run_commands(module, commands=result["commands"])
        result["results"] = []

        for ping_result in ping_results:
            destination_result = {}
            ping_results_list = ping_result.splitlines()

            stats = ""
            for line in ping_results_list:
                if line.startswith('Success'):
                    stats = line
                elif line.startswith('Sending'):
                    destination_result['destination'] = line.split(
                        ',')[1].split('to')[1]

            if stats:
                success, rx, tx, rtt = parse_ping(stats)
                loss = abs(100 - int(success))
                destination_result["packet_loss"] = str(loss) + "%"
                destination_result["packets_rx"] = int(rx)
                destination_result["packets_tx"] = int(tx)

                # Convert rtt values to int
                for k, v in rtt.items():
                    if rtt[k] is not None:
                        rtt[k] = int(v)

                destination_result["rtt"] = rtt

                destination_result["msg"] = validate_results(
                    module, loss, result)
                result["results"].append(destination_result)

        for item in list(conditionals):
            if item(inside_response):
                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)

    module.exit_json(**result)
Example #17
0
def main():
    """entry point for module execution
    """
    command_spec = dict(command=dict(key=True),
                        output=dict(),
                        prompt=dict(),
                        answer=dict())

    argument_spec = dict(
        # { command: <str>, output: <str>, prompt: <str>, response: <str> }
        commands=dict(type='list',
                      elements='dict',
                      options=command_spec,
                      required=True),
        wait_for=dict(type='list', aliases=['waitfor']),
        match=dict(default='all', choices=['any', 'all']),
        retries=dict(default=10, type='int'),
        interval=dict(default=1, type='int'))

    argument_spec.update(nxos_argument_spec)

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

    result = {'changed': False}

    warnings = list()
    commands = parse_commands(module, warnings)
    result['warnings'] = warnings

    wait_for = module.params['wait_for'] or list()

    try:
        conditionals = [Conditional(c) for c in wait_for]
    except AttributeError as exc:
        module.fail_json(msg=to_native(exc))

    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):
            try:
                if item(responses):
                    if match == 'any':
                        conditionals = list()
                        break
                    conditionals.remove(item)
            except FailedConditionalError as exc:
                module.fail_json(msg=to_native(exc))

        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.update({'stdout': responses, 'stdout_lines': to_lines(responses)})

    module.exit_json(**result)
Example #18
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)
Example #19
0
def main():
    spec = dict(
        # { command: <str>, prompt: <str>, response: <str> }
        zone=dict(type='str'),
        ip=dict(type='str'),
        mac=dict(type='str'),
        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'))

    spec.update(asa_argument_spec)

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

    result = {'changed': False}

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

    zone = module.params['zone']
    ip = module.params['ip']
    mac = module.params['mac']
    retries = module.params['retries']
    interval = module.params['interval']
    match = module.params['match']

    arps = {}
    zones = []

    while retries > 0:
        command = build_cmd(zone, ip, mac)

        response = run_commands(module, command)

        responses = response[0].splitlines()

        for p in responses:
            # Split the response to get the zone, ip, and mac address
            z = p.split()[0]
            ip = p.split()[1]
            mac = p.split()[2]
            if z in zones:
                arps[z].append({'ip': ip, 'mac_address': mac})
            else:
                zones.append(z)
                newzone = {z: [{'ip': ip, 'mac_address': mac}]}
                arps.update(newzone)

        for item in list(conditionals):
            if item(inside_response):
                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.update({'changed': False, 'results': arps})

    module.exit_json(**result)