def map_config_to_obj(module): obj = [] out = get_config(module, flags='| include ip route-static') for line in out.splitlines(): route = {} match = re.search(r'ip route-static\s*(?P<vrf>vpn-instance \S+)?\s*(?P<prefix>\d+.\d+.\d+.\d+)\s+' r'(?P<mask>\d+.\d+.\d+.\d+)\s*(?P<intr>\S+)?\s*(?P<next_hop>\d+.\d+.\d+.\d+)?\s*' r'(?P<adm_dist>preference \d+)?\s*(?P<tag>tag \d+)?\s*(?P<track>track nqa \S+ \S+)?\s*' r'(?P<name>description \S+)?', line) if match: if match.group('vrf'): route.update({'vrf': match.group('vrf').replace('vpn-instance ', '')}) if match.group('prefix'): route.update({'prefix': match.group('prefix')}) if match.group('mask'): route.update({'mask': match.group('mask')}) if match.group('intr') and not validate_ip_address(match.group('intr')): route.update({'interface': match.group('intr')}) if match.group('next_hop'): route.update({'next_hop': match.group('next_hop')}) if match.group('intr') and validate_ip_address(match.group('intr')): route.update({'next_hop': match.group('intr')}) if match.group('adm_dist'): route.update({'admin_distance': match.group('adm_dist').replace('preference ', '')}) if match.group('tag'): route.update({'tag': match.group('tag').replace('tag ', '')}) if match.group('track'): route.update({'track': match.group('track').replace('track nqa ', '')}) if match.group('name'): route.update({'name': match.group('name').replace('description ', '')}) 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 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 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 check_ip_addr_type(ip): '''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]): return NIOS_IPV4_NETWORK elif validate_ip_v6_address(check_ip[0]): return NIOS_IPV6_NETWORK
def update(self): self.have = self.read_current_from_device() if not self.should_update(): return False if self.want.reverse == 'enabled': if not self.want.receive and not self.have.receive: raise F5ModuleError( "A 'receive' string must be specified when setting 'reverse'." ) if self.want.time_until_up != 0 and self.have.time_until_up != 0: raise F5ModuleError( "Monitors with the 'reverse' attribute are not currently compatible with 'time_until_up'." ) if ((self.want.receive is not None and validate_ip_v6_address( self.want.receive) or self.have.receive is not None and validate_ip_v6_address(self.have.receive)) and (self.want.query_type == 'a' and self.have.query_type == 'a')): raise F5ModuleError( "Monitor has a IPv6 address. Only a 'query_type' of 'aaaa' is supported for IPv6." ) elif ((self.want.receive is not None and validate_ip_address( self.want.receive) or self.have.receive is not None and validate_ip_address(self.have.receive)) and (self.want.query_type == 'aaaa' and self.have.query_type == 'aaaa')): raise F5ModuleError( "Monitor has a IPv4 address. Only a 'query_type' of 'a' is supported for IPv4." ) if self.want.accept_rcode == 'anything': if self.want.receive is not None and is_valid_ip( self.want.receive) and self.have.receive is not None: raise F5ModuleError( "No 'receive' string may be specified, or exist, when 'accept_rcode' is 'anything'." ) elif self.want.receive is None and self.have.receive is not None: self.want.update({'receive': ''}) if self.module.check_mode: return True self.update_on_device() return True
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 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 _get_rdns(self): ip_address = self.module.params.get("ip_address") if utils.validate_ip_address(ip_address): if self.hcloud_server.public_net.ipv4.ip == ip_address: self.hcloud_rdns = { "ip_address": self.hcloud_server.public_net.ipv4.ip, "dns_ptr": self.hcloud_server.public_net.ipv4.dns_ptr, } else: self.module.fail_json(msg="The selected server does not have this IP address") elif utils.validate_ip_v6_address(ip_address): for ipv6_address_dns_ptr in self.hcloud_server.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"], } 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 create(self): self._set_changed_options() if self.want.reverse == 'enabled': if self.want.time_until_up != 0: raise F5ModuleError( "Monitors with the 'reverse' attribute are not currently compatible with 'time_until_up'." ) if not self.want.receive: raise F5ModuleError( "A 'receive' string must be specified when setting 'reverse'." ) if (self.want.receive is not None and validate_ip_v6_address(self.want.receive) and self.want.query_type == 'a'): raise F5ModuleError( "Monitor has a IPv6 address. Only a 'query_type' of 'aaaa' is supported for IPv6." ) elif (self.want.receive is not None and validate_ip_address(self.want.receive) and self.want.query_type == 'aaaa'): raise F5ModuleError( "Monitor has a IPv4 address. Only a 'query_type' of 'a' is supported for IPv4." ) if self.want.accept_rcode == 'anything': if self.want.receive is not None and is_valid_ip( self.want.receive): raise F5ModuleError( "No 'receive' string may be specified, or exist, when 'accept_rcode' is 'anything'." ) elif self.want.receive is None: self.want.update({'receive': ''}) if self.want.query_name is None: raise F5ModuleError( "'query_name' is required when creating a new DNS monitor.") if self.module.check_mode: return True self.create_on_device() return True
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', 'on', 'facility') 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), '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), 'facility': parse_facility(line, dest), 'level': parse_level(line, dest) }) return obj
def is_hop(value): if value: if validate_ip_address(value): return True return False
def is_ipv4(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'), 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='{} 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 main(): """ main entry point for module execution """ element_spec = dict( address=dict(type='str', aliases=['prefix']), next_hop=dict(type='str'), 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='{} 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_address(value): if value: address = value.split('/') if is_masklen(address[1]) and validate_ip_address(address[0]): return True return False