def main(): spec = dict( commands=dict(type='list', required=True), wait_for=dict(type='list'), retries=dict(default=10, type='int'), interval=dict(default=1, type='int') ) module = NetworkModule(argument_spec=spec, connect_on_load=False, supports_check_mode=True) commands = module.params['commands'] conditionals = module.params['wait_for'] or list() warnings = list() runner = CommandRunner(module) for cmd in commands: if module.check_mode and not cmd.startswith('show'): warnings.append('only show commands are supported when using ' 'check mode, not executing `%s`' % cmd) else: if cmd.startswith('conf'): module.fail_json(msg='dellos10_command does not support running ' 'config mode commands. Please use ' 'dellos10_config instead') runner.add_command(cmd) for item in conditionals: runner.add_conditional(item) runner.retries = module.params['retries'] runner.interval = module.params['interval'] try: runner.run() except FailedConditionsError: exc = get_exception() module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions) except NetworkError: exc = get_exception() module.fail_json(msg=str(exc)) result = dict(changed=False) result['stdout'] = list() for cmd in commands: try: output = runner.get_command(cmd) except ValueError: output = 'command not executed due to check_mode, see warnings' result['stdout'].append(output) result['warnings'] = warnings result['stdout_lines'] = list(to_lines(result['stdout'])) module.exit_json(**result)
def execute_show(cmds, module, command_type=None): command_type_map = { 'cli_show': 'json', 'cli_show_ascii': 'text' } try: if command_type: response = module.execute(cmds, command_type=command_type) else: response = module.execute(cmds) except ShellError: clie = get_exception() module.fail_json(msg='Error sending {0}'.format(cmds), error=str(clie)) except AttributeError: try: if command_type: command_type = command_type_map.get(command_type) module.cli.add_commands(cmds, output=command_type) response = module.cli.run_commands() else: module.cli.add_commands(cmds, raw=True) response = module.cli.run_commands() except ShellError: clie = get_exception() module.fail_json(msg='Error sending {0}'.format(cmds), error=str(clie)) return response
def execute_config_command(commands, module): try: module.configure(commands) except ShellError: clie = get_exception() module.fail_json(msg='Error sending CLI commands', error=str(clie), commands=commands) except AttributeError: try: module.config.load_config(commands) except NetworkError: clie = get_exception() module.fail_json(msg='Error sending CLI commands', error=str(clie), commands=commands)
def execute_config_command(commands, module): try: module.configure(commands) except ShellError: clie = get_exception() module.fail_json(msg="Error sending CLI commands", error=str(clie), commands=commands) except AttributeError: try: commands.insert(0, "configure") module.cli.add_commands(commands, output="config") module.cli.run_commands() except ShellError: clie = get_exception() module.fail_json(msg="Error sending CLI commands", error=str(clie), commands=commands)
def has_match(module, ssid, api_url, api_pwd, api_usr, body): compare_keys = ['syncIntervalMinutes', 'syncWarnThresholdMinutes', 'recoveryWarnThresholdMinutes', 'repoUtilizationWarnThreshold'] desired_state = dict((x, (body.get(x))) for x in compare_keys) label_exists = False matches_spec = False current_state = None async_id = None api_data = None desired_name = body.get('name') endpoint = 'storage-systems/%s/async-mirrors' % ssid url = api_url + endpoint try: rc, data = request(url, url_username=api_usr, url_password=api_pwd, headers=HEADERS) except Exception: error = get_exception() module.exit_json(exception="Error finding a match. Message: %s" % str(error)) for async_group in data: if async_group['label'] == desired_name: label_exists = True api_data = async_group async_id = async_group['groupRef'] current_state = dict( syncIntervalMinutes=async_group['syncIntervalMinutes'], syncWarnThresholdMinutes=async_group['syncCompletionTimeAlertThresholdMinutes'], recoveryWarnThresholdMinutes=async_group['recoveryPointAgeAlertThresholdMinutes'], repoUtilizationWarnThreshold=async_group['repositoryUtilizationWarnThreshold'], ) if current_state == desired_state: matches_spec = True return label_exists, matches_spec, api_data, async_id
def __init__(self, *args, **kwargs): connect_on_load = kwargs.pop('connect_on_load', True) argument_spec = NET_TRANSPORT_ARGS.copy() argument_spec['transport']['choices'] = NET_CONNECTIONS.keys() argument_spec.update(NET_CONNECTION_ARGS.copy()) if kwargs.get('argument_spec'): argument_spec.update(kwargs['argument_spec']) kwargs['argument_spec'] = argument_spec super(NetworkModule, self).__init__(*args, **kwargs) self.connection = None self._cli = None self._config = None try: transport = self.params['transport'] or '__default__' cls = NET_CONNECTIONS[transport] self.connection = cls() except KeyError: self.fail_json(msg='Unknown transport or no default transport specified') except (TypeError, NetworkError): exc = get_exception() self.fail_json(msg=to_native(exc)) if connect_on_load: self.connect()
def main(): argument_spec = dict( checkpoint_file=dict(required=False), rollback_to=dict(required=False), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False) ) module = get_network_module(argument_spec=argument_spec, mutually_exclusive=[['checkpoint_file', 'rollback_to']], supports_check_mode=False) checkpoint_file = module.params['checkpoint_file'] rollback_to = module.params['rollback_to'] status = None filename = None changed = False try: if checkpoint_file: checkpoint(checkpoint_file, module) status = 'checkpoint file created' elif rollback_to: rollback(rollback_to, module) status = 'rollback executed' changed = True filename = rollback_to or checkpoint_file except ShellError: clie = get_exception() module.fail_json(msg=str(clie)) module.exit_json(changed=changed, status=status, filename=filename)
def run_commands(self, commands, **kwargs): response = list() fmt = kwargs.get('format') or 'xml' for cmd in to_list(commands): try: resp = self.device.cli(command=cmd, format=fmt) response.append(resp) except (ValueError, RpcError): exc = get_exception() self._fail('Unable to get cli output: %s' % str(exc)) except Exception: exc = get_exception() self._fail('Uncaught exception - please report: %s' % str(exc)) return response
def unlock_config(self): try: self.config.unlock() self._locked = False except UnlockError: exc = get_exception() self.module.log('unable to unlock config: {0}'.format(str(exc)))
def main(): argument_spec = dict( flush_routes=dict(type='bool'), enforce_rtr_alert=dict(type='bool'), restart=dict(type='bool', default=False), state=dict(choices=['present', 'default'], default='present'), include_defaults=dict(default=False), config=dict(), save=dict(type='bool', default=False) ) module = get_network_module(argument_spec=argument_spec, supports_check_mode=True) state = module.params['state'] restart = module.params['restart'] if (state == 'default' and (module.params['flush_routes'] is not None or module.params['enforce_rtr_alert'] is not None)): module.fail_json(msg='When state=default other params have no effect.') args = [ "flush_routes", "enforce_rtr_alert", ] existing = invoke('get_existing', module, args) end_state = existing proposed = dict((k, v) for k, v in module.params.iteritems() if v is not None and k in args) proposed_args = proposed.copy() if state == 'default': proposed_args = dict((k, False) for k in args) result = {} if (state == 'present' or (state == 'default' and True in existing.values()) or restart): candidate = CustomNetworkConfig(indent=3) invoke('get_commands', module, existing, proposed_args, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result['updates'] = [] if restart: proposed['restart'] = restart result['connected'] = module.connected if module._verbosity > 0: end_state = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed module.exit_json(**result)
def get_cli_exception(exc=None): """Get cli exception message""" msg = list() if not exc: exc = get_exception() if exc: errs = str(exc).split("\r\n") for err in errs: if not err: continue if "matched error in response:" in err: continue if " at '^' position" in err: err = err.replace(" at '^' position", "") if err.replace(" ", "") == "^": continue if len(err) > 2 and err[0] in ["<", "["] and err[-1] in [">", "]"]: continue if err[-1] == ".": err = err[:-1] if err.replace(" ", "") == "": continue msg.append(err) else: msg = ["Error: Fail to get cli exception message."] while msg[-1][-1] == ' ': msg[-1] = msg[-1][:-1] if msg[-1][-1] != ".": msg[-1] += "." return ", ".join(msg).capitalize()
def execute(self, commands): try: return self.shell.send(commands) except ShellError: exc = get_exception() commands = [str(c) for c in commands] raise NetworkError(to_native(exc), commands=commands)
def get_module(connect_on_load=True, **kwargs): argument_spec = NET_TRANSPORT_ARGS.copy() argument_spec['transport']['choices'] = NET_CONNECTIONS.keys() argument_spec.update(NET_CONNECTION_ARGS.copy()) if kwargs.get('argument_spec'): argument_spec.update(kwargs['argument_spec']) kwargs['argument_spec'] = argument_spec module = NetworkModule(**kwargs) try: transport = module.params['transport'] or '__default__' cls = NET_CONNECTIONS[transport] module.connection = cls() except KeyError: module.fail_json(msg='Unknown transport or no default transport specified') except (TypeError, NetworkError): exc = get_exception() module.fail_json(msg=exc.message) if connect_on_load: connect(module) return module
def disconnect(module): try: if module.connected: module.connection.disconnect() except NetworkError: exc = get_exception() module.fail_json(msg=exc.message)
def load_config_session(self, config, commit=False, replace=False): """ Loads the configuration into the remote device """ session = 'ansible_%s' % int(time.time()) commands = ['configure session %s' % session] if replace: commands.append('rollback clean-config') commands.extend(config) if commands[-1] != 'end': commands.append('end') try: self.execute(commands) diff = self.diff_config(session) if commit: self.commit_config(session) else: self.execute(['no configure session %s' % session]) except NetworkError: exc = get_exception() if 'timeout trying to send command' in to_native(exc): # try to get control back and get out of config mode if isinstance(self, Cli): self.execute(['\x03', 'end']) self.abort_config(session) diff = None raise return diff
def request(url, data=None, headers=None, method='GET', use_proxy=True, force=False, last_mod_time=None, timeout=10, validate_certs=True, url_username=None, url_password=None, http_agent=None, force_basic_auth=False, ignore_errors=False): try: r = open_url(url=url, data=data, headers=headers, method=method, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=url_username, url_password=url_password, http_agent=http_agent, force_basic_auth=force_basic_auth) except HTTPError: err = get_exception() r = err.fp try: raw_data = r.read() if raw_data: data = json.loads(raw_data) else: data = None except: if ignore_errors: pass else: raise Exception(raw_data) resp_code = r.getcode() if resp_code >= 400 and not ignore_errors: raise Exception(resp_code, data) else: return resp_code, data
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 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(default=False, type='bool'), ) mutually_exclusive = [('lines', 'src')] required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines'])] module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, 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__'] = module.config.get_config() try: run(module, result) except NetworkError: exc = get_exception() module.disconnect() module.fail_json(msg=str(exc)) module.disconnect() module.exit_json(**result)
def connect(self, params, kickstart=True): host = params['host'] port = params.get('port') or 22 username = params['username'] password = params.get('password') key_file = params.get('ssh_keyfile') timeout = params['timeout'] try: self.shell = Shell( kickstart=kickstart, prompts_re=self.CLI_PROMPTS_RE, errors_re=self.CLI_ERRORS_RE, timeout=timeout ) self.shell.open(host, port=port, username=username, password=password, key_filename=key_file) except ShellError: exc = get_exception() raise NetworkError(msg='failed to connect to %s:%s' % (host, port), exc=to_native(exc)) self._connected = True
def main(): """ main entry point for module execution """ argument_spec = dict( rollback_location=dict(), local_max_checkpoints=dict(type='int'), remote_max_checkpoints=dict(type='int'), rescue_location=dict(), state=dict(default='present', choices=['present', 'absent']) ) module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, supports_check_mode=True) state = module.params['state'] result = dict(changed=False) commands = list() invoke(state, module, commands) try: load_config(module, commands, result) except NetworkError: exc = get_exception() module.fail_json(msg=str(exc), **exc.kwargs) module.exit_json(**result)
def lock_config(self): try: self.config.lock() self._locked = True except LockError: exc = get_exception() self.module.log('unable to lock config: {0}'.format(str(exc)))
def main(): argument_spec = dict( ip_address=dict(required=True), password=dict(no_log=True), username=dict(default='admin'), api_key=dict(no_log=True), cmd=dict(required=True) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['api_key', 'password']]) if not HAS_LIB: module.fail_json(msg='Missing required libraries.') ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] api_key = module.params['api_key'] cmd = module.params['cmd'] # Create the device with the appropriate pandevice type device = base.PanDevice.create_from_device(ip_address, username, password, api_key=api_key) changed = False try: xml_output = device.op(cmd, xml=True) changed = True except PanXapiError: exc = get_exception() if 'non NULL value' in exc.message: # rewrap and call again cmd_array = cmd.split() cmd_array_len = len(cmd_array) cmd_array[cmd_array_len - 1] = '\"' + cmd_array[cmd_array_len - 1] + '\"' cmd2 = ' '.join(cmd_array) try: xml_output = device.op(cmd2, xml=True) changed = True except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) obj_dict = xmltodict.parse(xml_output) json_output = json.dumps(obj_dict) module.exit_json(changed=changed, msg="Done", stdout=json_output, stdout_xml=xml_output)
def execute_config_command(commands, module): try: output = module.configure(commands) except ShellError: clie = get_exception() module.fail_json(msg='Error sending CLI commands', error=str(clie), commands=commands) except AttributeError: try: commands.insert(0, 'configure') module.cli.add_commands(commands, output='config') output = module.cli.run_commands() except ShellError: clie = get_exception() module.fail_json(msg='Error sending CLI commands', error=str(clie), commands=commands) return output
def disconnect(self): try: if self.connected: self.connection.disconnect() self.log('disconnected from %s' % self.params['host']) except NetworkError: exc = get_exception() self.fail_json(msg=to_native(exc))
def invoke(self, method, *args, **kwargs): try: return method(*args, **kwargs) except AttributeError: exc = get_exception() raise NetworkError('undefined method "%s"' % method.__name__, exc=str(exc)) except NotImplementedError: raise NetworkError('method not supported "%s"' % method.__name__)
def connect(module): try: if not module.connected: module.connection.connect(module.params) if module.params['authorize']: module.connection.authorize(module.params) except NetworkError: exc = get_exception() module.fail_json(msg=exc.message)
def main(): argument_spec = dict( vrf=dict(required=True, type="str"), safi=dict(required=True, type="str", choices=["unicast", "multicast"]), afi=dict(required=True, type="str", choices=["ipv4", "ipv6"]), route_target_both_auto_evpn=dict(required=False, type="bool"), m_facts=dict(required=False, default=False, type="bool"), state=dict(choices=["present", "absent"], default="present", required=False), include_defaults=dict(default=False), config=dict(), save=dict(type="bool", default=False), ) module = get_network_module(argument_spec=argument_spec, supports_check_mode=True) state = module.params["state"] args = ["vrf", "safi", "afi", "route_target_both_auto_evpn"] existing = invoke("get_existing", module, args) end_state = existing proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) proposed = {} for key, value in proposed_args.items(): if key != "interface": if str(value).lower() == "default": value = PARAM_TO_DEFAULT_KEYMAP.get(key) if value is None: value = "default" if existing.get(key) or (not existing.get(key) and value): proposed[key] = value result = {} if state == "present" or (state == "absent" and existing): candidate = CustomNetworkConfig(indent=3) invoke("state_%s" % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result["updates"] = [] result["connected"] = module.connected if module._verbosity > 0: end_state = invoke("get_existing", module, args) result["end_state"] = end_state result["existing"] = existing result["proposed"] = proposed_args if WARNINGS: result["warnings"] = WARNINGS module.exit_json(**result)
def execute_config(module, candidate): result = {} try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) return result
def connect(self): cls = globals().get(str(self.params['transport']).capitalize()) try: self.connection = cls(self) except TypeError: e = get_exception() self.fail_json(msg=e.message) self.connection.connect()
def main(): """ main entry point for module execution """ argument_spec = dict( http=dict(aliases=['enable_http'], default=True, type='bool', setter='set_http'), http_port=dict(default=80, type='int', setter='set_http'), https=dict(aliases=['enable_https'], default=False, type='bool', setter='set_https'), https_port=dict(default=443, type='int', setter='set_https'), sandbox=dict(aliases=['enable_sandbox'], default=False, type='bool'), # Only allow configuration of NXAPI using cli transport transport=dict(required=True, choices=['cli']), config=dict(), # Support for started and stopped is for backwards capability only and # will be removed in a future version state=dict(default='present', choices=['started', 'stopped', 'present', 'absent']) ) module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, supports_check_mode=True) state = module.params['state'] warnings = list() result = dict(changed=False, warnings=warnings) if state == 'started': state = 'present' warnings.append('state=started is deprecated and will be removed in a ' 'a future release. Please use state=present instead') elif state == 'stopped': state = 'absent' warnings.append('state=stopped is deprecated and will be removed in a ' 'a future release. Please use state=absent instead') commands = list() instance = get_instance(module) invoke(state, module, instance, commands) try: load(module, commands, result) except (ValueError, NetworkError): load_checkpoint(module, result) exc = get_exception() module.fail_json(msg=str(exc), **exc.kwargs) clean_result(result) module.exit_json(**result)
def commit_config(self, comment=None, confirm=None): try: kwargs = dict(comment=comment) if confirm and confirm > 0: kwargs['confirm'] = confirm return self.config.commit(**kwargs) except CommitError: exc = get_exception() msg = 'Unable to commit configuration: {0}'.format(str(exc)) self._fail(msg=msg)
def main(): argument_spec = dict(ip_address=dict(required=True), password=dict(required=True), username=dict(default='admin'), api_key=dict(no_log=True), dag_match_filter=dict(type='str', default=None), dag_name=dict(required=True), tag_name=dict(type='list', required=False), commit=dict(type='bool', default=True), devicegroup=dict(default=None), description=dict(default=None), operation=dict(type='str', required=True, choices=['add', 'list', 'delete'])) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['api_key', 'password']]) if not HAS_LIB: module.fail_json(msg='Missing required libraries.') ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] api_key = module.params['api_key'] operation = module.params['operation'] ag_object = create_address_group_object( address_gp_name=module.params.get('dag_name', None), dynamic_value=module.params.get('dag_match_filter', None), description=module.params.get('description', None), tag_name=module.params.get('tag_names', None)) commit = module.params['commit'] devicegroup = module.params['devicegroup'] # Create the device with the appropriate pandevice type device = base.PanDevice.create_from_device(ip_address, username, password, api_key=api_key) # If Panorama, validate the devicegroup dev_group = None if devicegroup and isinstance(device, panorama.Panorama): dev_group = get_devicegroup(device, devicegroup) if dev_group: device.add(dev_group) else: module.fail_json( msg= '\'%s\' device group not found in Panorama. Is the name correct?' % devicegroup) result = None if operation == 'add': result = add_address_group(device, dev_group, ag_object) elif operation == 'list': result, exc = get_all_address_group(device) elif operation == 'delete': result, exc = delete_address_group(device, group_name=module.params.get( 'dag_name', None)) if result and commit: try: device.commit(sync=True) except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) module.exit_json(changed=True, msg=result)
def main(): argument_spec = dict(interface=dict(required=True, type='str'), description=dict(required=False, type='str'), host_reachability=dict(required=False, type='bool'), shutdown=dict(required=False, type='bool'), source_interface=dict(required=False, type='str'), source_interface_hold_down_time=dict(required=False, type='str'), m_facts=dict(required=False, default=False, type='bool'), state=dict(choices=['present', 'absent'], default='present', required=False), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False)) module = get_network_module(argument_spec=argument_spec, supports_check_mode=True) state = module.params['state'] interface = module.params['interface'].lower() args = [ 'interface', 'description', 'host_reachability', 'shutdown', 'source_interface', 'source_interface_hold_down_time' ] existing = invoke('get_existing', module, args) end_state = existing proposed_args = dict((k, v) for k, v in module.params.iteritems() if v is not None and k in args) proposed = {} for key, value in proposed_args.iteritems(): if key != 'interface': if str(value).lower() == 'true': value = True elif str(value).lower() == 'false': value = False elif str(value).lower() == 'default': value = PARAM_TO_DEFAULT_KEYMAP.get(key) if value is None: if key in BOOL_PARAMS: value = False else: value = 'default' if existing.get(key) or (not existing.get(key) and value): proposed[key] = value result = {} if state == 'present' or (state == 'absent' and existing): if not existing: WARNINGS.append("The proposed NVE interface did not exist. " "It's recommended to use nxos_interface to create " "all logical interfaces.") candidate = CustomNetworkConfig(indent=3) invoke('state_%s' % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result['updates'] = [] result['connected'] = module.connected if module._verbosity > 0: end_state = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed_args if WARNINGS: result['warnings'] = WARNINGS module.exit_json(**result)
def main(): argument_spec = dict(ip_address=dict(required=True), password=dict(no_log=True), username=dict(default='admin'), api_key=dict(no_log=True), vsys_id=dict(default='vsys1'), rule_type=dict(required=True, choices=['security', 'nat']), source_zone=dict(default=None), source_ip=dict(default=None), source_user=dict(default=None), source_port=dict(default=None, type=int), to_interface=dict(default=None), destination_zone=dict(default=None), category=dict(default=None), application=dict(default=None), protocol=dict(default=None, type=int), destination_ip=dict(default=None), destination_port=dict(default=None, type=int)) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['api_key', 'password']]) if not HAS_LIB: module.fail_json(msg='Missing required libraries.') ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] api_key = module.params['api_key'] vsys_id = module.params['vsys_id'] rule_type = module.params['rule_type'] source_zone = module.params['source_zone'] source_ip = module.params['source_ip'] source_user = module.params['source_user'] source_port = module.params['source_port'] to_interface = module.params['to_interface'] destination_zone = module.params['destination_zone'] destination_ip = module.params['destination_ip'] destination_port = module.params['destination_port'] category = module.params['category'] application = module.params['application'] protocol = module.params['protocol'] # Create the device with the appropriate pandevice type device = base.PanDevice.create_from_device(ip_address, username, password, api_key=api_key) # Fail the module if this is a Panorama instance if isinstance(device, panorama.Panorama): module.fail_json(failed=1, msg='Panorama is not supported.') # Create and attach security and NAT rulebases. Then populate them. sec_rule_base = nat_rule_base = policies.Rulebase() device.add(sec_rule_base) device.add(nat_rule_base) policies.SecurityRule.refreshall(sec_rule_base) policies.NatRule.refreshall(nat_rule_base) # Which action shall we take on the object? if rule_type == 'security': # Search for the object test_string = create_security_test(source_ip=source_ip, source_user=source_user, destination_ip=destination_ip, destination_port=destination_port, application=application, protocol=protocol, category=category) elif rule_type == 'nat': test_string = create_nat_test(source_zone=source_zone, source_ip=source_ip, source_port=source_port, to_interface=to_interface, destination_zone=destination_zone, destination_ip=destination_ip, destination_port=destination_port, protocol=protocol) # Submit the op command with the appropriate test string try: response = device.op(cmd=test_string, vsys=vsys_id) except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) if response.find('result/rules').__len__() == 1: rule_name = response.find('result/rules/entry').text.split(';')[0] elif rule_type == 'nat': module.exit_json(msg='No matching NAT rule.') else: module.fail_json( msg='Rule match failed. Please check playbook syntax.') if rule_type == 'security': rule_match = sec_rule_base.find(rule_name, policies.SecurityRule) elif rule_type == 'nat': rule_match = nat_rule_base.find(rule_name, policies.NatRule) # Print out the rule module.exit_json(stdout_lines=json.dumps(xmltodict.parse( rule_match.element_str()), indent=2), msg='Rule matched')
def main(): argument_spec = dict( ip_address=dict(required=True), password=dict(required=True, no_log=True), username=dict(default='admin'), rule_name=dict(required=True), description=dict(default=''), tag=dict(), to_zone=dict(type='list', default=['any']), from_zone=dict(type='list', default=['any']), source=dict(type='list', default=["any"]), source_user=dict(type='list', default=['any']), destination=dict(type='list', default=["any"]), category=dict(type='list', default=['any']), application=dict(type='list', default=['any']), service=dict(type='list', default=['application-default']), hip_profiles=dict(type='list', default=['any']), group_profile=dict(), antivirus=dict(), vulnerability=dict(), spyware=dict(), url_filtering=dict(), file_blocking=dict(), data_filtering=dict(), wildfire_analysis=dict(), log_start=dict(type='bool', default=False), log_end=dict(type='bool', default=True), rule_type=dict(default='universal'), action=dict(default='allow'), commit=dict(type='bool', default=True) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] rule_name = module.params['rule_name'] description = module.params['description'] tag = module.params['tag'] from_zone = module.params['from_zone'] to_zone = module.params['to_zone'] source = module.params['source'] source_user = module.params['source_user'] destination = module.params['destination'] category = module.params['category'] application = module.params['application'] service = module.params['service'] hip_profiles = module.params['hip_profiles'] log_start = module.params['log_start'] log_end = module.params['log_end'] rule_type = module.params['rule_type'] action = module.params['action'] group_profile = module.params['group_profile'] antivirus = module.params['antivirus'] vulnerability = module.params['vulnerability'] spyware = module.params['spyware'] url_filtering = module.params['url_filtering'] file_blocking = module.params['file_blocking'] data_filtering = module.params['data_filtering'] wildfire_analysis = module.params['wildfire_analysis'] commit = module.params['commit'] fw = pandevice.firewall.Firewall(ip_address, username, password) if security_rule_exists(fw, rule_name): module.fail_json(msg='Rule with the same name already exists.') try: sec_rule = create_security_rule( rule_name=rule_name, description=description, tag=tag, from_zone=from_zone, to_zone=to_zone, source=source, source_user=source_user, destination=destination, category=category, application=application, service=service, hip_profiles=hip_profiles, group_profile=group_profile, antivirus=antivirus, vulnerability=vulnerability, spyware=spyware, url_filtering=url_filtering, file_blocking=file_blocking, data_filtering=data_filtering, wildfire_analysis=wildfire_analysis, log_start=log_start, log_end=log_end, rule_type=rule_type, action=action ) changed = add_security_rule(fw, sec_rule) except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) if changed and commit: fw.commit(sync=True) module.exit_json(changed=changed, msg="okey dokey")
def execute(self, commands, **kwargs): try: return self.shell.send(commands) except ShellError: exc = get_exception() raise NetworkError(exc.message, commands=commands)
def main(): argument_spec = dict( ip_address=dict(required=True), password=dict(no_log=True), username=dict(default='admin'), api_key=dict(no_log=True), operation=dict(default='add', choices=['add', 'update', 'delete', 'find']), rule_name=dict(required=True), description=dict(default=''), tag_name=dict(type='list'), destination_zone=dict(type='list', default=['any']), source_zone=dict(type='list', default=['any']), source_ip=dict(type='list', default=["any"]), source_user=dict(type='list', default=['any']), destination_ip=dict(type='list', default=["any"]), category=dict(type='list', default=['any']), application=dict(type='list', default=['any']), service=dict(type='list', default=['application-default']), hip_profiles=dict(type='list', default=['any']), group_profile=dict(), antivirus=dict(), vulnerability=dict(), spyware=dict(), url_filtering=dict(), file_blocking=dict(), data_filtering=dict(), wildfire_analysis=dict(), log_start=dict(type='bool', default=False), log_end=dict(type='bool', default=True), rule_type=dict(default='universal'), action=dict(default='allow'), devicegroup=dict(), commit=dict(type='bool', default=True) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['api_key', 'password']]) if not HAS_LIB: module.fail_json(msg='Missing required libraries.') ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] api_key = module.params['api_key'] operation = module.params['operation'] rule_name = module.params['rule_name'] description = module.params['description'] tag_name = module.params['tag_name'] source_zone = module.params['source_zone'] source_ip = module.params['source_ip'] source_user = module.params['source_user'] hip_profiles = module.params['hip_profiles'] destination_zone = module.params['destination_zone'] destination_ip = module.params['destination_ip'] application = module.params['application'] service = module.params['service'] category = module.params['category'] log_start = module.params['log_start'] log_end = module.params['log_end'] action = module.params['action'] group_profile = module.params['group_profile'] antivirus = module.params['antivirus'] vulnerability = module.params['vulnerability'] spyware = module.params['spyware'] url_filtering = module.params['url_filtering'] file_blocking = module.params['file_blocking'] data_filtering = module.params['data_filtering'] wildfire_analysis = module.params['wildfire_analysis'] rule_type = module.params['rule_type'] devicegroup = module.params['devicegroup'] commit = module.params['commit'] # Create the device with the appropriate pandevice type device = base.PanDevice.create_from_device(ip_address, username, password, api_key=api_key) # If Panorama, validate the devicegroup dev_group = None if devicegroup and isinstance(device, panorama.Panorama): dev_group = get_devicegroup(device, devicegroup) if dev_group: device.add(dev_group) else: module.fail_json(msg='\'%s\' device group not found in Panorama. Is the name correct?' % devicegroup) # Get the rulebase rulebase = get_rulebase(device, dev_group) # Which action shall we take on the object? if operation == "find": # Search for the object match = find_rule(rulebase, rule_name) # If found, format and return the result if match: match_dict = xmltodict.parse(match.element_str()) module.exit_json( stdout_lines=json.dumps(match_dict, indent=2), msg='Rule matched' ) else: module.fail_json(msg='Rule \'%s\' not found. Is the name correct?' % rule_name) elif operation == "delete": # Search for the object match = find_rule(rulebase, rule_name) # If found, delete it if match: try: if commit: match.delete() except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) module.exit_json(changed=True, msg='Rule \'%s\' successfully deleted' % rule_name) else: module.fail_json(msg='Rule \'%s\' not found. Is the name correct?' % rule_name) elif operation == "add": new_rule = create_security_rule( rule_name=rule_name, description=description, tag_name=tag_name, source_zone=source_zone, destination_zone=destination_zone, source_ip=source_ip, source_user=source_user, destination_ip=destination_ip, category=category, application=application, service=service, hip_profiles=hip_profiles, group_profile=group_profile, antivirus=antivirus, vulnerability=vulnerability, spyware=spyware, url_filtering=url_filtering, file_blocking=file_blocking, data_filtering=data_filtering, wildfire_analysis=wildfire_analysis, log_start=log_start, log_end=log_end, rule_type=rule_type, action=action ) # Search for the rule. Fail if found. match = find_rule(rulebase, rule_name) if match: if rule_is_match(match, new_rule): module.exit_json(changed=False, msg='Rule \'%s\' is already in place' % rule_name) else: module.fail_json(msg='Rule \'%s\' already exists. Use operation: \'update\' to change it.' % rule_name) else: try: changed = add_rule(rulebase, new_rule) if changed and commit: device.commit(sync=True) except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) module.exit_json(changed=changed, msg='Rule \'%s\' successfully added' % rule_name) elif operation == 'update': # Search for the rule. Update if found. match = find_rule(rulebase, rule_name) if match: try: new_rule = create_security_rule( rule_name=rule_name, description=description, tag_name=tag_name, source_zone=source_zone, destination_zone=destination_zone, source_ip=source_ip, source_user=source_user, destination_ip=destination_ip, category=category, application=application, service=service, hip_profiles=hip_profiles, group_profile=group_profile, antivirus=antivirus, vulnerability=vulnerability, spyware=spyware, url_filtering=url_filtering, file_blocking=file_blocking, data_filtering=data_filtering, wildfire_analysis=wildfire_analysis, log_start=log_start, log_end=log_end, rule_type=rule_type, action=action ) changed = update_rule(rulebase, new_rule) if changed and commit: device.commit(sync=True) except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) module.exit_json(changed=changed, msg='Rule \'%s\' successfully updated' % rule_name) else: module.fail_json(msg='Rule \'%s\' does not exist. Use operation: \'add\' to add it.' % rule_name)
def main(): argument_spec = dict( asn=dict(required=True, type='str'), vrf=dict(required=False, type='str', default='default'), safi=dict(required=True, type='str', choices=['unicast','multicast', 'evpn']), afi=dict(required=True, type='str', choices=['ipv4','ipv6', 'vpnv4', 'vpnv6', 'l2vpn']), additional_paths_install=dict(required=False, type='bool'), additional_paths_receive=dict(required=False, type='bool'), additional_paths_selection=dict(required=False, type='str'), additional_paths_send=dict(required=False, type='bool'), advertise_l2vpn_evpn=dict(required=False, type='bool'), client_to_client=dict(required=False, type='bool'), dampen_igp_metric=dict(required=False, type='str'), dampening_state=dict(required=False, type='bool'), dampening_half_time=dict(required=False, type='str'), dampening_max_suppress_time=dict(required=False, type='str'), dampening_reuse_time=dict(required=False, type='str'), dampening_routemap=dict(required=False, type='str'), dampening_suppress_time=dict(required=False, type='str'), default_information_originate=dict(required=False, type='bool'), default_metric=dict(required=False, type='str'), distance_ebgp=dict(required=False, type='str'), distance_ibgp=dict(required=False, type='str'), distance_local=dict(required=False, type='str'), inject_map=dict(required=False, type='list'), maximum_paths=dict(required=False, type='str'), maximum_paths_ibgp=dict(required=False, type='str'), networks=dict(required=False, type='list'), next_hop_route_map=dict(required=False, type='str'), redistribute=dict(required=False, type='list'), suppress_inactive=dict(required=False, type='bool'), table_map=dict(required=False, type='str'), table_map_filter=dict(required=False, type='bool'), state=dict(choices=['present', 'absent'], default='present', required=False), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False) ) module = get_network_module(argument_spec=argument_spec, required_together=[DAMPENING_PARAMS, ['distance_ibgp', 'distance_ebgp', 'distance_local']], supports_check_mode=True) state = module.params['state'] if module.params['dampening_routemap']: for param in DAMPENING_PARAMS: if module.params[param]: module.fail_json(msg='dampening_routemap cannot be used with' ' the {0} param'.format(param)) if module.params['advertise_l2vpn_evpn']: if module.params['vrf'] == 'default': module.fail_json(msg='It is not possible to advertise L2VPN ' 'EVPN in the default VRF. Please specify ' 'another one.', vrf=module.params['vrf']) if module.params['table_map_filter'] and not module.params['table_map']: module.fail_json(msg='table_map param is needed when using' ' table_map_filter filter.') args = [ "additional_paths_install", "additional_paths_receive", "additional_paths_selection", "additional_paths_send", "advertise_l2vpn_evpn", "afi", "asn", "client_to_client", "dampen_igp_metric", "dampening_half_time", "dampening_max_suppress_time", "dampening_reuse_time", "dampening_suppress_time", "dampening_routemap", "dampening_state", "default_information_originate", "default_metric", "distance_ebgp", "distance_ibgp", "distance_local", "inject_map", "maximum_paths", "maximum_paths_ibgp", "networks", "next_hop_route_map", "redistribute", "safi", "suppress_inactive", "table_map", "table_map_filter", "vrf" ] existing = invoke('get_existing', module, args) if existing.get('asn'): if (existing.get('asn') != module.params['asn'] and state == 'present'): module.fail_json(msg='Another BGP ASN already exists.', proposed_asn=module.params['asn'], existing_asn=existing.get('asn')) end_state = existing proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) if proposed_args.get('networks'): if proposed_args['networks'][0] == 'default': proposed_args['networks'] = 'default' if proposed_args.get('inject_map'): if proposed_args['inject_map'][0] == 'default': proposed_args['inject_map'] = 'default' proposed = {} for key, value in proposed_args.items(): if key not in ['asn', 'vrf']: if str(value).lower() == 'default': value = PARAM_TO_DEFAULT_KEYMAP.get(key) if value is None: value = 'default' if existing.get(key) or (not existing.get(key) and value): proposed[key] = value result = {} if state == 'present' or (state == 'absent' and existing): candidate = CustomNetworkConfig(indent=3) invoke('state_%s' % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result['updates'] = [] result['connected'] = module.connected if module._verbosity > 0: end_state = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed_args if WARNINGS: result['warnings'] = WARNINGS module.exit_json(**result)
def main(): argument_spec = dict(ip_address=dict(required=True), password=dict(required=True, no_log=True), username=dict(default='admin'), api_key=dict(no_log=True), devicegroup=dict(default=None), description=dict(default=None), ip_to_register=dict(type='str', required=False), tag_names=dict(type='list', required=True), commit=dict(type='bool', default=True), operation=dict(type='str', required=True)) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_LIB: module.fail_json(msg='pan-python is required for this module') ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] api_key = module.params['api_key'] commit = module.params['commit'] devicegroup = module.params['devicegroup'] operation = module.params['operation'] # Create the device with the appropriate pandevice type device = base.PanDevice.create_from_device(ip_address, username, password, api_key=api_key) # If Panorama, validate the devicegroup dev_group = None if devicegroup and isinstance(device, panorama.Panorama): dev_group = get_devicegroup(device, devicegroup) if dev_group: device.add(dev_group) else: module.fail_json( msg= '\'%s\' device group not found in Panorama. Is the name correct?' % devicegroup) result = None if operation == 'add': result, exc = register_ip_to_tag_map( device, ip_addresses=module.params.get('ip_to_register', None), tag=module.params.get('tag_names', None)) elif operation == 'list': result, exc = get_all_address_group_mapping(device) elif operation == 'delete': result, exc = delete_address_from_mapping( device, ip_address=module.params.get('ip_to_register', None), tags=module.params.get('tag_names', [])) else: module.fail_json(msg="Unsupported option") if not result: module.fail_json(msg=exc.message) if commit: try: device.commit(sync=True) except PanXapiError: exc = get_exception() module.fail_json(msg=exc) module.exit_json(changed=True, msg=result)
def main(): argument_spec = dict(ip_address=dict(required=True), password=dict(required=True, no_log=True), username=dict(default='admin'), rule_name=dict(required=True), from_zone=dict(type='list', required=True), to_zone=dict(required=True), source=dict(type='list', default=["any"]), destination=dict(type='list', default=["any"]), service=dict(default="any"), snat_type=dict(), snat_address=dict(), snat_interface=dict(), snat_interface_address=dict(), snat_bidirectional=dict(default=False), dnat_address=dict(), dnat_port=dict(), override=dict(type='bool', default=False), commit=dict(type='bool', default=True)) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_LIB: module.fail_json(msg='pan-python is required for this module') ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] xapi = pan.xapi.PanXapi(hostname=ip_address, api_username=username, api_password=password) rule_name = module.params['rule_name'] from_zone = module.params['from_zone'] to_zone = module.params['to_zone'] source = module.params['source'] destination = module.params['destination'] service = module.params['service'] snat_type = module.params['snat_type'] snat_address = module.params['snat_address'] snat_interface = module.params['snat_interface'] snat_interface_address = module.params['snat_interface_address'] snat_bidirectional = module.params['snat_bidirectional'] dnat_address = module.params['dnat_address'] dnat_port = module.params['dnat_port'] commit = module.params['commit'] override = module.params["override"] if not override and nat_rule_exists(xapi, rule_name): module.exit_json(changed=False, msg="rule exists") try: changed = add_nat(xapi, module, rule_name, from_zone, to_zone, source, destination, service, dnatxml=dnat_xml(module, dnat_address, dnat_port), snatxml=snat_xml(module, snat_type, snat_address, snat_interface, snat_interface_address, snat_bidirectional)) if changed and commit: xapi.commit(cmd="<commit></commit>", sync=True, interval=1) module.exit_json(changed=changed, msg="okey dokey") except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message)
def main(): argument_spec = dict(vrf=dict(required=False, type='str', default='default'), ospf=dict(required=True, type='str'), router_id=dict(required=False, type='str'), default_metric=dict(required=False, type='str'), log_adjacency=dict( required=False, type='str', choices=['log', 'detail', 'default']), timer_throttle_lsa_start=dict(required=False, type='str'), timer_throttle_lsa_hold=dict(required=False, type='str'), timer_throttle_lsa_max=dict(required=False, type='str'), timer_throttle_spf_start=dict(required=False, type='str'), timer_throttle_spf_hold=dict(required=False, type='str'), timer_throttle_spf_max=dict(required=False, type='str'), auto_cost=dict(required=False, type='str'), state=dict(choices=['present', 'absent'], default='present', required=False), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False)) module = get_network_module(argument_spec=argument_spec, supports_check_mode=True) state = module.params['state'] args = [ 'vrf', 'ospf', 'router_id', 'default_metric', 'log_adjacency', 'timer_throttle_lsa_start', 'timer_throttle_lsa_hold', 'timer_throttle_lsa_max', 'timer_throttle_spf_start', 'timer_throttle_spf_hold', 'timer_throttle_spf_max', 'auto_cost' ] existing = invoke('get_existing', module, args) end_state = existing proposed_args = dict((k, v) for k, v in module.params.iteritems() if v is not None and k in args) proposed = {} for key, value in proposed_args.iteritems(): if key != 'interface': if str(value).lower() == 'true': value = True elif str(value).lower() == 'false': value = False elif str(value).lower() == 'default': value = PARAM_TO_DEFAULT_KEYMAP.get(key) if value is None: value = 'default' if existing.get(key) or (not existing.get(key) and value): proposed[key] = value result = {} if state == 'present' or (state == 'absent' and existing): candidate = CustomNetworkConfig(indent=3) invoke('state_%s' % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result['updates'] = [] result['connected'] = module.connected if module._verbosity > 0: end_state = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed_args module.exit_json(**result)
def main(): spec = dict( # { command: <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 = NetworkModule(argument_spec=spec, connect_on_load=False, supports_check_mode=True) commands = list(parse_commands(module)) conditionals = module.params['wait_for'] or list() warnings = list() runner = CommandRunner(module) for cmd in commands: if module.check_mode and not cmd['command'].startswith('show'): warnings.append('only show commands are supported when using ' 'check mode, not executing `%s`' % cmd['command']) else: if cmd['command'].startswith('conf'): module.fail_json(msg='ios_command does not support running ' 'config mode commands. Please use ' 'ios_config instead') try: runner.add_command(**cmd) except AddCommandError: exc = get_exception() warnings.append('duplicate command detected: %s' % cmd) for item in conditionals: runner.add_conditional(item) runner.retries = module.params['retries'] runner.interval = module.params['interval'] runner.match = module.params['match'] try: runner.run() except FailedConditionsError: exc = get_exception() module.fail_json(msg=str(exc), failed_conditions=exc.failed_conditions) except NetworkError: exc = get_exception() module.disconnect() module.fail_json(msg=str(exc), stdout=exc.kwargs.get('stdout')) result = dict(changed=False, stdout=list()) for cmd in commands: try: output = runner.get_command(cmd['command']) except ValueError: output = 'command not executed due to check_mode, see warnings' result['stdout'].append(output) result['warnings'] = warnings module.exit_json(**result)
def main(): module = AnsibleModule( argument_spec=dict(repo=dict(required=True), user=dict(required=True), password=dict(no_log=True), token=dict(no_log=True), action=dict(choices=['latest_release'], default=None), state=dict(choices=['absent', 'present'], default=None), body=dict(default=None), name=dict(default=None), tag_name=dict(required=False), target_commitish=dict(required=False), draft=dict(required=False, type='bool', default=False), prerelease=dict(type='bool', default=False)), supports_check_mode=False, required_one_of=(('password', 'token'), ), mutually_exclusive=(('password', 'token'), ('state', 'action')), required_if=( ('state', 'present', ('tag_name', 'target_commitish')), ('state', 'absent', ('tag_name', )), ), ) if not HAS_GITHUB_API: module.fail_json(msg='Missing required github3 module (check docs or ' 'install with: pip install github3.py==1.0.0a4)') repo = module.params['repo'] user = module.params['user'] password = module.params['password'] login_token = module.params['token'] action = module.params['action'] state = module.params['state'] # login to github try: if user and password: gh_obj = github3.login(user, password=password) elif login_token: gh_obj = github3.login(token=login_token) # test if we're actually logged in gh_obj.me() except github3.AuthenticationFailed: e = get_exception() module.fail_json(msg='Failed to connect to GitHub: %s' % e, details="Please check username and password or token " "for repository %s" % repo) repository = gh_obj.repository(user, repo) if not repository: module.fail_json(msg="Repository %s/%s doesn't exist" % (user, repo)) if action == 'latest_release': release = repository.latest_release() if release: module.exit_json(tag=release.tag_name) else: module.exit_json(tag=None) else: release = find_release(module, repository) if state == 'absent': if isinstance(release, github3.null.NullObject): module.exit_json(changed=False, result="Release not found") else: if delete_release(module, release): module.exit_json(changed=True, deleted=True) else: module.fail_json(msg="Failed to delete release") elif state == 'present': if isinstance(release, github3.null.NullObject): release = create_release(module, repository) module.exit_json(changed=True, created=True, release=release.as_dict()) else: update = update_release(module, release) if update is None: module.exit_json(changed=False, release=release.as_dict()) elif update: time.sleep(1) # Remote change is quick, but not immediate release = find_release(module, repository) module.exit_json(changed=True, updated=True, release=release.as_dict()) else: module.fail_json(msg="Failed to update release") else: module.fail_json(msg="No action or state provided")
def main(): argument_spec = dict( asn=dict(required=True, type='str'), vrf=dict(required=False, type='str', default='default'), bestpath_always_compare_med=dict(required=False, type='bool'), bestpath_aspath_multipath_relax=dict(required=False, type='bool'), bestpath_compare_neighborid=dict(required=False, type='bool'), bestpath_compare_routerid=dict(required=False, type='bool'), bestpath_cost_community_ignore=dict(required=False, type='bool'), bestpath_med_confed=dict(required=False, type='bool'), bestpath_med_missing_as_worst=dict(required=False, type='bool'), bestpath_med_non_deterministic=dict(required=False, type='bool'), cluster_id=dict(required=False, type='str'), confederation_id=dict(required=False, type='str'), confederation_peers=dict(required=False, type='str'), disable_policy_batching=dict(required=False, type='bool'), disable_policy_batching_ipv4_prefix_list=dict(required=False, type='str'), disable_policy_batching_ipv6_prefix_list=dict(required=False, type='str'), enforce_first_as=dict(required=False, type='bool'), event_history_cli=dict(required=False, choices=['true', 'false', 'default', 'size_small', 'size_medium', 'size_large', 'size_disable']), event_history_detail=dict(required=False, choices=['true', 'false', 'default', 'size_small', 'size_medium', 'size_large', 'size_disable']), event_history_events=dict(required=False, choices=['true', 'false', 'default' 'size_small', 'size_medium', 'size_large', 'size_disable']), event_history_periodic=dict(required=False, choices=['true', 'false', 'default', 'size_small', 'size_medium', 'size_large', 'size_disable']), fast_external_fallover=dict(required=False, type='bool'), flush_routes=dict(required=False, type='bool'), graceful_restart=dict(required=False, type='bool'), graceful_restart_helper=dict(required=False, type='bool'), graceful_restart_timers_restart=dict(required=False, type='str'), graceful_restart_timers_stalepath_time=dict(required=False, type='str'), isolate=dict(required=False, type='bool'), local_as=dict(required=False, type='str'), log_neighbor_changes=dict(required=False, type='bool'), maxas_limit=dict(required=False, type='str'), neighbor_down_fib_accelerate=dict(required=False, type='bool'), reconnect_interval=dict(required=False, type='str'), router_id=dict(required=False, type='str'), shutdown=dict(required=False, type='bool'), suppress_fib_pending=dict(required=False, type='bool'), timer_bestpath_limit=dict(required=False, type='str'), timer_bgp_hold=dict(required=False, type='str'), timer_bgp_keepalive=dict(required=False, type='str'), state=dict(choices=['present', 'absent'], default='present', required=False), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False) ) module = get_network_module(argument_spec=argument_spec, required_together=[['timer_bgp_hold', 'timer_bgp_keepalive']], supports_check_mode=True) state = module.params['state'] args = [ "asn", "bestpath_always_compare_med", "bestpath_aspath_multipath_relax", "bestpath_compare_neighborid", "bestpath_compare_routerid", "bestpath_cost_community_ignore", "bestpath_med_confed", "bestpath_med_missing_as_worst", "bestpath_med_non_deterministic", "cluster_id", "confederation_id", "confederation_peers", "disable_policy_batching", "disable_policy_batching_ipv4_prefix_list", "disable_policy_batching_ipv6_prefix_list", "enforce_first_as", "event_history_cli", "event_history_detail", "event_history_events", "event_history_periodic", "fast_external_fallover", "flush_routes", "graceful_restart", "graceful_restart_helper", "graceful_restart_timers_restart", "graceful_restart_timers_stalepath_time", "isolate", "local_as", "log_neighbor_changes", "maxas_limit", "neighbor_down_fib_accelerate", "reconnect_interval", "router_id", "shutdown", "suppress_fib_pending", "timer_bestpath_limit", "timer_bgp_hold", "timer_bgp_keepalive", "vrf" ] if module.params['vrf'] != 'default': for param, inserted_value in module.params.items(): if param in GLOBAL_PARAMS and inserted_value: module.fail_json(msg='Global params can be modified only' ' under "default" VRF.', vrf=module.params['vrf'], global_param=param) existing = invoke('get_existing', module, args) if existing.get('asn'): if (existing.get('asn') != module.params['asn'] and state == 'present'): module.fail_json(msg='Another BGP ASN already exists.', proposed_asn=module.params['asn'], existing_asn=existing.get('asn')) end_state = existing proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) proposed = {} for key, value in proposed_args.items(): if key != 'asn' and key != 'vrf': if str(value).lower() == 'default': value = PARAM_TO_DEFAULT_KEYMAP.get(key) if value is None: value = 'default' if existing.get(key) or (not existing.get(key) and value): proposed[key] = value result = {} if (state == 'present' or (state == 'absent' and existing.get('asn') == module.params['asn'])): candidate = CustomNetworkConfig(indent=3) invoke('state_%s' % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result['updates'] = [] result['connected'] = module.connected if module._verbosity > 0: end_state = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed_args if WARNINGS: result['warnings'] = WARNINGS module.exit_json(**result)
def main(): argument_spec = dict( asn=dict(required=True, type='str'), vrf=dict(required=False, type='str', default='default'), neighbor=dict(required=True, type='str'), description=dict(required=False, type='str'), capability_negotiation=dict(required=False, type='bool'), connected_check=dict(required=False, type='bool'), dynamic_capability=dict(required=False, type='bool'), ebgp_multihop=dict(required=False, type='str'), local_as=dict(required=False, type='str'), log_neighbor_changes=dict(required=False, type='str', choices=['enable', 'disable', 'inherit']), low_memory_exempt=dict(required=False, type='bool'), maximum_peers=dict(required=False, type='str'), pwd=dict(required=False, type='str'), pwd_type=dict(required=False, type='str', choices=['cleartext', '3des', 'cisco_type_7', 'default']), remote_as=dict(required=False, type='str'), remove_private_as=dict( required=False, type='str', choices=['enable', 'disable', 'all', 'replace-as']), shutdown=dict(required=False, type='str'), suppress_4_byte_as=dict(required=False, type='bool'), timers_keepalive=dict(required=False, type='str'), timers_holdtime=dict(required=False, type='str'), transport_passive_only=dict(required=False, type='bool'), update_source=dict(required=False, type='str'), m_facts=dict(required=False, default=False, type='bool'), state=dict(choices=['present', 'absent'], default='present', required=False), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False)) module = get_network_module( argument_spec=argument_spec, required_together=[['timer_bgp_hold', 'timer_bgp_keepalive']], supports_check_mode=True) state = module.params['state'] if module.params['pwd_type'] == 'default': module.params['pwd_type'] = '0' args = [ 'asn', 'capability_negotiation', 'connected_check', 'description', 'dynamic_capability', 'ebgp_multihop', 'local_as', 'log_neighbor_changes', 'low_memory_exempt', 'maximum_peers', 'neighbor', 'pwd', 'pwd_type', 'remote_as', 'remove_private_as', 'shutdown', 'suppress_4_byte_as', 'timers_keepalive', 'timers_holdtime', 'transport_passive_only', 'update_source', 'vrf' ] existing = invoke('get_existing', module, args) if existing.get('asn'): if (existing.get('asn') != module.params['asn'] and state == 'present'): module.fail_json(msg='Another BGP ASN already exists.', proposed_asn=module.params['asn'], existing_asn=existing.get('asn')) end_state = existing proposed_args = dict((k, v) for k, v in module.params.iteritems() if v is not None and k in args) proposed = {} for key, value in proposed_args.iteritems(): if key not in ['asn', 'vrf', 'neighbor', 'pwd_type']: if str(value).lower() == 'default': value = PARAM_TO_DEFAULT_KEYMAP.get(key) if value is None: value = 'default' if existing.get(key) or (not existing.get(key) and value): proposed[key] = value result = {} if state == 'present' or (state == 'absent' and existing): candidate = CustomNetworkConfig(indent=3) invoke('state_%s' % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result['updates'] = [] result['connected'] = module.connected if module._verbosity > 0: end_state = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed_args if WARNINGS: result['warnings'] = WARNINGS module.exit_json(**result)
def main(): argument_spec = basic_auth_argument_spec() argument_spec.update(api_username=dict(type='str', required=True), api_password=dict(type='str', required=True, no_log=True), api_url=dict(type='str', required=True), ssid=dict(required=True)) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) p = module.params ssid = p['ssid'] validate_certs = p['validate_certs'] api_usr = p['api_username'] api_pwd = p['api_password'] api_url = p['api_url'] facts = dict(ssid=ssid) # fetch the list of storage-pool objects and look for one with a matching name try: (rc, resp) = request(api_url + "/storage-systems/%s/graph" % ssid, headers=dict(Accept="application/json"), url_username=api_usr, url_password=api_pwd, validate_certs=validate_certs) except: error = get_exception() module.fail_json( msg= "Failed to obtain facts from storage array with id [%s]. Error [%s]" % (ssid, str(error))) facts['snapshot_images'] = [ dict(id=d['id'], status=d['status'], pit_capacity=d['pitCapacity'], creation_method=d['creationMethod'], reposity_cap_utilization=d['repositoryCapacityUtilization'], active_cow=d['activeCOW'], rollback_source=d['isRollbackSource']) for d in resp['highLevelVolBundle']['pit'] ] facts['netapp_disks'] = [ dict(id=d['id'], available=d['available'], media_type=d['driveMediaType'], status=d['status'], usable_bytes=d['usableCapacity'], tray_ref=d['physicalLocation']['trayRef'], product_id=d['productID'], firmware_version=d['firmwareVersion'], serial_number=d['serialNumber'].lstrip()) for d in resp['drive'] ] facts['netapp_storage_pools'] = [ dict(id=sp['id'], name=sp['name'], available_capacity=sp['freeSpace'], total_capacity=sp['totalRaidedSpace'], used_capacity=sp['usedSpace']) for sp in resp['volumeGroup'] ] all_volumes = list(resp['volume']) # all_volumes.extend(resp['thinVolume']) # TODO: exclude thin-volume repo volumes (how to ID?) facts['netapp_volumes'] = [ dict(id=v['id'], name=v['name'], parent_storage_pool_id=v['volumeGroupRef'], capacity=v['capacity'], is_thin_provisioned=v['thinProvisioned']) for v in all_volumes ] features = [f for f in resp['sa']['capabilities']] features.extend([ f['capability'] for f in resp['sa']['premiumFeatures'] if f['isEnabled'] ]) features = list(set(features)) # ensure unique features.sort() facts['netapp_enabled_features'] = features # TODO: include other details about the storage pool (size, type, id, etc) result = dict(ansible_facts=facts, changed=False) module.exit_json(msg="Gathered facts for %s." % ssid, **result)
def open(self, host, port=22, username=None, password=None, key_filename=None, pkey=None, look_for_keys=None, allow_agent=False, key_policy="loose"): self.ssh = paramiko.SSHClient() if key_policy != "ignore": self.ssh.load_system_host_keys() try: self.ssh.load_host_keys( os.path.expanduser('~/.ssh/known_hosts')) except IOError: pass if key_policy == "strict": self.ssh.set_missing_host_key_policy(paramiko.RejectPolicy()) else: self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # unless explicitly set, disable look for keys if a password is # present. this changes the default search order paramiko implements if not look_for_keys: look_for_keys = password is None try: self.ssh.connect( host, port=port, username=username, password=password, timeout=self._timeout, look_for_keys=look_for_keys, pkey=pkey, key_filename=key_filename, allow_agent=allow_agent, ) self.shell = self.ssh.invoke_shell() self.shell.settimeout(self._timeout) except socket.gaierror: raise ShellError("unable to resolve host name") except AuthenticationException: raise ShellError('Unable to authenticate to remote device') except socket.timeout: raise ShellError("timeout trying to connect to remote device") except socket.error: exc = get_exception() if exc.errno == 60: raise ShellError('timeout trying to connect to host') raise if self.kickstart: self.shell.sendall("\n") self.receive()
def main(): argument_spec = pgutils.postgres_common_argument_spec() argument_spec.update( dict( db=dict(required=True, aliases=['name']), owner=dict(default=""), template=dict(default=""), encoding=dict(default=""), lc_collate=dict(default=""), lc_ctype=dict(default=""), state=dict(default="present", choices=["absent", "present"]), )) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if not HAS_PSYCOPG2: module.fail_json(msg="the python psycopg2 module is required") db = module.params["db"] port = module.params["port"] owner = module.params["owner"] template = module.params["template"] encoding = module.params["encoding"] lc_collate = module.params["lc_collate"] lc_ctype = module.params["lc_ctype"] state = module.params["state"] sslrootcert = module.params["ssl_rootcert"] changed = False # To use defaults values, keyword arguments must be absent, so # check which values are empty and don't include in the **kw # dictionary params_map = { "login_host": "host", "login_user": "******", "login_password": "******", "port": "port", "ssl_mode": "sslmode", "ssl_rootcert": "sslrootcert" } kw = dict((params_map[k], v) for (k, v) in iteritems(module.params) if k in params_map and v != '' and v is not None) # If a login_unix_socket is specified, incorporate it here. is_localhost = "host" not in kw or kw["host"] == "" or kw[ "host"] == "localhost" if is_localhost and module.params["login_unix_socket"] != "": kw["host"] = module.params["login_unix_socket"] try: pgutils.ensure_libs(sslrootcert=module.params.get('ssl_rootcert')) db_connection = psycopg2.connect(database="postgres", **kw) # Enable autocommit so we can create databases if psycopg2.__version__ >= '2.4.2': db_connection.autocommit = True else: db_connection.set_isolation_level( psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cursor = db_connection.cursor( cursor_factory=psycopg2.extras.DictCursor) except pgutils.LibraryError: e = get_exception() module.fail_json(msg="unable to connect to database: {0}".format( str(e)), exception=traceback.format_exc()) except TypeError: e = get_exception() if 'sslrootcert' in e.args[0]: module.fail_json( msg= 'Postgresql server must be at least version 8.4 to support sslrootcert. Exception: {0}' .format(e), exception=traceback.format_exc()) module.fail_json(msg="unable to connect to database: %s" % e, exception=traceback.format_exc()) except Exception: e = get_exception() module.fail_json(msg="unable to connect to database: %s" % e, exception=traceback.format_exc()) try: if module.check_mode: if state == "absent": changed = db_exists(cursor, db) elif state == "present": changed = not db_matches(cursor, db, owner, template, encoding, lc_collate, lc_ctype) module.exit_json(changed=changed, db=db) if state == "absent": try: changed = db_delete(cursor, db) except SQLParseError: e = get_exception() module.fail_json(msg=str(e)) elif state == "present": try: changed = db_create(cursor, db, owner, template, encoding, lc_collate, lc_ctype) except SQLParseError: e = get_exception() module.fail_json(msg=str(e)) except NotSupportedError: e = get_exception() module.fail_json(msg=str(e)) except SystemExit: # Avoid catching this on Python 2.4 raise except Exception: e = get_exception() module.fail_json(msg="Database query failed: %s" % e) module.exit_json(changed=changed, db=db)
def http_request(self, req): tmp_ca_cert_path, to_add_ca_cert_path, paths_checked = self.get_ca_certs( ) https_proxy = os.environ.get('https_proxy') context = None if HAS_SSLCONTEXT: context = self._make_context(to_add_ca_cert_path) # Detect if 'no_proxy' environment variable is set and if our URL is included use_proxy = self.detect_no_proxy(req.get_full_url()) if not use_proxy: # ignore proxy settings for this host request return req try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if https_proxy: proxy_parts = generic_urlparse(urlparse(https_proxy)) port = proxy_parts.get('port') or 443 s.connect((proxy_parts.get('hostname'), port)) if proxy_parts.get('scheme') == 'http': s.sendall(self.CONNECT_COMMAND % (self.hostname, self.port)) if proxy_parts.get('username'): credentials = "%s:%s" % (proxy_parts.get( 'username', ''), proxy_parts.get('password', '')) s.sendall( b('Proxy-Authorization: Basic %s\r\n') % base64.b64encode( to_bytes( credentials, errors='surrogate_or_strict')).strip()) s.sendall(b('\r\n')) connect_result = b("") while connect_result.find(b("\r\n\r\n")) <= 0: connect_result += s.recv(4096) # 128 kilobytes of headers should be enough for everyone. if len(connect_result) > 131072: raise ProxyError( 'Proxy sent too verbose headers. Only 128KiB allowed.' ) self.validate_proxy_response(connect_result) if context: ssl_s = context.wrap_socket( s, server_hostname=self.hostname) elif HAS_URLLIB3_SNI_SUPPORT: ssl_s = ssl_wrap_socket(s, ca_certs=tmp_ca_cert_path, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL, server_hostname=self.hostname) else: ssl_s = ssl.wrap_socket(s, ca_certs=tmp_ca_cert_path, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL) match_hostname(ssl_s.getpeercert(), self.hostname) else: raise ProxyError( 'Unsupported proxy scheme: %s. Currently ansible only supports HTTP proxies.' % proxy_parts.get('scheme')) else: s.connect((self.hostname, self.port)) if context: ssl_s = context.wrap_socket(s, server_hostname=self.hostname) elif HAS_URLLIB3_SNI_SUPPORT: ssl_s = ssl_wrap_socket(s, ca_certs=tmp_ca_cert_path, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL, server_hostname=self.hostname) else: ssl_s = ssl.wrap_socket(s, ca_certs=tmp_ca_cert_path, cert_reqs=ssl.CERT_REQUIRED, ssl_version=PROTOCOL) match_hostname(ssl_s.getpeercert(), self.hostname) # close the ssl connection #ssl_s.unwrap() s.close() except (ssl.SSLError, socket.error): e = get_exception() # fail if we tried all of the certs but none worked if 'connection refused' in str(e).lower(): raise ConnectionError('Failed to connect to %s:%s.' % (self.hostname, self.port)) else: build_ssl_validation_error(self.hostname, self.port, paths_checked) except CertificateError: build_ssl_validation_error(self.hostname, self.port, paths_checked) try: # cleanup the temp file created, don't worry # if it fails for some reason os.remove(tmp_ca_cert_path) except: pass try: # cleanup the temp file created, don't worry # if it fails for some reason if to_add_ca_cert_path: os.remove(to_add_ca_cert_path) except: pass return req
def main(): argument_spec = dict(interface=dict(required=True, type='str'), vni=dict(required=True, type='str'), assoc_vrf=dict(required=False, type='bool'), multicast_group=dict(required=False, type='str'), peer_list=dict(required=False, type='list'), suppress_arp=dict(required=False, type='bool'), ingress_replication=dict( required=False, type='str', choices=['bgp', 'static', 'default']), state=dict(choices=['present', 'absent'], default='present', required=False), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False)) module = get_network_module(argument_spec=argument_spec, supports_check_mode=True) if module.params['assoc_vrf']: mutually_exclusive_params = [ 'multicast_group', 'suppress_arp', 'ingress_replication' ] for param in mutually_exclusive_params: if module.params[param]: module.fail_json(msg='assoc_vrf cannot be used with ' '{0} param'.format(param)) if module.params['peer_list']: if module.params['ingress_replication'] != 'static': module.fail_json(msg='ingress_replication=static is required ' 'when using peer_list param') else: peer_list = module.params['peer_list'] if peer_list[0] == 'default': module.params['peer_list'] = 'default' else: stripped_peer_list = map(str.strip, peer_list) module.params['peer_list'] = stripped_peer_list state = module.params['state'] args = [ 'assoc_vrf', 'interface', 'vni', 'ingress_replication', 'multicast_group', 'peer_list', 'suppress_arp' ] existing, interface_exist = invoke('get_existing', module, args) end_state = existing proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) proposed = {} for key, value in proposed_args.items(): if key != 'interface': if str(value).lower() == 'default': value = PARAM_TO_DEFAULT_KEYMAP.get(key) if value is None: value = 'default' if existing.get(key) or (not existing.get(key) and value): proposed[key] = value result = {} if state == 'present' or (state == 'absent' and existing): if not interface_exist: WARNINGS.append("The proposed NVE interface does not exist. " "Use nxos_interface to create it first.") elif interface_exist != module.params['interface']: module.fail_json(msg='Only 1 NVE interface is allowed on ' 'the switch.') elif (existing and state == 'absent' and existing['vni'] != module.params['vni']): module.fail_json(msg="ERROR: VNI delete failed: Could not find" " vni node for {0}".format(module.params['vni']), existing_vni=existing['vni']) else: candidate = CustomNetworkConfig(indent=3) invoke('state_%s' % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result['updates'] = [] result['connected'] = module.connected if module._verbosity > 0: end_state, interface_exist = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed_args if WARNINGS: result['warnings'] = WARNINGS module.exit_json(**result)
def run_commands(self, commands, **kwargs): try: return self.shell.send(commands) except ShellError: e = get_exception() self.module.fail_json(msg=e.message, commands=commands)
def fetch_url(module, url, data=None, headers=None, method=None, use_proxy=True, force=False, last_mod_time=None, timeout=10): '''Sends a request via HTTP(S) or FTP (needs the module as parameter) :arg module: The AnsibleModule (used to get username, password etc. (s.b.). :arg url: The url to use. :kwarg data: The data to be sent (in case of POST/PUT). :kwarg headers: A dict with the request headers. :kwarg method: "POST", "PUT", etc. :kwarg boolean use_proxy: Default: True :kwarg boolean force: If True: Do not get a cached copy (Default: False) :kwarg last_mod_time: Default: None :kwarg int timeout: Default: 10 :returns: A tuple of (**response**, **info**). Use ``response.body()`` to read the data. The **info** contains the 'status' and other meta data. When a HttpError (status > 400) occurred then ``info['body']`` contains the error response data:: Example:: data={...} resp, info = fetch_url("http://example.com", data=module.jsonify(data) header={Content-type': 'application/json'}, method="POST") status_code = info["status"] body = resp.read() if status_code >= 400 : body = info['body'] ''' if not HAS_URLPARSE: module.fail_json(msg='urlparse is not installed') # Get validate_certs from the module params validate_certs = module.params.get('validate_certs', True) username = module.params.get('url_username', '') password = module.params.get('url_password', '') http_agent = module.params.get('http_agent', None) force_basic_auth = module.params.get('force_basic_auth', '') follow_redirects = module.params.get('follow_redirects', 'urllib2') r = None info = dict(url=url) try: r = open_url(url, data=data, headers=headers, method=method, use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs, url_username=username, url_password=password, http_agent=http_agent, force_basic_auth=force_basic_auth, follow_redirects=follow_redirects) info.update(r.info()) info.update( dict(msg="OK (%s bytes)" % r.headers.get('Content-Length', 'unknown'), url=r.geturl(), status=r.code)) except NoSSLError: e = get_exception() distribution = get_distribution() if distribution is not None and distribution.lower() == 'redhat': module.fail_json( msg='%s. You can also install python-ssl from EPEL' % str(e)) else: module.fail_json(msg='%s' % str(e)) except (ConnectionError, ValueError): e = get_exception() module.fail_json(msg=str(e)) except urllib_error.HTTPError: e = get_exception() try: body = e.read() except AttributeError: body = '' info.update(dict(msg=str(e), body=body, **e.info())) info['status'] = e.code except urllib_error.URLError: e = get_exception() code = int(getattr(e, 'code', -1)) info.update(dict(msg="Request failed: %s" % str(e), status=code)) except socket.error: e = get_exception() info.update(dict(msg="Connection failure: %s" % str(e), status=-1)) except Exception: e = get_exception() info.update( dict(msg="An unknown error occurred: %s" % str(e), status=-1)) return r, info
def main(): argument_spec = dict( key_id=dict(required=True, type='str'), md5string=dict(required=True, type='str'), auth_type=dict(choices=['text', 'encrypt'], default='text'), trusted_key=dict(choices=['true', 'false'], default='false'), authentication=dict(choices=['on', 'off']), state=dict(choices=['absent', 'present'], default='present'), ) module = get_network_module(argument_spec=argument_spec, supports_check_mode=True) key_id = module.params['key_id'] md5string = module.params['md5string'] auth_type = module.params['auth_type'] trusted_key = module.params['trusted_key'] authentication = module.params['authentication'] state = module.params['state'] args = dict(key_id=key_id, md5string=md5string, auth_type=auth_type, trusted_key=trusted_key, authentication=authentication) changed = False proposed = dict((k, v) for k, v in args.iteritems() if v is not None) existing = get_ntp_auth_info(key_id, module) end_state = existing delta = dict(set(proposed.iteritems()).difference(existing.iteritems())) commands = [] if state == 'present': if delta: command = set_ntp_auth_key(key_id, md5string, auth_type, trusted_key, delta.get('authentication')) if command: commands.append(command) elif state == 'absent': if existing: auth_toggle = None if authentication == existing.get('authentication'): auth_toggle = authentication command = remove_ntp_auth_key(key_id, md5string, auth_type, trusted_key, auth_toggle) if command: commands.append(command) cmds = flatten_list(commands) if cmds: if module.check_mode: module.exit_json(changed=True, commands=cmds) else: try: execute_config_command(cmds, module) except ShellError: clie = get_exception() module.fail_json(msg=str(clie) + ": " + cmds) end_state = get_ntp_auth_info(key_id, module) delta = dict( set(end_state.iteritems()).difference(existing.iteritems())) if delta or (len(existing) != len(end_state)): changed = True if 'configure' in cmds: cmds.pop(0) results = {} results['proposed'] = proposed results['existing'] = existing results['updates'] = cmds results['changed'] = changed results['end_state'] = end_state module.exit_json(**results)
def setup_host(self): if self.module.params['hostname'] is None or len( self.module.params['hostname']) == 0: self.module.fail_json( msg= "name attribute could not be empty when adding or modifying host." ) msg = None host_response = self.get_host(self.module.params['macaddr']) # If host was not found using macaddr, add create message if host_response is None: msg = OmapiMessage.open( to_bytes('host', errors='surrogate_or_strict')) msg.message.append(('create', struct.pack('!I', 1))) msg.message.append(('exclusive', struct.pack('!I', 1))) msg.obj.append( ('hardware-address', pack_mac(self.module.params['macaddr']))) msg.obj.append(('hardware-type', struct.pack('!I', 1))) msg.obj.append(('name', self.module.params['hostname'])) if self.module.params['ip'] is not None: msg.obj.append((to_bytes("ip-address", errors='surrogate_or_strict'), pack_ip(self.module.params['ip']))) stmt_join = "" if self.module.params['ddns']: stmt_join += 'ddns-hostname "{0}"; '.format( self.module.params['hostname']) try: if len(self.module.params['statements']) > 0: stmt_join += "; ".join(self.module.params['statements']) stmt_join += "; " except TypeError: e = get_exception() self.module.fail_json(msg="Invalid statements found: %s" % e) if len(stmt_join) > 0: msg.obj.append(('statements', stmt_join)) try: response = self.omapi.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: self.module.fail_json( msg= "Failed to add host, ensure authentication and host parameters " "are valid.") self.module.exit_json(changed=True, lease=self.unpack_facts(response.obj)) except OmapiError: e = get_exception() self.module.fail_json(msg="OMAPI error: %s" % e) # Forge update message else: response_obj = self.unpack_facts(host_response.obj) fields_to_update = {} if to_bytes('ip-address', errors='surrogate_or_strict') not in response_obj or \ unpack_ip(response_obj[to_bytes('ip-address', errors='surrogate_or_strict')]) != self.module.params['ip']: fields_to_update['ip-address'] = pack_ip( self.module.params['ip']) # Name cannot be changed if 'name' not in response_obj or response_obj[ 'name'] != self.module.params['hostname']: self.module.fail_json( msg= "Changing hostname is not supported. Old was %s, new is %s. " "Please delete host and add new." % (response_obj['name'], self.module.params['hostname'])) """ # It seems statements are not returned by OMAPI, then we cannot modify them at this moment. if 'statements' not in response_obj and len(self.module.params['statements']) > 0 or \ response_obj['statements'] != self.module.params['statements']: with open('/tmp/omapi', 'w') as fb: for (k,v) in iteritems(response_obj): fb.writelines('statements: %s %s\n' % (k, v)) """ if len(fields_to_update) == 0: self.module.exit_json(changed=False, lease=response_obj) else: msg = OmapiMessage.update(host_response.handle) msg.update_object(fields_to_update) try: response = self.omapi.query_server(msg) if response.opcode != OMAPI_OP_STATUS: self.module.fail_json( msg= "Failed to modify host, ensure authentication and host parameters " "are valid.") self.module.exit_json(changed=True) except OmapiError: e = get_exception() self.module.fail_json(msg="OMAPI error: %s" % e)
def main(): argument_spec = dict( ip_address=dict(required=True), password=dict(no_log=True), username=dict(default='admin'), api_key=dict(no_log=True), operation=dict(required=True, choices=['add', 'update', 'delete', 'find']), addressobject=dict(default=None), addressgroup=dict(default=None), serviceobject=dict(default=None), servicegroup=dict(default=None), address=dict(default=None), address_type=dict(default='ip-netmask', choices=['ip-netmask', 'ip-range', 'fqdn']), static_value=dict(type='list', default=None), dynamic_value=dict(default=None), protocol=dict(default=None, choices=['tcp', 'udp']), source_port=dict(default=None), destination_port=dict(default=None), services=dict(type='list', default=None), description=dict(default=None), tag_name=dict(default=None), color=dict(default=None, choices=[ 'red', 'green', 'blue', 'yellow', 'copper', 'orange', 'purple', 'gray', 'light green', 'cyan', 'light gray', 'blue gray', 'lime', 'black', 'gold', 'brown' ]), vsys=dict(default='vsys1'), devicegroup=dict(default=None), commit=dict(type='bool', default=False), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['api_key', 'password']], mutually_exclusive=[[ 'addressobject', 'addressgroup', 'serviceobject', 'servicegroup', 'tag_name' ]]) if not HAS_LIB: module.fail_json(msg='Missing required libraries.') ip_address = module.params["ip_address"] password = module.params["password"] username = module.params['username'] api_key = module.params['api_key'] operation = module.params['operation'] addressobject = module.params['addressobject'] addressgroup = module.params['addressgroup'] serviceobject = module.params['serviceobject'] servicegroup = module.params['servicegroup'] address = module.params['address'] address_type = module.params['address_type'] static_value = module.params['static_value'] dynamic_value = module.params['dynamic_value'] protocol = module.params['protocol'] source_port = module.params['source_port'] destination_port = module.params['destination_port'] services = module.params['services'] description = module.params['description'] tag_name = module.params['tag_name'] color = module.params['color'] vsys = module.params['vsys'] devicegroup = module.params['devicegroup'] commit = module.params['commit'] # Create the device with the appropriate pandevice type device = PanDevice.create_from_device(ip_address, username, password, api_key=api_key) # If Panorama, validate the devicegroup dev_group = None if hasattr(device, 'refresh_devices'): # Panorama: set the device group. if devicegroup == 'shared': # Device group of None is "shared" scope for Panorama. devicegroup = None if devicegroup is not None: dev_group = get_devicegroup(device, devicegroup) if dev_group: device.add(dev_group) else: module.fail_json( msg= '\'%s\' device group not found in Panorama. Is the name correct?' % devicegroup) else: # Firewall: set the targetted vsys. device.vsys = vsys # What type of object are we talking about? if addressobject: obj_name = addressobject obj_type = objects.AddressObject elif addressgroup: obj_name = addressgroup obj_type = objects.AddressGroup elif serviceobject: obj_name = serviceobject obj_type = objects.ServiceObject elif servicegroup: obj_name = servicegroup obj_type = objects.ServiceGroup elif tag_name: obj_name = tag_name obj_type = objects.Tag else: module.fail_json(msg='No object type defined!') # Which operation shall we perform on the object? msg = None if operation == "find": # Search for the object match = find_object(device, dev_group, obj_name, obj_type) # If found, format and return the result if match: match_dict = xmltodict.parse(match.element_str()) module.exit_json(stdout_lines=json.dumps(match_dict, indent=2), msg='Object matched') else: module.fail_json( msg='Object \'%s\' not found. Is the name correct?' % obj_name) elif operation == "delete": # Search for the object match = find_object(device, dev_group, obj_name, obj_type) # If found, delete it if match: try: match.delete() except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) msg = "Object '{0}' successfully deleted".format(obj_name) else: module.fail_json( msg='Object \'%s\' not found. Is the name correct?' % obj_name) elif operation == "add": # Search for the object. Fail if found. match = find_object(device, dev_group, obj_name, obj_type) if match: module.fail_json( msg= 'Object \'%s\' already exists. Use operation: \'update\' to change it.' % obj_name) else: try: new_object = create_object(addressobject=addressobject, addressgroup=addressgroup, serviceobject=serviceobject, servicegroup=servicegroup, address=address, address_type=address_type, static_value=static_value, dynamic_value=dynamic_value, protocol=protocol, source_port=source_port, destination_port=destination_port, services=services, description=description, tag_name=tag_name, color=color) changed = add_object(device, dev_group, new_object) except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) msg = "Object '{0}' successfully added".format(obj_name) elif operation == "update": # Search for the object. Update if found. match = find_object(device, dev_group, obj_name, obj_type) if match: try: new_object = create_object(addressobject=addressobject, addressgroup=addressgroup, serviceobject=serviceobject, servicegroup=servicegroup, address=address, address_type=address_type, static_value=static_value, dynamic_value=dynamic_value, protocol=protocol, source_port=source_port, destination_port=destination_port, services=services, description=description, tag_name=tag_name, color=color) changed = add_object(device, dev_group, new_object) except PanXapiError: exc = get_exception() module.fail_json(msg=exc.message) msg = "Object '{0}' successfully updated.".format(obj_name) else: module.fail_json( msg= 'Object \'%s\' does not exist. Use operation: \'add\' to add it.' % obj_name) # Optional: commit the change. if commit: try: device.commit(sync=True) except PanDeviceError as e: module.fail_json(msg='Failed to commit: {0}'.format(e)) # Done. module.exit_json(changed=True, msg=msg)