def map_config_to_obj(module): obj = [] out = get_config(module, flags='| include ip route') for line in out.splitlines(): # Split by whitespace but do not split quotes, needed for description splitted_line = findall(r'[^"\s]\S*|".+?"', line) route = {} prefix_with_mask = splitted_line[2] prefix = None mask = None iface = None nhop = None if validate_ip_address(prefix_with_mask) is True: my_net = ipaddress.ip_network(prefix_with_mask) prefix = str(my_net.network_address) mask = str(my_net.netmask) route.update({ 'prefix': prefix, 'mask': mask, 'admin_distance': '1' }) if splitted_line[3] is not None: if validate_ip_address(splitted_line[3]) is False: iface = str(splitted_line[3]) route.update(interface=iface) if validate_ip_address(splitted_line[4]) is True: nhop = str(splitted_line[4]) route.update(next_hop=nhop) if splitted_line[5].isdigit(): route.update(admin_distance=str(splitted_line[5])) elif splitted_line[4].isdigit(): route.update(admin_distance=str(splitted_line[4])) else: if splitted_line[6] is not None and splitted_line[ 6].isdigit(): route.update(admin_distance=str(splitted_line[6])) else: nhop = str(splitted_line[3]) route.update(next_hop=nhop) if splitted_line[4].isdigit(): route.update(admin_distance=str(splitted_line[4])) index = 0 for word in splitted_line: if word in ('tag', 'description'): route.update(word=splitted_line[index + 1]) index = index + 1 obj.append(route) return obj
def map_config_to_obj(module): obj = [] out = get_config(module, flags="| include ip route") for line in out.splitlines(): # Split by whitespace but do not split quotes, needed for name parameter splitted_line = findall('[^"\\s]\\S*|".+?"', line) if splitted_line[2] == "vrf": route = {"vrf": splitted_line[3]} del splitted_line[:4] # Removes the words ip route vrf vrf_name else: route = {} del splitted_line[:2] # Removes the words ip route prefix = splitted_line[0] mask = splitted_line[1] route.update({"prefix": prefix, "mask": mask, "admin_distance": "1"}) next_word = None for word in splitted_line[2:]: if next_word: route[next_word] = word.strip('"') next_word = None elif validate_ip_address(word): route.update(next_hop=word) elif word.isdigit(): route.update(admin_distance=word) elif word in ("tag", "name", "track"): next_word = word else: route.update(interface=word) obj.append(route) return obj
def is_valid_ip(addr, type='all'): if type in ['all', 'ipv4']: if validate_ip_address(addr): return True if type in ['all', 'ipv6']: if validate_ip_v6_address(addr): return True return False
def map_config_to_obj(module): obj = [] dest_group = ( "console", "host", "monitor", "buffered", "on", "facility", "trap", ) data = get_config(module, flags=["| include logging"]) for line in data.split("\n"): match = re.search(r"^logging (\S+)", line, re.M) if match: if match.group(1) in dest_group: dest = match.group(1) obj.append( { "dest": dest, "name": parse_name(line, dest), "size": parse_size(line, dest), "facility": parse_facility(line, dest), "level": parse_level(line, dest), } ) elif validate_ip_address(match.group(1)): dest = "host" obj.append( { "dest": dest, "name": match.group(1), "size": parse_size(line, dest), "facility": parse_facility(line, dest), "level": parse_level(line, dest), } ) else: ip_match = re.search( r"\d+\.\d+\.\d+\.\d+", match.group(1), re.M ) if ip_match: dest = "host" obj.append( { "dest": dest, "name": match.group(1), "size": parse_size(line, dest), "facility": parse_facility(line, dest), "level": parse_level(line, dest), } ) return obj
def check_ip_addr_type(obj_filter, ib_spec): '''This function will check if the argument ip is type v4/v6 and return appropriate infoblox network/networkcontainer type ''' ip = obj_filter['network'] if 'container' in obj_filter and obj_filter['container']: check_ip = ip.split('/') del ib_spec['container'] # removing the container key from post arguments del ib_spec['options'] # removing option argument as for network container it's not supported if validate_ip_address(check_ip[0]): return NIOS_IPV4_NETWORK_CONTAINER, ib_spec elif validate_ip_v6_address(check_ip[0]): return NIOS_IPV6_NETWORK_CONTAINER, ib_spec else: check_ip = ip.split('/') del ib_spec['container'] # removing the container key from post arguments if validate_ip_address(check_ip[0]): return NIOS_IPV4_NETWORK, ib_spec elif validate_ip_v6_address(check_ip[0]): return NIOS_IPV6_NETWORK, ib_spec
def _set_config(self, want, have): # Set the interface config based on the want and have config commands = [] interface = 'interface ' + want['name'] if want == have: return if want.get('ipv4'): haddr = have.get('ipv4') if not haddr: # if interface has no address, have empty list haddr = [] for waddr in want.get('ipv4'): waddr = remove_empties(waddr) if waddr not in haddr: # if wanted address not yet configured, add if waddr.get('address') != 'dhcp': ipv4_addr = waddr['address'].split('/') if len(ipv4_addr) != 2: # validate ip address self._module.fail_json(msg='Invalid format') if not validate_ip_address( ipv4_addr[0]) or not is_masklen(ipv4_addr[1]): self._module.fail_json(msg='Invalid IP address') cmd = 'ip address {0}'.format(waddr['address']) if waddr.get('secondary'): cmd += ' secondary' elif waddr.get('address') == 'dhcp': cmd = 'ip address dhcp' if waddr.get('dhcp_client'): cmd += ' client-id vlan{0}'.format( waddr.get('dhcp_client')) if waddr.get('dhcp_hostname'): cmd += ' hostname {0}'.format( waddr.get('dhcp_hostname')) add_command_to_config_list(interface, cmd, commands) if want.get('ipv6'): haddr = have.get('ipv6') if not haddr: haddr = [] for waddr in want.get('ipv6'): waddr = remove_empties(waddr) if waddr not in haddr: ipv6_addr = waddr['address'].split('/') if len(ipv6_addr) != 2: # validate ipv6 address self._module.fail_json(msg='Invalid format') if not validate_ip_v6_address( ipv6_addr[0]) or int(ipv6_addr[1]) > 64: self._module.fail_json(msg='Invalid IP address') cmd = 'ipv6 address {0}'.format(waddr['address']) add_command_to_config_list(interface, cmd, commands) return commands
def validate_ip_addr_type(ip, arg_spec, module): '''This function will check if the argument ip is type v4/v6 and return appropriate infoblox network type ''' check_ip = ip.split('/') if validate_ip_address(check_ip[0]) and 'ipaddr' in arg_spec: arg_spec['ipv4addr'] = arg_spec.pop('ipaddr') module.params['ipv4addr'] = module.params.pop('ipaddr') return NIOS_IPV4_FIXED_ADDRESS, arg_spec, module elif validate_ip_v6_address(check_ip[0]) and 'ipaddr' in arg_spec: arg_spec['ipv6addr'] = arg_spec.pop('ipaddr') module.params['ipv6addr'] = module.params.pop('ipaddr') return NIOS_IPV6_FIXED_ADDRESS, arg_spec, module
def _get_rdns(self): ip_address = self.module.params.get("ip_address") if utils.validate_ip_address(ip_address): if self.module.params.get("server"): if self.hcloud_resource.public_net.ipv4.ip == ip_address: self.hcloud_rdns = { "ip_address": self.hcloud_resource.public_net.ipv4.ip, "dns_ptr": self.hcloud_resource.public_net.ipv4.dns_ptr, } else: self.module.fail_json( msg="The selected server does not have this IP address" ) elif self.module.params.get("floating_ip"): if self.hcloud_resource.ip == ip_address: self.hcloud_rdns = { "ip_address": self.hcloud_resource.ip, "dns_ptr": self.hcloud_resource.dns_ptr[0]["dns_ptr"], } else: self.module.fail_json( msg= "The selected Floating IP does not have this IP address" ) elif utils.validate_ip_v6_address(ip_address): if self.module.params.get("server"): for ipv6_address_dns_ptr in self.hcloud_resource.public_net.ipv6.dns_ptr: if ipv6_address_dns_ptr["ip"] == ip_address: self.hcloud_rdns = { "ip_address": ipv6_address_dns_ptr["ip"], "dns_ptr": ipv6_address_dns_ptr["dns_ptr"], } elif self.module.params.get("floating_ip"): for ipv6_address_dns_ptr in self.hcloud_resource.dns_ptr: if ipv6_address_dns_ptr["ip"] == ip_address: self.hcloud_rdns = { "ip_address": ipv6_address_dns_ptr["ip"], "dns_ptr": ipv6_address_dns_ptr["dns_ptr"], } else: self.module.fail_json(msg="The given IP address is not valid")
def map_config_to_obj(module): obj = [] dest_group = ('console', 'host', 'monitor', 'buffered', 'on', 'facility', 'trap') data = get_config(module, flags=['| include logging']) for line in data.split('\n'): match = re.search(r'^logging (\S+)', line, re.M) if match: if match.group(1) in dest_group: dest = match.group(1) obj.append({ 'dest': dest, 'name': parse_name(line, dest), 'size': parse_size(line, dest), 'facility': parse_facility(line, dest), 'level': parse_level(line, dest) }) elif validate_ip_address(match.group(1)): dest = 'host' obj.append({ 'dest': dest, 'name': match.group(1), 'size': parse_size(line, dest), 'facility': parse_facility(line, dest), 'level': parse_level(line, dest) }) else: ip_match = re.search(r'\d+\.\d+\.\d+\.\d+', match.group(1), re.M) if ip_match: dest = 'host' obj.append({ 'dest': dest, 'name': match.group(1), 'size': parse_size(line, dest), 'facility': parse_facility(line, dest), 'level': parse_level(line, dest) }) return obj
def map_config_to_obj(module): obj = [] out = get_config(module, flags='| include ip route') for line in out.splitlines(): splitted_line = findall( r'[^"\s]\S*|".+?"', line ) # Split by whitespace but do not split quotes, needed for name parameter if splitted_line[2] == 'vrf': route = {'vrf': splitted_line[3]} del splitted_line[:4] # Removes the words ip route vrf vrf_name else: route = {} del splitted_line[:2] # Removes the words ip route prefix = splitted_line[0] mask = splitted_line[1] route.update({'prefix': prefix, 'mask': mask, 'admin_distance': '1'}) next_word = None for word in splitted_line[2:]: if next_word: route[next_word] = word.strip( '"') # Remove quotes which is needed for name next_word = None elif validate_ip_address(word): route.update(next_hop=word) elif word.isdigit(): route.update(admin_distance=word) elif word in ('tag', 'name', 'track'): next_word = word else: route.update(interface=word) obj.append(route) return obj
def map_config_to_obj(module): obj = [] dest_group = ("console", "host", "monitor", "buffered", "permanent", "external") data = run_commands(module, "show log config")[0] chunks = data.split( " " ) for chunk in chunks: blocks = re.split("Statistics .+", chunk, re.M) for line in blocks: match = re.search(r"(\S+) log:", line, re.M) if "Facility:" in line: dest = "facility" haves = populate_have(line, dest) for have in haves: obj.append(have) if match: if match.group(1).lower() in dest_group: dest = match.group(1).lower() haves = populate_have(line, dest) for have in haves: obj.append(have) elif validate_ip_address(match.group(1)): dest = "host" haves = populate_have(line, dest) for have in haves: obj.append(have) else: ip_match = re.search(r"\d+\.\d+\.\d+\.\d+", match.group(1), re.M) if ip_match: dest = "host" haves = populate_have(line, dest) for have in haves: obj.append(have) return obj
def map_config_to_obj(module): obj = [] route = {} out = get_config(module, flags="ip route") for line in out.splitlines(): # Split by whitespace but do not split quotes, needed for name parameter splitted_line = findall(r'[^"\s]\S*|".+?"', line) if len(splitted_line) <= 1: continue if splitted_line[2] == "vrf": route = {"vrf": splitted_line[3]} del splitted_line[:4] # Removes the words ip route vrf vrf_name else: route = {} del splitted_line[:2] # Removes the words ip route prefix_mask = splitted_line[0] prefix_mask_list = prefix_mask.split("/") prefix = prefix_mask_list[0] mask = prefix_mask_list[1] route.update({"prefix": prefix, "mask": mask, "admin_distance": "1"}) for word in splitted_line[1:]: if validate_ip_address(word): route.update(next_hop=word) elif word.isdigit(): route.update(admin_distance=word) else: route.update(interface=word) obj.append(route) return obj
def main(): """ main entry point for module execution """ element_spec = dict( address=dict(type="str", aliases=["prefix"]), next_hop=dict(type="str"), vrf=dict(type="str", default="default"), admin_distance=dict(default=1, type="int"), state=dict(default="present", choices=["present", "absent"]), ) aggregate_spec = deepcopy(element_spec) aggregate_spec["address"] = dict(required=True, aliases=["prefix"]) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) aggregate_spec["vrf"].update(default="default") argument_spec = dict( aggregate=dict(type="list", elements="dict", options=aggregate_spec)) argument_spec.update(element_spec) argument_spec.update(eos_argument_spec) required_one_of = [["aggregate", "address"]] required_together = [["address", "next_hop"]] mutually_exclusive = [["aggregate", "address"]] module = AnsibleModule( argument_spec=argument_spec, required_one_of=required_one_of, required_together=required_together, mutually_exclusive=mutually_exclusive, supports_check_mode=True, ) address = module.params["address"] if address is not None: prefix = address.split("/")[-1] if address and prefix: if "/" not in address or not validate_ip_address( address.split("/")[0]): module.fail_json( msg="{0} is not a valid IP address".format(address)) if not validate_prefix(prefix): module.fail_json( msg="Length of prefix should be between 0 and 32 bits") warnings = list() result = {"changed": False} if warnings: result["warnings"] = warnings want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands((want, have), module) result["commands"] = commands if commands: commit = not module.check_mode response = load_config(module, commands, commit=commit) if response.get("diff") and module._diff: result["diff"] = {"prepared": response.get("diff")} result["session_name"] = response.get("session") result["changed"] = True module.exit_json(**result)
def is_hop(value): if value: if validate_ip_address(value): return True return False
def is_address(value): if value: address = value.split("/") if is_masklen(address[1]) and validate_ip_address(address[0]): return True return False
def main(): """ main entry point for module execution """ element_spec = dict(address=dict(type='str', aliases=['prefix']), next_hop=dict(type='str'), vrf=dict(type='str', default='default'), admin_distance=dict(default=1, type='int'), state=dict(default='present', choices=['present', 'absent'])) aggregate_spec = deepcopy(element_spec) aggregate_spec['address'] = dict(required=True) # remove default in aggregate spec, to handle common arguments remove_default_spec(aggregate_spec) argument_spec = dict(aggregate=dict(type='list', elements='dict', options=aggregate_spec), ) argument_spec.update(element_spec) argument_spec.update(eos_argument_spec) required_one_of = [['aggregate', 'address']] required_together = [['address', 'next_hop']] mutually_exclusive = [['aggregate', 'address']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, required_together=required_together, mutually_exclusive=mutually_exclusive, supports_check_mode=True) address = module.params['address'] if address is not None: prefix = address.split('/')[-1] if address and prefix: if '/' not in address or not validate_ip_address( address.split('/')[0]): module.fail_json( msg='{0} is not a valid IP address'.format(address)) if not validate_prefix(prefix): module.fail_json( msg='Length of prefix should be between 0 and 32 bits') warnings = list() result = {'changed': False} if warnings: result['warnings'] = warnings want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands((want, have), module) result['commands'] = commands if commands: commit = not module.check_mode response = load_config(module, commands, commit=commit) if response.get('diff') and module._diff: result['diff'] = {'prepared': response.get('diff')} result['session_name'] = response.get('session') result['changed'] = True module.exit_json(**result)