diff --git a/lib/ansible/modules/network/f5/bigip_selfip.py b/lib/ansible/modules/network/f5/bigip_selfip.py index 3d0efe66e4..c6eca4b95c 100644 --- a/lib/ansible/modules/network/f5/bigip_selfip.py +++ b/lib/ansible/modules/network/f5/bigip_selfip.py @@ -1,19 +1,23 @@ #!/usr/bin/python # -*- coding: utf-8 -*- # -# Copyright (c) 2017 F5 Networks Inc. +# Copyright (c) 2016 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) +from __future__ import absolute_import, division, print_function +__metaclass__ = type + + ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} -DOCUMENTATION = ''' +DOCUMENTATION = r''' --- module: bigip_selfip short_description: Manage Self-IPs on a BIG-IP system description: - - Manage Self-IPs on a BIG-IP system + - Manage Self-IPs on a BIG-IP system. version_added: "2.2" options: address: @@ -29,38 +33,44 @@ options: name: description: - The self IP to create. - required: true + required: True default: Value of C(address) netmask: description: - - The netmasks for the self IP. - required: true + - The netmask for the self IP. When creating a new Self IP, this value + is required. state: description: - The state of the variable on the system. When C(present), guarantees that the Self-IP exists with the provided attributes. When C(absent), removes the Self-IP from the system. - required: false default: present choices: - absent - present traffic_group: description: - - The traffic group for the self IP addresses in an active-active, - redundant load balancer configuration. - required: false + - The traffic group for the Self IP addresses in an active-active, + redundant load balancer configuration. When creating a new Self IP, if + this value is not specified, the default of C(/Common/traffic-group-local-only) + will be used. vlan: description: - - The VLAN that the new self IPs will be on. - required: true + - The VLAN that the new self IPs will be on. When creating a new Self + IP, this value is required. route_domain: description: - - The route domain id of the system. - If none, id of the route domain will be "0" (default route domain) - required: false - default: none + - The route domain id of the system. When creating a new Self IP, if + this value is not specified, a default value of C(0) will be used. version_added: 2.3 + partition: + description: + - Device partition to manage resources on. You can set different partitions + for Self IPs, but the address used may not match any other address used + by a Self IP. In that sense, Self IPs are not isolated by partitions as + other resources on a BIG-IP are. + default: Common + version_added: 2.5 notes: - Requires the f5-sdk Python package on the host. This is as easy as pip install f5-sdk. @@ -73,238 +83,294 @@ author: - Tim Rupp (@caphrim007) ''' -EXAMPLES = ''' +EXAMPLES = r''' - name: Create Self IP bigip_selfip: - address: "10.10.10.10" - name: "self1" - netmask: "255.255.255.0" - password: "secret" - server: "lb.mydomain.com" - user: "admin" - validate_certs: "no" - vlan: "vlan1" + address: 10.10.10.10 + name: self1 + netmask: 255.255.255.0 + password: secret + server: lb.mydomain.com + user: admin + validate_certs: no + vlan: vlan1 delegate_to: localhost - name: Create Self IP with a Route Domain bigip_selfip: - server: "lb.mydomain.com" - user: "admin" - password: "secret" - validate_certs: "no" - name: "self1" - address: "10.10.10.10" - netmask: "255.255.255.0" - vlan: "vlan1" - route_domain: "10" - allow_service: "default" + server: lb.mydomain.com + user: admin + password: secret + validate_certs: no + name: self1 + address: 10.10.10.10 + netmask: 255.255.255.0 + vlan: vlan1 + route_domain: 10 + allow_service: default delegate_to: localhost - name: Delete Self IP bigip_selfip: - name: "self1" - password: "secret" - server: "lb.mydomain.com" - state: "absent" - user: "admin" - validate_certs: "no" + name: self1 + password: secret + server: lb.mydomain.com + state: absent + user: admin + validate_certs: no delegate_to: localhost - name: Allow management web UI to be accessed on this Self IP bigip_selfip: - name: "self1" - password: "secret" - server: "lb.mydomain.com" - state: "absent" - user: "admin" - validate_certs: "no" - allow_service: - - "tcp:443" + name: self1 + password: secret + server: lb.mydomain.com + state: absent + user: admin + validate_certs: no + allow_service: + - tcp:443 delegate_to: localhost - name: Allow HTTPS and SSH access to this Self IP bigip_selfip: - name: "self1" - password: "secret" - server: "lb.mydomain.com" - state: "absent" - user: "admin" - validate_certs: "no" - allow_service: - - "tcp:443" - - "tpc:22" + name: self1 + password: secret + server: lb.mydomain.com + state: absent + user: admin + validate_certs: no + allow_service: + - tcp:443 + - tcp:22 delegate_to: localhost - name: Allow all services access to this Self IP bigip_selfip: - name: "self1" - password: "secret" - server: "lb.mydomain.com" - state: "absent" - user: "admin" - validate_certs: "no" - allow_service: - - all + name: self1 + password: secret + server: lb.mydomain.com + state: absent + user: admin + validate_certs: no + allow_service: + - all delegate_to: localhost - name: Allow only GRE and IGMP protocols access to this Self IP bigip_selfip: - name: "self1" - password: "secret" - server: "lb.mydomain.com" - state: "absent" - user: "admin" - validate_certs: "no" - allow_service: - - gre:0 - - igmp:0 + name: self1 + password: secret + server: lb.mydomain.com + state: absent + user: admin + validate_certs: no + allow_service: + - gre:0 + - igmp:0 delegate_to: localhost - name: Allow all TCP, but no other protocols access to this Self IP bigip_selfip: - name: "self1" - password: "secret" - server: "lb.mydomain.com" - state: "absent" - user: "admin" - validate_certs: "no" - allow_service: - - tcp:0 + name: self1 + password: secret + server: lb.mydomain.com + state: absent + user: admin + validate_certs: no + allow_service: + - tcp:0 delegate_to: localhost ''' -RETURN = ''' +RETURN = r''' allow_service: - description: Services that allowed via this Self IP - returned: changed - type: list - sample: ['igmp:0','tcp:22','udp:53'] + description: Services that allowed via this Self IP + returned: changed + type: list + sample: ['igmp:0','tcp:22','udp:53'] address: - description: The address for the Self IP - returned: created - type: string - sample: "192.0.2.10" + description: The address for the Self IP + returned: created + type: string + sample: 192.0.2.10 name: - description: The name of the Self IP - returned: created, changed or deleted - type: string - sample: "self1" + description: The name of the Self IP + returned: created, changed and deleted + type: string + sample: self1 netmask: - description: The netmask of the Self IP - returned: created or changed - type: string - sample: "255.255.255.0" + description: The netmask of the Self IP + returned: changed and created + type: string + sample: 255.255.255.0 traffic_group: - description: The traffic group that the Self IP is a member of - returned: changed or created - type: string - sample: "traffic-group-local-only" + description: The traffic group that the Self IP is a member of + returned: changed and created + type: string + sample: traffic-group-local-only vlan: - description: The VLAN set on the Self IP - returned: created or changed - type: string - sample: "vlan1" + description: The VLAN set on the Self IP + returned: changed and created + type: string + sample: vlan1 ''' +import os +import re + +from ansible.module_utils.f5_utils import AnsibleF5Client +from ansible.module_utils.f5_utils import AnsibleF5Parameters +from ansible.module_utils.f5_utils import HAS_F5SDK +from ansible.module_utils.f5_utils import F5ModuleError +from ansible.module_utils.six import iteritems +from collections import defaultdict + try: - from f5.bigip import ManagementRoot - from icontrol.session import iControlUnexpectedHTTPError - HAS_F5SDK = True + from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError except ImportError: HAS_F5SDK = False try: - from netaddr import IPNetwork, AddrFormatError + from netaddr import IPNetwork, AddrFormatError, IPAddress HAS_NETADDR = True except ImportError: HAS_NETADDR = False -FLOAT = ['enabled', 'disabled'] -DEFAULT_TG = 'traffic-group-local-only' -ALLOWED_PROTOCOLS = ['eigrp', 'egp', 'gre', 'icmp', 'igmp', 'igp', 'ipip', - 'l2tp', 'ospf', 'pim', 'tcp', 'udp'] +class Parameters(AnsibleF5Parameters): + api_map = { + 'trafficGroup': 'traffic_group', + 'allowService': 'allow_service' + } -class BigIpSelfIp(object): - def __init__(self, *args, **kwargs): - if not HAS_F5SDK: - raise F5ModuleError("The python f5-sdk module is required") + updatables = [ + 'traffic_group', 'allow_service', 'vlan', 'route_domain', 'netmask' + ] - # The params that change in the module - self.cparams = dict() + returnables = [ + 'traffic_group', 'allow_service', 'vlan', 'route_domain', 'netmask' + ] - # Stores the params that are sent to the module - self.params = kwargs - self.api = ManagementRoot(kwargs['server'], - kwargs['user'], - kwargs['password'], - port=kwargs['server_port']) + api_attributes = [ + 'trafficGroup', 'allowService', 'vlan', 'address' + ] - def present(self): - changed = False + def __init__(self, params=None): + self._values = defaultdict(lambda: None) + self._values['__warnings'] = [] + if params: + self.update(params=params) - if self.exists(): - changed = self.update() - else: - changed = self.create() + def update(self, params=None): + if params: + for k, v in iteritems(params): + if self.api_map is not None and k in self.api_map: + map_key = self.api_map[k] + else: + map_key = k - return changed + # Handle weird API parameters like `dns.proxy.__iter__` by + # using a map provided by the module developer + class_attr = getattr(type(self), map_key, None) + if isinstance(class_attr, property): + # There is a mapped value for the api_map key + if class_attr.fset is None: + # If the mapped value does not have + # an associated setter + self._values[map_key] = v + else: + # The mapped value has a setter + setattr(self, map_key, v) + else: + # If the mapped value is not a @property + self._values[map_key] = v - def absent(self): - changed = False + def to_return(self): + result = {} + for returnable in self.returnables: + result[returnable] = getattr(self, returnable) + result = self._filter_params(result) + return result - if self.exists(): - changed = self.delete() - - return changed - - def read(self): - """Read information and transform it - - The values that are returned by BIG-IP in the f5-sdk can have encoding - attached to them as well as be completely missing in some cases. - - Therefore, this method will transform the data from the BIG-IP into a - format that is more easily consumable by the rest of the class and the - parameters that are supported by the module. - - :return: List of values currently stored in BIG-IP, formatted for use - in this class. - """ - p = dict() - name = self.params['name'] - partition = self.params['partition'] - r = self.api.tm.net.selfips.selfip.load( - name=name, - partition=partition - ) - - if hasattr(r, 'address'): - p['route_domain'] = str(None) - if '%' in r.address: - ipaddr = [] - ipaddr = r.address.split('%', 1) - rdmask = ipaddr[1].split('/', 1) - r.address = "%s/%s" % (ipaddr[0], rdmask[1]) - p['route_domain'] = str(rdmask[0]) - ipnet = IPNetwork(r.address) - p['address'] = str(ipnet.ip) - p['netmask'] = str(ipnet.netmask) - if hasattr(r, 'trafficGroup'): - p['traffic_group'] = str(r.trafficGroup) - if hasattr(r, 'vlan'): - p['vlan'] = str(r.vlan) - if hasattr(r, 'allowService'): - if r.allowService == 'all': - p['allow_service'] = set(['all']) + def api_params(self): + result = {} + for api_attribute in self.api_attributes: + if self.api_map is not None and api_attribute in self.api_map: + result[api_attribute] = getattr(self, self.api_map[api_attribute]) else: - p['allow_service'] = set([str(x) for x in r.allowService]) - else: - p['allow_service'] = set(['none']) - p['name'] = name - return p + result[api_attribute] = getattr(self, api_attribute) + result = self._filter_params(result) + return result - def verify_services(self): + @property + def address(self): + address = "{0}%{1}/{2}".format( + self.ip, self.route_domain, self.netmask + ) + return address + + @address.setter + def address(self, value): + self._values['ip'] = value + + @property + def ip(self): + if self._values['ip'] is None: + return None + try: + ip = str(IPAddress(self._values['ip'])) + return ip + except AddrFormatError: + raise F5ModuleError( + 'The provided address is not a valid IP address' + ) + + @property + def traffic_group(self): + if self._values['traffic_group'] is None: + return None + return self._fqdn_name(self._values['traffic_group']) + + @property + def route_domain(self): + if self._values['route_domain'] is None: + return None + result = int(self._values['route_domain']) + return result + + @property + def netmask(self): + if self._values['netmask'] is None: + return None + + # Check if numeric + if isinstance(self._values['netmask'], int): + result = int(self._values['netmask']) + if 0 < result < 256: + return result + raise F5ModuleError( + 'The provided netmask {0} is neither in IP or CIDR format'.format(result) + ) + else: + try: + # IPv4 netmask + address = '0.0.0.0/' + self._values['netmask'] + ip = IPNetwork(address) + except AddrFormatError as ex: + try: + # IPv6 netmask + address = '::/' + self._values['netmask'] + ip = IPNetwork(address) + except AddrFormatError as ex: + raise F5ModuleError( + 'The provided netmask {0} is neither in IP or CIDR format'.format(self._values['netmask']) + ) + result = int(ip.prefixlen) + return result + + @property + def allow_service(self): """Verifies that a supplied service string has correct format The string format for port lockdown is PROTOCOL:PORT. This method @@ -323,34 +389,282 @@ class BigIpSelfIp(object): :raises F5ModuleError: """ + if self._values['allow_service'] is None: + return None result = [] - for svc in self.params['allow_service']: - if svc in ['all', 'none', 'default']: + allowed_protocols = [ + 'eigrp', 'egp', 'gre', 'icmp', 'igmp', 'igp', 'ipip', + 'l2tp', 'ospf', 'pim', 'tcp', 'udp' + ] + special_protocols = [ + 'all', 'none', 'default' + ] + for svc in self._values['allow_service']: + if svc in special_protocols: result = [svc] break - - tmp = svc.split(':') - if tmp[0] not in ALLOWED_PROTOCOLS: - raise F5ModuleError( - "The provided protocol '%s' is invalid" % (tmp[0]) - ) - try: - port = int(tmp[1]) - except Exception: - raise F5ModuleError( - "The provided port '%s' is not a number" % (tmp[1]) - ) - - if port < 0 or port > 65535: - raise F5ModuleError( - "The provided port '%s' must be between 0 and 65535" - % (port) - ) + elif svc in allowed_protocols: + full_service = '{0}:0'.format(svc) + result.append(full_service) else: - result.append(svc) + tmp = svc.split(':') + if tmp[0] not in allowed_protocols: + raise F5ModuleError( + "The provided protocol '%s' is invalid" % (tmp[0]) + ) + try: + port = int(tmp[1]) + except Exception: + raise F5ModuleError( + "The provided port '%s' is not a number" % (tmp[1]) + ) + + if port < 0 or port > 65535: + raise F5ModuleError( + "The provided port '{0}' must be between 0 and 65535".format(port) + ) + else: + result.append(svc) return set(result) - def fmt_services(self, services): + def _fqdn_name(self, value): + if value is not None and not value.startswith('/'): + return '/{0}/{1}'.format(self.partition, value) + return value + + @property + def vlan(self): + if self._values['vlan'] is None: + return None + return self._fqdn_name(self._values['vlan']) + + +class ApiParameters(Parameters): + api_map = {} + + @property + def address(self): + if self.ip and self.route_domain and self.netmask: + return '{0}%{1}/{2}'.format(self.ip, self.route_domain, self.netmask) + elif self.ip and self.netmask: + return '{0}/{1}'.format(self.ip, self.netmask) + + @address.setter + def address(self, value): + pattern = '^(?P[0-9A-Fa-f:.]+)%?(?P\d+)?\/(?P\d+)$' + matches = re.match(pattern, value) + if not matches: + raise F5ModuleError( + "The specified address is malformed. Please see documentation." + ) + try: + ip = matches.group('ip') + self._values['ip'] = str(IPAddress(ip)) + except AddrFormatError: + raise F5ModuleError( + 'The provided address is not a valid IP address' + ) + self._values['route_domain'] = matches.group('rd') + self._values['netmask'] = matches.group('nm') + + @property + def allow_service(self): + return self._values['allow_service'] + + @property + def trafficGroup(self): + return self.traffic_group + + @trafficGroup.setter + def trafficGroup(self, value): + self._values['traffic_group'] = value + + @property + def allowService(self): + return self._values['allow_service'] + + @allowService.setter + def allowService(self, value): + if value == 'all': + self._values['allow_service'] = set(['all']) + else: + self._values['allow_service'] = set([str(x) for x in value]) + + +class ModuleManager(object): + def __init__(self, client): + self.client = client + self.have = None + self.want = Parameters(self.client.module.params) + self.changes = ApiParameters() + + def _set_changed_options(self): + changed = {} + for key in Parameters.returnables: + if getattr(self.want, key) is not None: + changed[key] = getattr(self.want, key) + if changed: + self.changes = Parameters(changed) + + def _update_changed_options(self): + diff = Difference(self.want, self.have) + updatables = ApiParameters.updatables + changed = dict() + for k in updatables: + change = diff.compare(k) + if change is None: + continue + else: + if k in ['netmask', 'route_domain']: + changed['address'] = change + else: + changed[k] = change + if changed: + self.changes = ApiParameters(changed) + return True + return False + + def exec_module(self): + changed = False + result = dict() + state = self.want.state + + try: + if state == "present": + changed = self.present() + elif state == "absent": + changed = self.absent() + except iControlUnexpectedHTTPError as e: + raise F5ModuleError(str(e)) + + changes = self.changes.to_return() + result.update(**changes) + result.update(dict(changed=changed)) + return result + + def present(self): + if self.exists(): + changed = self.update() + else: + changed = self.create() + return changed + + def absent(self): + changed = False + if self.exists(): + changed = self.remove() + return changed + + def should_update(self): + result = self._update_changed_options() + if result: + return True + return False + + def read_current_from_device(self): + resource = self.client.api.tm.net.selfips.selfip.load( + name=self.want.name, + partition=self.want.partition + ) + result = resource.attrs + params = ApiParameters(result) + return params + + def update(self): + self.have = self.read_current_from_device() + if not self.should_update(): + return False + if self.client.check_mode: + return True + self.update_on_device() + return True + + def update_on_device(self): + params = self.changes.api_params() + resource = self.client.api.tm.net.selfips.selfip.load( + name=self.want.name, + partition=self.want.partition + ) + resource.modify(**params) + + def create(self): + if self.want.address is None or self.want.netmask is None: + raise F5ModuleError( + 'An address and a netmask must be specified' + ) + if self.want.vlan is None: + raise F5ModuleError( + 'A VLAN name must be specified' + ) + if self.want.traffic_group is None: + self.want.update({'traffic_group': '/Common/traffic-group-local-only'}) + if self.want.route_domain is None: + self.want.update({'route_domain': 0}) + + if self.want.check_mode: + return True + self.create_on_device() + if self.exists(): + return True + else: + raise F5ModuleError("Failed to create the Self IP") + + def create_on_device(self): + params = self.changes.api_params() + self.client.api.tm.net.selfips.selfip.create( + name=self.want.name, + partition=self.want.partition, + address=self.want.address, + vlan=self.want.vlan, + **params + ) + + def remove(self): + if self.client.check_mode: + return True + self.remove_from_device() + if self.exists(): + raise F5ModuleError("Failed to delete the Self IP") + return True + + def remove_from_device(self): + resource = self.client.api.tm.net.selfips.selfip.load( + name=self.want.name, + partition=self.want.partition + ) + resource.delete() + + def exists(self): + result = self.client.api.tm.net.selfips.selfip.exists( + name=self.want.name, + partition=self.want.partition + ) + return result + + +class Difference(object): + def __init__(self, want, have=None): + self.want = want + self.have = have + + def compare(self, param): + try: + result = getattr(self, param) + return result + except AttributeError: + return self.__default(param) + + def __default(self, param): + attr1 = getattr(self.want, param) + try: + attr2 = getattr(self.have, param) + if attr1 != attr2: + return attr1 + except AttributeError: + return attr1 + + @property + def allow_service(self): """Returns services formatted for consumption by f5-sdk update The BIG-IP endpoint for services takes different values depending on @@ -368,314 +682,107 @@ class BigIpSelfIp(object): :param services: The services to format. This is always a Python set :return: """ - result = list(services) - if result[0] == 'all': + if self.want.allow_service is None: + return None + result = list(self.want.allow_service) + if self.want.allow_service == self.have.allow_service: + return None + elif result[0] == 'none' and self.have.allow_service is None: + return None + elif result[0] == 'all': return 'all' elif result[0] == 'none': + return [] + else: + return list(result) + + @property + def netmask(self): + if self.want.netmask is None: return None - else: - return list(services) - - def traffic_groups(self): - result = [] - - groups = self.api.tm.cm.traffic_groups.get_collection() - for group in groups: - # Just checking for the addition of the partition here for - # different versions of BIG-IP - if '/' + self.params['partition'] + '/' in group.name: - result.append(group.name) - else: - full_name = '/%s/%s' % (self.params['partition'], group.name) - result.append(str(full_name)) - return result - - def update(self): - changed = False - svcs = [] - params = dict() - current = self.read() - - check_mode = self.params['check_mode'] - address = self.params['address'] - allow_service = self.params['allow_service'] - name = self.params['name'] - netmask = self.params['netmask'] - partition = self.params['partition'] - traffic_group = self.params['traffic_group'] - vlan = self.params['vlan'] - route_domain = self.params['route_domain'] - - if address is not None and address != current['address']: - raise F5ModuleError( - 'Self IP addresses cannot be updated' - ) - - if netmask is not None: - # I ignore the address value here even if they provide it because - # you are not allowed to change it. - try: - address = IPNetwork(current['address']) - - new_addr = "%s/%s" % (address.ip, netmask) - nipnet = IPNetwork(new_addr) - if route_domain is not None: - nipnet = "%s%s%s" % (address.ip, route_domain, netmask) - - cur_addr = "%s/%s" % (current['address'], current['netmask']) - cipnet = IPNetwork(cur_addr) - if route_domain is not None: - cipnet = "%s%s%s" % (current['address'], current['route_domain'], current['netmask']) - - if nipnet != cipnet: - if route_domain is not None: - address = "%s%s%s/%s" % (address.ip, '%', route_domain, netmask) - else: - address = "%s/%s" % (nipnet.ip, nipnet.prefixlen) - params['address'] = address - except AddrFormatError: - raise F5ModuleError( - 'The provided address/netmask value was invalid' - ) - - if traffic_group is not None: - traffic_group = "/%s/%s" % (partition, traffic_group) - if traffic_group not in self.traffic_groups(): - raise F5ModuleError( - 'The specified traffic group was not found' - ) - - if 'traffic_group' in current: - if traffic_group != current['traffic_group']: - params['trafficGroup'] = traffic_group - else: - params['trafficGroup'] = traffic_group - - if vlan is not None: - vlans = self.get_vlans() - vlan = "/%s/%s" % (partition, vlan) - - if 'vlan' in current: - if vlan != current['vlan']: - params['vlan'] = vlan - else: - params['vlan'] = vlan - - if vlan not in vlans: - raise F5ModuleError( - 'The specified VLAN was not found' - ) - - if allow_service is not None: - svcs = self.verify_services() - if 'allow_service' in current: - if svcs != current['allow_service']: - params['allowService'] = self.fmt_services(svcs) - else: - params['allowService'] = self.fmt_services(svcs) - - if params: - changed = True - params['name'] = name - params['partition'] = partition - if check_mode: - return changed - self.cparams = camel_dict_to_snake_dict(params) - if svcs: - self.cparams['allow_service'] = list(svcs) - else: - return changed - - r = self.api.tm.net.selfips.selfip.load( - name=name, - partition=partition - ) - r.update(**params) - r.refresh() - - return True - - def get_vlans(self): - """Returns formatted list of VLANs - - The VLAN values stored in BIG-IP are done so using their fully - qualified name which includes the partition. Therefore, "correct" - values according to BIG-IP look like this - - /Common/vlan1 - - This is in contrast to the formats that most users think of VLANs - as being stored as - - vlan1 - - To provide for the consistent user experience while not turfing - BIG-IP, we need to massage the values that are provided by the - user so that they include the partition. - - :return: List of vlans formatted with preceding partition - """ - partition = self.params['partition'] - vlans = self.api.tm.net.vlans.get_collection() - return [str("/" + partition + "/" + x.name) for x in vlans] - - def create(self): - params = dict() - - svcs = [] - check_mode = self.params['check_mode'] - address = self.params['address'] - allow_service = self.params['allow_service'] - name = self.params['name'] - netmask = self.params['netmask'] - partition = self.params['partition'] - traffic_group = self.params['traffic_group'] - vlan = self.params['vlan'] - route_domain = self.params['route_domain'] - - if address is None or netmask is None: - raise F5ModuleError( - 'An address and a netmask must be specififed' - ) - - if vlan is None: - raise F5ModuleError( - 'A VLAN name must be specified' - ) - else: - vlan = "/%s/%s" % (partition, vlan) - try: - ipin = "%s/%s" % (address, netmask) - ipnet = IPNetwork(ipin) - if route_domain is not None: - params['address'] = "%s%s%s/%s" % (ipnet.ip, '%', route_domain, ipnet.prefixlen) + address = IPNetwork(self.have.ip) + if self.want.route_domain is not None: + nipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.want.netmask) + cipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.have.netmask) + elif self.have.route_domain is not None: + nipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.want.netmask) + cipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.have.netmask) else: - params['address'] = "%s/%s" % (ipnet.ip, ipnet.prefixlen) + nipnet = "{0}/{1}".format(address.ip, self.want.netmask) + cipnet = "{0}/{1}".format(address.ip, self.have.netmask) + if nipnet != cipnet: + return nipnet + except AddrFormatError: + raise F5ModuleError( + 'The provided address/netmask value "{0}" was invalid'.format(self.have.ip) + ) + + @property + def route_domain(self): + if self.want.route_domain is None: + return None + try: + address = IPNetwork(self.have.ip) + + if self.want.netmask is not None: + nipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.want.netmask) + cipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.want.netmask) + elif self.have.netmask is not None: + nipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.have.netmask) + cipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.have.netmask) + + if nipnet != cipnet: + return nipnet except AddrFormatError: raise F5ModuleError( 'The provided address/netmask value was invalid' ) - if traffic_group is None: - params['trafficGroup'] = "/%s/%s" % (partition, DEFAULT_TG) - else: - traffic_group = "/%s/%s" % (partition, traffic_group) - if traffic_group in self.traffic_groups(): - params['trafficGroup'] = traffic_group - else: - raise F5ModuleError( - 'The specified traffic group was not found' - ) + @property + def traffic_group(self): + if self.want.traffic_group == self.have.traffic_group: + return None + return self.want.traffic_group - vlans = self.get_vlans() - if vlan in vlans: - params['vlan'] = vlan - else: - raise F5ModuleError( - 'The specified VLAN was not found' - ) - if allow_service is not None: - svcs = self.verify_services() - params['allowService'] = self.fmt_services(svcs) - - params['name'] = name - params['partition'] = partition - - self.cparams = camel_dict_to_snake_dict(params) - if svcs: - self.cparams['allow_service'] = list(svcs) - - if check_mode: - return True - - d = self.api.tm.net.selfips.selfip - d.create(**params) - - if self.exists(): - return True - else: - raise F5ModuleError("Failed to create the self IP") - - def delete(self): - params = dict() - check_mode = self.params['check_mode'] - - params['name'] = self.params['name'] - params['partition'] = self.params['partition'] - - self.cparams = camel_dict_to_snake_dict(params) - if check_mode: - return True - - dc = self.api.tm.net.selfips.selfip.load(**params) - dc.delete() - - if self.exists(): - raise F5ModuleError("Failed to delete the self IP") - return True - - def exists(self): - name = self.params['name'] - partition = self.params['partition'] - return self.api.tm.net.selfips.selfip.exists( - name=name, - partition=partition +class ArgumentSpec(object): + def __init__(self): + self.supports_check_mode = True + self.argument_spec = dict( + address=dict(), + allow_service=dict(type='list'), + name=dict(required=True), + netmask=dict(), + traffic_group=dict(), + vlan=dict(), + route_domain=dict() ) - - def flush(self): - result = dict() - state = self.params['state'] - - try: - if state == "present": - changed = self.present() - elif state == "absent": - changed = self.absent() - except iControlUnexpectedHTTPError as e: - raise F5ModuleError(str(e)) - - result.update(**self.cparams) - result.update(dict(changed=changed)) - return result + self.f5_product_name = 'bigip' def main(): - argument_spec = f5_argument_spec() + if not HAS_F5SDK: + raise F5ModuleError("The python f5-sdk module is required") - meta_args = dict( - address=dict(required=False, default=None), - allow_service=dict(type='list', default=None), - name=dict(required=True), - netmask=dict(required=False, default=None), - traffic_group=dict(required=False, default=None), - vlan=dict(required=False, default=None), - route_domain=dict(required=False, default=None) - ) - argument_spec.update(meta_args) + if not HAS_NETADDR: + raise F5ModuleError("The python netaddr module is required") - module = AnsibleModule( - argument_spec=argument_spec, - supports_check_mode=True + spec = ArgumentSpec() + + client = AnsibleF5Client( + argument_spec=spec.argument_spec, + supports_check_mode=spec.supports_check_mode, + f5_product_name=spec.f5_product_name ) try: - if not HAS_NETADDR: - raise F5ModuleError( - "The netaddr python module is required." - ) - - obj = BigIpSelfIp(check_mode=module.check_mode, **module.params) - result = obj.flush() - - module.exit_json(**result) + mm = ModuleManager(client) + results = mm.exec_module() + client.module.exit_json(**results) except F5ModuleError as e: - module.fail_json(msg=str(e)) + client.module.fail_json(msg=str(e)) -from ansible.module_utils.basic import * -from ansible.module_utils.ec2 import camel_dict_to_snake_dict -from ansible.module_utils.f5_utils import * if __name__ == '__main__': main() diff --git a/test/units/modules/network/f5/fixtures/load_tm_net_self.json b/test/units/modules/network/f5/fixtures/load_tm_net_self.json new file mode 100644 index 0000000000..9bf4f23458 --- /dev/null +++ b/test/units/modules/network/f5/fixtures/load_tm_net_self.json @@ -0,0 +1,26 @@ +{ + "kind": "tm:net:self:selfstate", + "name": "net1", + "partition": "Common", + "fullPath": "/Common/net1", + "generation": 7, + "selfLink": "https://localhost/mgmt/tm/net/self/~Common~net1?ver=13.0.0", + "address": "10.10.10.10%1/24", + "addressSource": "from-user", + "floating": "disabled", + "inheritedTrafficGroup": "false", + "trafficGroup": "/Common/traffic-group-local-only", + "trafficGroupReference": { + "link": "https://localhost/mgmt/tm/cm/traffic-group/~Common~traffic-group-local-only?ver=13.0.0" + }, + "unit": 0, + "vlan": "/Common/net1", + "vlanReference": { + "link": "https://localhost/mgmt/tm/net/vlan/~Common~net1?ver=13.0.0" + }, + "allowService": [ + "tcp:80", + "udp:53", + "gre:0" + ] +} diff --git a/test/units/modules/network/f5/test_bigip_selfip.py b/test/units/modules/network/f5/test_bigip_selfip.py new file mode 100644 index 0000000000..48266745e0 --- /dev/null +++ b/test/units/modules/network/f5/test_bigip_selfip.py @@ -0,0 +1,221 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2017 F5 Networks Inc. +# +# This file is part of Ansible +# +# Ansible is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Ansible is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with Ansible. If not, see . + +from __future__ import (absolute_import, division, print_function) +__metaclass__ = type + +import os +import json +import pytest +import sys + +from nose.plugins.skip import SkipTest +if sys.version_info < (2, 7): + raise SkipTest("F5 Ansible modules require Python >= 2.7") + +from ansible.compat.tests import unittest +from ansible.compat.tests.mock import patch, Mock +from ansible.module_utils import basic +from ansible.module_utils._text import to_bytes +from ansible.module_utils.f5_utils import AnsibleF5Client +from ansible.module_utils.f5_utils import F5ModuleError + +try: + from library.bigip_selfip import Parameters + from library.bigip_selfip import ApiParameters + from library.bigip_selfip import ModuleManager + from library.bigip_selfip import ArgumentSpec + from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError +except ImportError: + try: + from ansible.modules.network.f5.bigip_selfip import Parameters + from ansible.modules.network.f5.bigip_selfip import ApiParameters + from ansible.modules.network.f5.bigip_selfip import ModuleManager + from ansible.modules.network.f5.bigip_selfip import ArgumentSpec + from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError + except ImportError: + raise SkipTest("F5 Ansible modules require the f5-sdk Python library") + +fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') +fixture_data = {} + + +def set_module_args(args): + args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) + basic._ANSIBLE_ARGS = to_bytes(args) + + +def load_fixture(name): + path = os.path.join(fixture_path, name) + + if path in fixture_data: + return fixture_data[path] + + with open(path) as f: + data = f.read() + + try: + data = json.loads(data) + except Exception: + pass + + fixture_data[path] = data + return data + + +class TestParameters(unittest.TestCase): + def test_module_parameters(self): + args = dict( + address='10.10.10.10', + allow_service=[ + 'tcp:80', + 'udp:53', + 'gre' + ], + name='net1', + netmask='255.255.255.0', + partition='Common', + route_domain='1', + state='present', + traffic_group='traffic-group-local-only', + vlan='net1' + ) + p = Parameters(args) + assert p.address == '10.10.10.10%1/24' + assert p.allow_service == set(['tcp:80', 'udp:53', 'gre:0']) + assert p.name == 'net1' + assert p.netmask == 24 + assert p.route_domain == 1 + assert p.traffic_group == '/Common/traffic-group-local-only' + assert p.vlan == '/Common/net1' + + def test_module_invalid_service(self): + args = dict( + allow_service=[ + 'tcp:80', + 'udp:53', + 'grp' + ] + ) + p = Parameters(args) + with pytest.raises(F5ModuleError) as ex: + assert p.allow_service == set(['tcp:80', 'udp:53', 'grp']) + assert 'The provided protocol' in str(ex) + + def test_api_parameters(self): + args = dict( + address='10.10.10.10%1/24', + allowService=[ + 'tcp:80', + 'udp:53', + 'gre' + ], + name='net1', + state='present', + trafficGroup='/Common/traffic-group-local-only', + vlan='net1' + ) + p = ApiParameters(args) + assert p.address == '10.10.10.10%1/24' + assert p.allow_service == set(['tcp:80', 'udp:53', 'gre']) + assert p.name == 'net1' + assert p.netmask == 24 + assert p.route_domain == 1 + assert p.traffic_group == '/Common/traffic-group-local-only' + assert p.vlan == '/Common/net1' + + +@patch('ansible.module_utils.f5_utils.AnsibleF5Client._get_mgmt_root', + return_value=True) +class TestManager(unittest.TestCase): + + def setUp(self): + self.spec = ArgumentSpec() + + def test_create_selfip(self, *args): + set_module_args(dict( + address='10.10.10.10', + allow_service=[ + 'tcp:80', + 'udp:53', + 'gre' + ], + name='net1', + netmask='255.255.255.0', + partition='Common', + route_domain='1', + state='present', + traffic_group='traffic-group-local-only', + vlan='net1', + password='passsword', + server='localhost', + user='admin' + )) + + client = AnsibleF5Client( + argument_spec=self.spec.argument_spec, + supports_check_mode=self.spec.supports_check_mode, + f5_product_name=self.spec.f5_product_name + ) + mm = ModuleManager(client) + + # Override methods to force specific logic in the module to happen + mm.exists = Mock(side_effect=[False, True]) + mm.create_on_device = Mock(return_value=True) + + results = mm.exec_module() + + assert results['changed'] is True + + def test_create_selfip_idempotent(self, *args): + set_module_args(dict( + address='10.10.10.10', + allow_service=[ + 'tcp:80', + 'udp:53', + 'gre' + ], + name='net1', + netmask='255.255.255.0', + partition='Common', + route_domain='1', + state='present', + traffic_group='traffic-group-local-only', + vlan='net1', + password='passsword', + server='localhost', + user='admin' + )) + + current = ApiParameters(load_fixture('load_tm_net_self.json')) + + client = AnsibleF5Client( + argument_spec=self.spec.argument_spec, + supports_check_mode=self.spec.supports_check_mode, + f5_product_name=self.spec.f5_product_name + ) + mm = ModuleManager(client) + + # Override methods to force specific logic in the module to happen + mm.exists = Mock(side_effect=[True, True]) + mm.read_current_from_device = Mock(return_value=current) + + results = mm.exec_module() + + assert results['changed'] is False