From 1f1f1c9d048b41cf6b98278b1fedde50a87d8715 Mon Sep 17 00:00:00 2001 From: Tim Rupp Date: Sat, 2 Dec 2017 20:04:21 -0800 Subject: [PATCH] Refactors bigip_node (#33492) * Refactors bigip_node Includes a number of fixes and enhancements in addition to refactoring the code to be inline with f5 standards * Fixes upstream errors --- lib/ansible/modules/network/f5/bigip_node.py | 1067 +++++++++++------ .../network/f5/fixtures/load_ltm_node_1.json | 25 + .../network/f5/fixtures/load_ltm_node_3.json | 24 + .../modules/network/f5/test_bigip_node.py | 143 +++ 4 files changed, 877 insertions(+), 382 deletions(-) create mode 100644 test/units/modules/network/f5/fixtures/load_ltm_node_1.json create mode 100644 test/units/modules/network/f5/fixtures/load_ltm_node_3.json create mode 100644 test/units/modules/network/f5/test_bigip_node.py diff --git a/lib/ansible/modules/network/f5/bigip_node.py b/lib/ansible/modules/network/f5/bigip_node.py index 14e1f2a3d80..0609e56dbab 100644 --- a/lib/ansible/modules/network/f5/bigip_node.py +++ b/lib/ansible/modules/network/f5/bigip_node.py @@ -1,456 +1,759 @@ #!/usr/bin/python # -*- coding: utf-8 -*- # -# Copyright (c) 2017 F5 Networks Inc. -# Copyright (c) 2013 Matt Hite +# 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_node -short_description: "Manages F5 BIG-IP LTM nodes" +short_description: Manages F5 BIG-IP LTM nodes description: - - "Manages F5 BIG-IP LTM nodes via iControl SOAP API" + - Manages F5 BIG-IP LTM nodes. version_added: "1.4" -author: - - Matt Hite (@mhite) - - Tim Rupp (@caphrim007) -notes: - - "Requires BIG-IP software version >= 11" - - "F5 developed module 'bigsuds' required (see http://devcentral.f5.com)" - - "Best run as a local_action in your playbook" -requirements: - - bigsuds options: state: description: - - Pool member state - required: true + - Specifies the current state of the node. C(enabled) (All traffic + allowed), specifies that system sends traffic to this node regardless + of the node's state. C(disabled) (Only persistent or active connections + allowed), Specifies that the node can handle only persistent or + active connections. C(offline) (Only active connections allowed), + Specifies that the node can handle only active connections. In all + cases except C(absent), the node will be created if it does not yet + exist. + - Be particularly careful about changing the status of a node whose FQDN + cannot be resolved. These situations disable your ability to change their + C(state) to C(disabled) or C(offline). They will remain in an + *Unavailable - Enabled* state. default: present - choices: ['present', 'absent'] - aliases: [] - session_state: - description: - - Set new session availability status for node - version_added: "1.9" - required: false - default: null - choices: ['enabled', 'disabled'] - aliases: [] - monitor_state: - description: - - Set monitor availability status for node - version_added: "1.9" - required: false - default: null - choices: ['enabled', 'disabled'] - aliases: [] - partition: - description: - - Partition - required: false - default: 'Common' - choices: [] - aliases: [] + choices: + - present + - absent + - enabled + - disabled + - offline name: description: - - "Node name" - required: false - default: null - choices: [] + - Specifies the name of the node. + required: True monitor_type: description: - - Monitor rule type when monitors > 1 - version_added: "2.2" - required: False - default: null - choices: ['and_list', 'm_of_n'] - aliases: [] + - Monitor rule type when C(monitors) is specified. When creating a new + pool, if this value is not specified, the default of 'and_list' will + be used. + - Both C(single) and C(and_list) are functionally identical since BIG-IP + considers all monitors as "a list". BIG=IP either has a list of many, + or it has a list of one. Where they differ is in the extra guards that + C(single) provides; namely that it only allows a single monitor. + version_added: "1.3" + choices: ['and_list', 'm_of_n', 'single'] quorum: description: - - Monitor quorum value when monitor_type is m_of_n + - Monitor quorum value when C(monitor_type) is C(m_of_n). version_added: "2.2" - required: False - default: null - choices: [] - aliases: [] monitors: description: - - Monitor template name list. Always use the full path to the monitor. + - Specifies the health monitors that the system currently uses to + monitor this node. version_added: "2.2" - required: False - default: null - choices: [] - aliases: [] - host: + address: description: - - "Node IP. Required when state=present and node does not exist. Error when state=absent." - required: true - default: null - choices: [] - aliases: ['address', 'ip'] + - IP address of the node. This can be either IPv4 or IPv6. When creating a + new node, one of either C(address) or C(fqdn) must be provided. This + parameter cannot be updated after it is set. + aliases: + - ip + - host + version_added: "2.2" + fqdn: + description: + - FQDN name of the node. This can be any name that is a valid RFC 1123 DNS + name. Therefore, the only characters that can be used are "A" to "Z", + "a" to "z", "0" to "9", the hyphen ("-") and the period ("."). + - FQDN names must include at lease one period; delineating the host from + the domain. ex. C(host.domain). + - FQDN names must end with a letter or a number. + - When creating a new node, one of either C(address) or C(fqdn) must be + provided. This parameter cannot be updated after it is set. + aliases: + - hostname + version_added: "2.5" description: description: - - "Node description." - required: false - default: null - choices: [] + - Specifies descriptive text that identifies the node. + partition: + description: + - Device partition to manage resources on. + 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 + - Requires the netaddr Python package on the host. This is as easy as + pip install netaddr extends_documentation_fragment: f5 +requirements: + - f5-sdk >= 3.0.2 +author: + - Tim Rupp (@caphrim007) ''' -EXAMPLES = ''' +EXAMPLES = r''' - name: Add node bigip_node: - server: "lb.mydomain.com" - user: "admin" - password: "secret" - state: "present" - partition: "Common" - host: "10.20.30.40" - name: "10.20.30.40" - -# Note that the BIG-IP automatically names the node using the -# IP address specified in previous play's host parameter. -# Future plays referencing this node no longer use the host -# parameter but instead use the name parameter. -# Alternatively, you could have specified a name with the -# name parameter when state=present. + server: lb.mydomain.com + user: admin + password: secret + state: present + partition: Common + host: 10.20.30.40 + name: 10.20.30.40 + delegate_to: localhost - name: Add node with a single 'ping' monitor bigip_node: - server: "lb.mydomain.com" - user: "admin" - password: "secret" - state: "present" - partition: "Common" - host: "10.20.30.40" - name: "mytestserver" - monitors: - - /Common/icmp + server: lb.mydomain.com + user: admin + password: secret + state: present + partition: Common + host: 10.20.30.40 + name: mytestserver + monitors: + - /Common/icmp delegate_to: localhost - name: Modify node description bigip_node: - server: "lb.mydomain.com" - user: "admin" - password: "secret" - state: "present" - partition: "Common" - name: "10.20.30.40" - description: "Our best server yet" + server: lb.mydomain.com + user: admin + password: secret + state: present + partition: Common + name: 10.20.30.40 + description: Our best server yet delegate_to: localhost - name: Delete node bigip_node: - server: "lb.mydomain.com" - user: "admin" - password: "secret" - state: "absent" - partition: "Common" - name: "10.20.30.40" - -# The BIG-IP GUI doesn't map directly to the API calls for "Node -> -# General Properties -> State". The following states map to API monitor -# and session states. -# -# Enabled (all traffic allowed): -# monitor_state=enabled, session_state=enabled -# Disabled (only persistent or active connections allowed): -# monitor_state=enabled, session_state=disabled -# Forced offline (only active connections allowed): -# monitor_state=disabled, session_state=disabled -# -# See https://devcentral.f5.com/questions/icontrol-equivalent-call-for-b-node-down + server: lb.mydomain.com + user: admin + password: secret + state: absent + partition: Common + name: 10.20.30.40 + delegate_to: localhost - name: Force node offline bigip_node: - server: "lb.mydomain.com" - user: "admin" - password: "mysecret" - state: "present" - session_state: "disabled" - monitor_state: "disabled" - partition: "Common" - name: "10.20.30.40" + server: lb.mydomain.com + user: admin + password: secret + state: disabled + partition: Common + name: 10.20.30.40 + delegate_to: localhost + +- name: Add node by their FQDN + bigip_node: + server: lb.mydomain.com + user: admin + password: secret + state: present + partition: Common + fqdn: foo.bar.com + name: 10.20.30.40 + delegate_to: localhost ''' +RETURN = r''' +monitor_type: + description: + - Changed value for the monitor_type of the node. + returned: changed and success + type: string + sample: m_of_n +quorum: + description: + - Changed value for the quorum of the node. + returned: changed and success + type: int + sample: 1 +monitors: + description: + - Changed list of monitors for the node. + returned: changed and success + type: list + sample: ['icmp', 'tcp_echo'] +description: + description: + - Changed value for the description of the node. + returned: changed and success + type: string + sample: E-Commerce webserver in ORD +session: + description: + - Changed value for the internal session of the node. + returned: changed and success + type: string + sample: user-disabled +state: + description: + - Changed value for the internal state of the node. + returned: changed and success + type: string + sample: m_of_n +''' -def node_exists(api, address): - # hack to determine if node exists - result = False - try: - api.LocalLB.NodeAddressV2.get_object_status(nodes=[address]) - result = True - except bigsuds.OperationFailed as e: - if "was not found" in str(e): - result = False +import re +import time + +try: + import netaddr + HAS_NETADDR = True +except ImportError: + HAS_NETADDR = False + +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 ansible.module_utils.f5_utils import iControlUnexpectedHTTPError +except ImportError: + HAS_F5SDK = False + + +class Parameters(AnsibleF5Parameters): + api_map = { + 'monitor': 'monitors' + } + + api_attributes = [ + 'monitor', 'description', 'address', 'fqdn', + + # Used for changing state + # + # user-enabled (enabled) + # user-disabled (disabled) + # user-disabled (offline) + 'session', + + # Used for changing state + # user-down (offline) + 'state' + ] + + returnables = [ + 'monitor_type', 'quorum', 'monitors', 'description', 'fqdn', 'session', 'state' + ] + + updatables = [ + 'monitor_type', 'quorum', 'monitors', 'description', 'state' + ] + + def __init__(self, params=None): + self._values = defaultdict(lambda: None) + self._values['__warnings'] = [] + if params: + self.update(params=params) + + 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 + + # 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 to_return(self): + result = {} + try: + for returnable in self.returnables: + result[returnable] = getattr(self, returnable) + result = self._filter_params(result) + return result + except Exception: + return result + + 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: + result[api_attribute] = getattr(self, api_attribute) + result = self._filter_params(result) + return result + + 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 monitors_list(self): + if self._values['monitors'] is None: + return [] + try: + result = re.findall(r'/\w+/[^\s}]+', self._values['monitors']) + return result + except Exception: + return self._values['monitors'] + + @property + def monitors(self): + if self._values['monitors'] is None: + return None + monitors = [self._fqdn_name(x) for x in self.monitors_list] + if self.monitor_type == 'm_of_n': + monitors = ' '.join(monitors) + result = 'min %s of { %s }' % (self.quorum, monitors) else: - # genuine exception - raise - return result - - -def create_node_address(api, address, name): - try: - api.LocalLB.NodeAddressV2.create( - nodes=[name], - addresses=[address], - limits=[0] - ) - result = True - desc = "" - except bigsuds.OperationFailed as e: - if "already exists" in str(e): - result = False - desc = "referenced name or IP already in use" + result = ' and '.join(monitors).strip() + + return result + + @property + def quorum(self): + if self.kind == 'tm:ltm:pool:poolstate': + if self._values['monitors'] is None: + return None + pattern = r'min\s+(?P\d+)\s+of' + matches = re.search(pattern, self._values['monitors']) + if matches: + quorum = matches.group('quorum') + else: + quorum = None else: - # genuine exception - raise - return (result, desc) - - -def get_node_address(api, name): - return api.LocalLB.NodeAddressV2.get_address(nodes=[name])[0] - + quorum = self._values['quorum'] + try: + if quorum is None: + return None + return int(quorum) + except ValueError: + raise F5ModuleError( + "The specified 'quorum' must be an integer." + ) -def delete_node_address(api, address): - try: - api.LocalLB.NodeAddressV2.delete_node_address(nodes=[address]) - result = True - desc = "" - except bigsuds.OperationFailed as e: - if "is referenced by a member of pool" in str(e): - result = False - desc = "node referenced by pool" + @property + def monitor_type(self): + if self.kind == 'tm:ltm:node:nodestate': + if self._values['monitors'] is None: + return None + pattern = r'min\s+\d+\s+of' + matches = re.search(pattern, self._values['monitors']) + if matches: + return 'm_of_n' + else: + return 'and_list' else: - # genuine exception - raise - return (result, desc) - - -def set_node_description(api, name, description): - api.LocalLB.NodeAddressV2.set_description(nodes=[name], - descriptions=[description]) - - -def get_node_description(api, name): - return api.LocalLB.NodeAddressV2.get_description(nodes=[name])[0] - - -def set_node_session_enabled_state(api, name, session_state): - session_state = "STATE_%s" % session_state.strip().upper() - api.LocalLB.NodeAddressV2.set_session_enabled_state(nodes=[name], - states=[session_state]) - - -def get_node_session_status(api, name): - result = api.LocalLB.NodeAddressV2.get_session_status(nodes=[name])[0] - result = result.split("SESSION_STATUS_")[-1].lower() - return result - + if self._values['monitor_type'] is None: + return None + return self._values['monitor_type'] + + @property + def fqdn(self): + if self._values['fqdn'] is None: + return None + result = dict( + addressFamily='ipv4', + autopopulate='disabled', + downInterval=3600, + tmName=self._values['fqdn'] + ) + return result + + +class Changes(Parameters): + pass + + +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 monitor_type(self): + if self.want.monitor_type is None: + self.want.update(dict(monitor_type=self.have.monitor_type)) + if self.want.quorum is None: + self.want.update(dict(quorum=self.have.quorum)) + if self.want.monitor_type == 'm_of_n' and self.want.quorum is None: + raise F5ModuleError( + "Quorum value must be specified with monitor_type 'm_of_n'." + ) + elif self.want.monitor_type == 'single': + if len(self.want.monitors_list) > 1: + raise F5ModuleError( + "When using a 'monitor_type' of 'single', only one monitor may be provided." + ) + elif len(self.have.monitors_list) > 1 and len(self.want.monitors_list) == 0: + # Handle instances where there already exists many monitors, and the + # user runs the module again specifying that the monitor_type should be + # changed to 'single' + raise F5ModuleError( + "A single monitor must be specified if more than one monitor currently exists on your pool." + ) + # Update to 'and_list' here because the above checks are all that need + # to be done before we change the value back to what is expected by + # BIG-IP. + # + # Remember that 'single' is nothing more than a fancy way of saying + # "and_list plus some extra checks" + self.want.update(dict(monitor_type='and_list')) + if self.want.monitor_type != self.have.monitor_type: + return self.want.monitor_type + + @property + def monitors(self): + if self.want.monitor_type is None: + self.want.update(dict(monitor_type=self.have.monitor_type)) + if not self.want.monitors_list: + self.want.monitors = self.have.monitors_list + if not self.want.monitors and self.want.monitor_type is not None: + raise F5ModuleError( + "The 'monitors' parameter cannot be empty when 'monitor_type' parameter is specified" + ) + if self.want.monitors != self.have.monitors: + return self.want.monitors + + @property + def state(self): + result = None + if self.want.state in ['present', 'enabled']: + if self.have.session not in ['user-enabled', 'monitor-enabled']: + result = dict( + session='user-enabled', + state='user-up', + ) + elif self.want.state == 'disabled': + if self.have.session != 'user-disabled' or self.have.state == 'user-down': + result = dict( + session='user-disabled', + state='user-up' + ) + elif self.want.state == 'offline': + if self.have.state != 'user-down': + result = dict( + session='user-disabled', + state='user-down' + ) + return result + + +class ModuleManager(object): + def __init__(self, client): + self.client = client + self.have = None + self.want = Parameters(self.client.module.params) + self.changes = Changes() + + 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 = Changes(changed) + + def _update_changed_options(self): + diff = Difference(self.want, self.have) + updatables = Parameters.updatables + changed = dict() + for k in updatables: + change = diff.compare(k) + if change is None: + continue + else: + if isinstance(change, dict): + changed.update(change) + else: + changed[k] = change + if changed: + self.changes = Changes(changed) + return True + return False + + def _announce_deprecations(self): + warnings = [] + if self.want: + warnings += self.want._values.get('__warnings', []) + if self.have: + warnings += self.have._values.get('__warnings', []) + for warning in warnings: + self.client.module.deprecate( + msg=warning['msg'], + version=warning['version'] + ) -def set_node_monitor_state(api, name, monitor_state): - monitor_state = "STATE_%s" % monitor_state.strip().upper() - api.LocalLB.NodeAddressV2.set_monitor_state(nodes=[name], - states=[monitor_state]) + def exec_module(self): + changed = False + result = dict() + state = self.want.state + + try: + if state in ['present', 'enabled', 'disabled', 'offline']: + changed = self.present() + elif state == "absent": + changed = self.absent() + except IOError as e: + raise F5ModuleError(str(e)) + + changes = self.changes.to_return() + result.update(**changes) + result.update(dict(changed=changed)) + self._announce_deprecations() + return result + + def present(self): + if self.exists(): + return self.update() + else: + return self.create() + def _check_required_creation_vars(self): + if self.want.address is None and self.want.fqdn is None: + raise F5ModuleError( + "At least one of 'address' or 'fqdn' is required when creating a node" + ) + elif self.want.address is not None and self.want.fqdn is not None: + raise F5ModuleError( + "Only one of 'address' or 'fqdn' can be provided when creating a node" + ) + elif self.want.fqdn is not None: + self.want.update(dict(address='any6')) + + def _munge_creation_state_for_device(self): + # Modifying the state before sending to BIG-IP + # + # The 'state' must be set to None to exclude the values (accepted by this + # module) from being sent to the BIG-IP because for specific Ansible states, + # BIG-IP will consider those state values invalid. + if self.want.state in ['present', 'enabled']: + self.want.update(dict( + session='user-enabled', + state='user-up', + )) + elif self.want.state in 'disabled': + self.want.update(dict( + session='user-disabled', + state='user-up' + )) + else: + # State 'offline' + # Offline state will result in the monitors stopping for the node + self.want.update(dict( + session='user-disabled', + + # only a valid state can be specified. The module's value is "offline", + # but this is an invalid value for the BIG-IP. Therefore set it to user-down. + state='user-down', + + # Even user-down wil not work when _creating_ a node, so we register another + # want value (that is not sent to the API). This is checked for later to + # determine if we have to PATCH the node to be offline. + is_offline=True + )) + + def create(self): + self._check_required_creation_vars() + self._munge_creation_state_for_device() + self._set_changed_options() + if self.client.check_mode: + return True + self.create_on_device() + if not self.exists(): + raise F5ModuleError("Failed to create the node") + # It appears that you cannot create a node in an 'offline' state, so instead + # we update its status to offline after we create it. + if self.want.is_offline: + self.update_node_offline_on_device() + return True + + def should_update(self): + result = self._update_changed_options() + if result: + return True + return False + + 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() + if self.want.state == 'offline': + self.update_node_offline_on_device() + return True + + def absent(self): + if self.exists(): + return self.remove() + return False + + def remove(self): + if self.client.check_mode: + return True + self.remove_from_device() + if self.exists(): + raise F5ModuleError("Failed to delete the node.") + return True + + def read_current_from_device(self): + resource = self.client.api.tm.ltm.nodes.node.load( + name=self.want.name, + partition=self.want.partition + ) + result = resource.attrs + return Parameters(result) -def get_node_monitor_status(api, name): - result = api.LocalLB.NodeAddressV2.get_monitor_status(nodes=[name])[0] - result = result.split("MONITOR_STATUS_")[-1].lower() - return result + def exists(self): + result = self.client.api.tm.ltm.nodes.node.exists( + name=self.want.name, + partition=self.want.partition + ) + return result + def update_node_offline_on_device(self): + params = dict( + session="user-disabled", + state="user-down" + ) + result = self.client.api.tm.ltm.nodes.node.load( + name=self.want.name, + partition=self.want.partition + ) + result.modify(**params) -def get_monitors(api, name): - result = api.LocalLB.NodeAddressV2.get_monitor_rule(nodes=[name])[0] - monitor_type = result['type'].split("MONITOR_RULE_TYPE_")[-1].lower() - quorum = result['quorum'] - monitor_templates = result['monitor_templates'] - return (monitor_type, quorum, monitor_templates) + def update_on_device(self): + params = self.changes.api_params() + result = self.client.api.tm.ltm.nodes.node.load( + name=self.want.name, + partition=self.want.partition + ) + result.modify(**params) + + def create_on_device(self): + params = self.want.api_params() + resource = self.client.api.tm.ltm.nodes.node.create( + name=self.want.name, + partition=self.want.partition, + **params + ) + self._wait_for_fqdn_checks(resource) + def _wait_for_fqdn_checks(self, resource): + while True: + if resource.state == 'fqdn-checking': + resource.refresh() + time.sleep(1) + else: + break -def set_monitors(api, name, monitor_type, quorum, monitor_templates): - monitor_type = "MONITOR_RULE_TYPE_%s" % monitor_type.strip().upper() - monitor_rule = {'type': monitor_type, 'quorum': quorum, 'monitor_templates': monitor_templates} - api.LocalLB.NodeAddressV2.set_monitor_rule(nodes=[name], - monitor_rules=[monitor_rule]) + def remove_from_device(self): + result = self.client.api.tm.ltm.nodes.node.load( + name=self.want.name, + partition=self.want.partition + ) + if result: + result.delete() + + +class ArgumentSpec(object): + def __init__(self): + self.supports_check_mode = True + self.argument_spec = dict( + name=dict(required=True), + address=dict( + aliases=['host', 'ip'] + ), + fqdn=dict( + aliases=['hostname'] + ), + description=dict(), + monitor_type=dict( + choices=[ + 'and_list', 'm_of_n', 'single' + ] + ), + quorum=dict(type='int'), + monitors=dict(type='list'), + state=dict( + choices=['absent', 'present', 'enabled', 'disabled', 'offline'], + default='present' + ) + ) + self.f5_product_name = 'bigip' def main(): - monitor_type_choices = ['and_list', 'm_of_n'] - - argument_spec = f5_argument_spec() - - meta_args = dict( - session_state=dict(type='str', choices=['enabled', 'disabled']), - monitor_state=dict(type='str', choices=['enabled', 'disabled']), - name=dict(type='str', required=True), - host=dict(type='str', aliases=['address', 'ip']), - description=dict(type='str'), - monitor_type=dict(type='str', choices=monitor_type_choices), - quorum=dict(type='int'), - monitors=dict(type='list') - ) - argument_spec.update(meta_args) + spec = ArgumentSpec() - module = AnsibleModule( - argument_spec=argument_spec, - supports_check_mode=True + 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_F5SDK: + raise F5ModuleError("The python f5-sdk module is required") - if module.params['validate_certs']: - import ssl - if not hasattr(ssl, 'SSLContext'): - module.fail_json( - msg='bigsuds does not support verifying certificates with python < 2.7.9. Either update python or set validate_certs=False on the task' - ) + if not HAS_NETADDR: + raise F5ModuleError("The python netaddr module is required") - server = module.params['server'] - server_port = module.params['server_port'] - user = module.params['user'] - password = module.params['password'] - state = module.params['state'] - partition = module.params['partition'] - validate_certs = module.params['validate_certs'] - - session_state = module.params['session_state'] - monitor_state = module.params['monitor_state'] - host = module.params['host'] - name = module.params['name'] - address = fq_name(partition, name) - description = module.params['description'] - monitor_type = module.params['monitor_type'] - if monitor_type: - monitor_type = monitor_type.lower() - quorum = module.params['quorum'] - monitors = module.params['monitors'] - if monitors: - monitors = [] - for monitor in module.params['monitors']: - monitors.append(fq_name(partition, monitor)) - - # sanity check user supplied values - if state == 'absent' and host is not None: - module.fail_json(msg="host parameter invalid when state=absent") - - if monitors: - if len(monitors) == 1: - # set default required values for single monitor - quorum = 0 - monitor_type = 'single' - elif len(monitors) > 1: - if not monitor_type: - module.fail_json(msg="monitor_type required for monitors > 1") - if monitor_type == 'm_of_n' and not quorum: - module.fail_json(msg="quorum value required for monitor_type m_of_n") - if monitor_type != 'm_of_n': - quorum = 0 - elif monitor_type: - # no monitors specified but monitor_type exists - module.fail_json(msg="monitor_type require monitors parameter") - elif quorum is not None: - # no monitors specified but quorum exists - module.fail_json(msg="quorum requires monitors parameter") + mm = ModuleManager(client) + results = mm.exec_module() + client.module.exit_json(**results) + except F5ModuleError as e: + client.module.fail_json(msg=str(e)) - try: - api = bigip_api(server, user, password, validate_certs, port=server_port) - result = {'changed': False} # default - - if state == 'absent': - if node_exists(api, address): - if not module.check_mode: - deleted, desc = delete_node_address(api, address) - if not deleted: - module.fail_json(msg="unable to delete: %s" % desc) - else: - result = {'changed': True} - else: - # check-mode return value - result = {'changed': True} - - elif state == 'present': - if not node_exists(api, address): - if host is None: - module.fail_json(msg="host parameter required when " - "state=present and node does not exist") - if not module.check_mode: - created, desc = create_node_address(api, address=host, name=address) - if not created: - module.fail_json(msg="unable to create: %s" % desc) - else: - result = {'changed': True} - if session_state is not None: - set_node_session_enabled_state(api, address, - session_state) - result = {'changed': True} - if monitor_state is not None: - set_node_monitor_state(api, address, monitor_state) - result = {'changed': True} - if description is not None: - set_node_description(api, address, description) - result = {'changed': True} - if monitors: - set_monitors(api, address, monitor_type, quorum, monitors) - else: - # check-mode return value - result = {'changed': True} - else: - # node exists -- potentially modify attributes - if host is not None: - if get_node_address(api, address) != host: - module.fail_json(msg="Changing the node address is " - "not supported by the API; " - "delete and recreate the node.") - if session_state is not None: - session_status = get_node_session_status(api, address) - if session_state == 'enabled' and \ - session_status == 'forced_disabled': - if not module.check_mode: - set_node_session_enabled_state(api, address, - session_state) - result = {'changed': True} - elif session_state == 'disabled' and \ - session_status != 'force_disabled': - if not module.check_mode: - set_node_session_enabled_state(api, address, - session_state) - result = {'changed': True} - if monitor_state is not None: - monitor_status = get_node_monitor_status(api, address) - if monitor_state == 'enabled' and \ - monitor_status == 'forced_down': - if not module.check_mode: - set_node_monitor_state(api, address, - monitor_state) - result = {'changed': True} - elif monitor_state == 'disabled' and \ - monitor_status != 'forced_down': - if not module.check_mode: - set_node_monitor_state(api, address, - monitor_state) - result = {'changed': True} - if description is not None: - if get_node_description(api, address) != description: - if not module.check_mode: - set_node_description(api, address, description) - result = {'changed': True} - if monitors: - t_monitor_type, t_quorum, t_monitor_templates = get_monitors(api, address) - if (t_monitor_type != monitor_type) or (t_quorum != quorum) or (set(t_monitor_templates) != set(monitors)): - if not module.check_mode: - set_monitors(api, address, monitor_type, quorum, monitors) - result = {'changed': True} - except Exception as e: - module.fail_json(msg="received exception: %s" % e) - - module.exit_json(**result) - -from ansible.module_utils.basic import * -from ansible.module_utils.f5_utils import * if __name__ == '__main__': main() diff --git a/test/units/modules/network/f5/fixtures/load_ltm_node_1.json b/test/units/modules/network/f5/fixtures/load_ltm_node_1.json new file mode 100644 index 00000000000..96d25b03d12 --- /dev/null +++ b/test/units/modules/network/f5/fixtures/load_ltm_node_1.json @@ -0,0 +1,25 @@ +{ + "kind": "tm:ltm:node:nodestate", + "name": "foo", + "partition": "Common", + "fullPath": "/Common/foo", + "generation": 158, + "selfLink": "https://localhost/mgmt/tm/ltm/node/~Common~foo?ver=13.0.0", + "address": "1.2.3.4", + "connectionLimit": 0, + "description": "my description of node", + "dynamicRatio": 1, + "ephemeral": "false", + "fqdn": { + "addressFamily": "ipv4", + "autopopulate": "disabled", + "downInterval": 5, + "interval": "3600" + }, + "logging": "disabled", + "monitor": "default", + "rateLimit": "disabled", + "ratio": 1, + "session": "user-enabled", + "state": "unchecked" +} diff --git a/test/units/modules/network/f5/fixtures/load_ltm_node_3.json b/test/units/modules/network/f5/fixtures/load_ltm_node_3.json new file mode 100644 index 00000000000..c6e30cf32e6 --- /dev/null +++ b/test/units/modules/network/f5/fixtures/load_ltm_node_3.json @@ -0,0 +1,24 @@ +{ + "kind": "tm:ltm:node:nodestate", + "name": "mytestserver", + "partition": "Common", + "fullPath": "/Common/mytestserver", + "generation": 2286, + "selfLink": "https://localhost/mgmt/tm/ltm/node/~Common~mytestserver?ver=13.0.0", + "address": "10.20.30.40", + "connectionLimit": 0, + "dynamicRatio": 1, + "ephemeral": "false", + "fqdn": { + "addressFamily": "ipv4", + "autopopulate": "disabled", + "downInterval": 5, + "interval": "3600" + }, + "logging": "disabled", + "monitor": "/Common/icmp ", + "rateLimit": "disabled", + "ratio": 1, + "session": "monitor-enabled", + "state": "down" +} diff --git a/test/units/modules/network/f5/test_bigip_node.py b/test/units/modules/network/f5/test_bigip_node.py new file mode 100644 index 00000000000..fa014368795 --- /dev/null +++ b/test/units/modules/network/f5/test_bigip_node.py @@ -0,0 +1,143 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2017 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 + +import os +import json +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 Mock +from ansible.compat.tests.mock import patch +from ansible.module_utils.f5_utils import AnsibleF5Client + +try: + from library.bigip_node import Parameters + from library.bigip_node import ModuleManager + from library.bigip_node import ArgumentSpec + from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError + from test.unit.modules.utils import set_module_args +except ImportError: + try: + from ansible.modules.network.f5.bigip_node import Parameters + from ansible.modules.network.f5.bigip_node import ModuleManager + from ansible.modules.network.f5.bigip_node import ArgumentSpec + from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError + from units.modules.utils import set_module_args + 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 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( + host='10.20.30.40', + name='10.20.30.40' + ) + + p = Parameters(args) + assert p.host == '10.20.30.40' + assert p.name == '10.20.30.40' + + def test_api_parameters(self): + args = load_fixture('load_ltm_node_1.json') + + p = Parameters(args) + assert p.address == '1.2.3.4' + + +@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_node(self, *args): + set_module_args(dict( + host='10.20.30.40', + name='mytestserver', + monitors=[ + '/Common/icmp' + ], + partition='Common', + state='present', + 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( + host='10.20.30.40', + name='mytestserver', + monitors=[ + '/Common/icmp' + ], + partition='Common', + state='present', + password='passsword', + server='localhost', + user='admin' + )) + + current = Parameters(load_fixture('load_ltm_node_3.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