Remove f5-sdk from bigip_gtm_wide_ip (#48509)

This commit is contained in:
Tim Rupp 2018-11-10 18:48:52 -08:00 committed by GitHub
parent 4a74c1fec6
commit ce06cfe8ef
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 255 additions and 106 deletions

View file

@ -1,7 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
# Copyright (c) 2017 F5 Networks Inc. # Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # 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 from __future__ import absolute_import, division, print_function
@ -11,6 +11,7 @@ __metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'], 'status': ['stableinterface'],
'supported_by': 'certified'} 'supported_by': 'certified'}
DOCUMENTATION = r''' DOCUMENTATION = r'''
--- ---
module: bigip_gtm_wide_ip module: bigip_gtm_wide_ip
@ -104,9 +105,17 @@ options:
- You can use the same wildcard characters for aliases as you can for actual - You can use the same wildcard characters for aliases as you can for actual
wide IP names. wide IP names.
version_added: 2.7 version_added: 2.7
last_resort_pool:
description:
- Specifies which GTM pool, for the system to use as the last resort pool for
the wide IP.
- The valid pools for this parameter are those with the C(type) specified in this
module.
version_added: 2.8
extends_documentation_fragment: f5 extends_documentation_fragment: f5
author: author:
- Tim Rupp (@caphrim007) - Tim Rupp (@caphrim007)
- Wojciech Wypior (@wojtek0806)
''' '''
EXAMPLES = r''' EXAMPLES = r'''
@ -194,38 +203,38 @@ from ansible.module_utils.six import iteritems
from distutils.version import LooseVersion from distutils.version import LooseVersion
try: try:
from library.module_utils.network.f5.bigip import HAS_F5SDK from library.module_utils.network.f5.bigip import F5RestClient
from library.module_utils.network.f5.bigip import F5Client
from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import fq_name from library.module_utils.network.f5.common import fq_name
from library.module_utils.network.f5.common import is_valid_fqdn
from library.module_utils.network.f5.common import f5_argument_spec from library.module_utils.network.f5.common import f5_argument_spec
from library.module_utils.network.f5.common import transform_name
try: from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError from library.module_utils.network.f5.common import fail_json
except ImportError: from library.module_utils.network.f5.common import is_valid_fqdn
HAS_F5SDK = False from library.module_utils.network.f5.icontrol import tmos_version
from library.module_utils.network.f5.icontrol import module_provisioned
except ImportError: except ImportError:
from ansible.module_utils.network.f5.bigip import HAS_F5SDK from ansible.module_utils.network.f5.bigip import F5RestClient
from ansible.module_utils.network.f5.bigip import F5Client
from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import fq_name from ansible.module_utils.network.f5.common import fq_name
from ansible.module_utils.network.f5.common import is_valid_fqdn
from ansible.module_utils.network.f5.common import f5_argument_spec from ansible.module_utils.network.f5.common import f5_argument_spec
try: from ansible.module_utils.network.f5.common import transform_name
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError from ansible.module_utils.network.f5.common import exit_json
except ImportError: from ansible.module_utils.network.f5.common import fail_json
HAS_F5SDK = False from ansible.module_utils.network.f5.common import is_valid_fqdn
from ansible.module_utils.network.f5.icontrol import tmos_version
from ansible.module_utils.network.f5.icontrol import module_provisioned
class Parameters(AnsibleF5Parameters): class Parameters(AnsibleF5Parameters):
api_map = { api_map = {
'poolLbMode': 'pool_lb_method', 'poolLbMode': 'pool_lb_method',
'rules': 'irules', 'rules': 'irules',
'lastResortPool': 'last_resort_pool',
} }
updatables = [ updatables = [
@ -236,6 +245,7 @@ class Parameters(AnsibleF5Parameters):
'enabled', 'enabled',
'disabled', 'disabled',
'aliases', 'aliases',
'last_resort_pool',
] ]
returnables = [ returnables = [
@ -245,6 +255,7 @@ class Parameters(AnsibleF5Parameters):
'pools', 'pools',
'irules', 'irules',
'aliases', 'aliases',
'last_resort_pool',
] ]
api_attributes = [ api_attributes = [
@ -254,6 +265,7 @@ class Parameters(AnsibleF5Parameters):
'pools', 'pools',
'rules', 'rules',
'aliases', 'aliases',
'lastResortPool',
] ]
@ -274,7 +286,7 @@ class ApiParameters(Parameters):
def pools(self): def pools(self):
result = [] result = []
if self._values['pools'] is None: if self._values['pools'] is None:
return None return []
pools = sorted(self._values['pools'], key=lambda x: x['order']) pools = sorted(self._values['pools'], key=lambda x: x['order'])
for item in pools: for item in pools:
pool = dict() pool = dict()
@ -288,8 +300,22 @@ class ApiParameters(Parameters):
result.append(pool) result.append(pool)
return result return result
@property
def last_resort_pool(self):
if self._values['last_resort_pool'] in [None, '', 'none']:
return ''
return self._values['last_resort_pool']
class ModuleParameters(Parameters): class ModuleParameters(Parameters):
@property
def last_resort_pool(self):
if self._values['last_resort_pool'] in [None, '', 'none']:
return ''
return '{0} {1}'.format(
self.type, fq_name(self.partition, self._values['last_resort_pool'])
)
@property @property
def pool_lb_method(self): def pool_lb_method(self):
if self._values['pool_lb_method'] is None: if self._values['pool_lb_method'] is None:
@ -431,6 +457,14 @@ class ReportableChanges(Changes):
) )
return result return result
@property
def last_resort_pool(self):
if self._values['last_resort_pool'] is None:
return None
if self._values['last_resort_pool'] in ['', 'none']:
return 'none'
return self._values['last_resort_pool'].split(' ')[1]
class Difference(object): class Difference(object):
def __init__(self, want, have=None): def __init__(self, want, have=None):
@ -472,6 +506,15 @@ class Difference(object):
else: else:
return want return want
@property
def last_resort_pool(self):
if self.want.last_resort_pool is None:
return None
if self.want.last_resort_pool == '' and self.have.last_resort_pool == '':
return None
if self.want.last_resort_pool != self.have.last_resort_pool:
return self.want.last_resort_pool
@property @property
def state(self): def state(self):
if self.want.state == 'disabled' and self.have.enabled: if self.want.state == 'disabled' and self.have.enabled:
@ -516,6 +559,10 @@ class ModuleManager(object):
self.kwargs = kwargs self.kwargs = kwargs
def exec_module(self): def exec_module(self):
if not module_provisioned(self.client, 'gtm'):
raise F5ModuleError(
"GTM must be provisioned to use this module."
)
if self.version_is_less_than_12(): if self.version_is_less_than_12():
manager = self.get_manager('untyped') manager = self.get_manager('untyped')
else: else:
@ -529,7 +576,7 @@ class ModuleManager(object):
return UntypedManager(**self.kwargs) return UntypedManager(**self.kwargs)
def version_is_less_than_12(self): def version_is_less_than_12(self):
version = self.client.api.tmos_version version = tmos_version(self.client)
if LooseVersion(version) < LooseVersion('12.0.0'): if LooseVersion(version) < LooseVersion('12.0.0'):
return True return True
else: else:
@ -575,13 +622,10 @@ class BaseManager(object):
result = dict() result = dict()
state = self.want.state state = self.want.state
try: if state in ["present", "disabled"]:
if state in ["present", "disabled"]: changed = self.present()
changed = self.present() elif state == "absent":
elif state == "absent": changed = self.absent()
changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
reportable = ReportableChanges(params=self.changes.to_return()) reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return() changes = reportable.to_return()
@ -646,42 +690,89 @@ class BaseManager(object):
class UntypedManager(BaseManager): class UntypedManager(BaseManager):
def exists(self): def exists(self):
return self.client.api.tm.gtm.wideips.wideip.exists( uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}".format(
name=self.want.name, self.client.provider['server'],
partition=self.want.partition self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
) )
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError:
return False
if resp.status == 404 or 'code' in response and response['code'] == 404:
return False
return True
def update_on_device(self): def update_on_device(self):
params = self.changes.api_params() params = self.changes.api_params()
result = self.client.api.tm.gtm.wideips.wipeip.load( uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}".format(
name=self.want.name, self.client.provider['server'],
partition=self.want.partition self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
) )
result.modify(**params) resp = self.client.api.patch(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def read_current_from_device(self): def read_current_from_device(self):
resource = self.client.api.tm.gtm.wideips.wideip.load( uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}".format(
name=self.want.name, self.client.provider['server'],
partition=self.want.partition self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
) )
result = resource.attrs resp = self.client.api.get(uri)
return ApiParameters(params=result) try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return ApiParameters(params=response)
def create_on_device(self): def create_on_device(self):
params = self.changes.api_params() params = self.changes.api_params()
self.client.api.tm.gtm.wideips.wideip.create( params['name'] = self.want.name
name=self.want.name, params['partition'] = self.want.partition
partition=self.want.partition, uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/".format(
**params self.client.provider['server'],
self.client.provider['server_port']
) )
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return response['selfLink']
def remove_from_device(self): def remove_from_device(self):
result = self.client.api.tm.gtm.wideips.wideip.load( uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}".format(
name=self.want.name, self.client.provider['server'],
partition=self.want.partition self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
) )
if result: response = self.client.api.delete(uri)
result.delete() if response.status == 200:
return True
raise F5ModuleError(response.content)
class TypedManager(BaseManager): class TypedManager(BaseManager):
@ -692,69 +783,96 @@ class TypedManager(BaseManager):
"The 'type' option is required for BIG-IP instances " "The 'type' option is required for BIG-IP instances "
"greater than or equal to 12.x" "greater than or equal to 12.x"
) )
type_map = dict(
a='a_s',
aaaa='aaaas',
cname='cnames',
mx='mxs',
naptr='naptrs',
srv='srvs'
)
self.collection = type_map[self.want.type]
def exists(self): def exists(self):
wideips = self.client.api.tm.gtm.wideips uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/{3}".format(
collection = getattr(wideips, self.collection) self.client.provider['server'],
resource = getattr(collection, self.want.type) self.client.provider['server_port'],
result = resource.exists( self.want.type,
name=self.want.name, transform_name(self.want.partition, self.want.name)
partition=self.want.partition
) )
return result resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError:
return False
if resp.status == 404 or 'code' in response and response['code'] == 404:
return False
return True
def update_on_device(self): def update_on_device(self):
params = self.changes.api_params() params = self.changes.api_params()
wideips = self.client.api.tm.gtm.wideips uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/{3}".format(
collection = getattr(wideips, self.collection) self.client.provider['server'],
resource = getattr(collection, self.want.type) self.client.provider['server_port'],
result = resource.load( self.want.type,
name=self.want.name, transform_name(self.want.partition, self.want.name)
partition=self.want.partition
) )
result.modify(**params) resp = self.client.api.patch(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def read_current_from_device(self): def read_current_from_device(self):
wideips = self.client.api.tm.gtm.wideips uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/{3}".format(
collection = getattr(wideips, self.collection) self.client.provider['server'],
resource = getattr(collection, self.want.type) self.client.provider['server_port'],
result = resource.load( self.want.type,
name=self.want.name, transform_name(self.want.partition, self.want.name)
partition=self.want.partition
) )
result = result.attrs resp = self.client.api.get(uri)
return ApiParameters(params=result) try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return ApiParameters(params=response)
def create_on_device(self): def create_on_device(self):
params = self.changes.api_params() params = self.changes.api_params()
wideips = self.client.api.tm.gtm.wideips params['name'] = self.want.name
collection = getattr(wideips, self.collection) params['partition'] = self.want.partition
resource = getattr(collection, self.want.type) uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/".format(
resource.create( self.client.provider['server'],
name=self.want.name, self.client.provider['server_port'],
partition=self.want.partition, self.want.type
**params
) )
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return response['selfLink']
def remove_from_device(self): def remove_from_device(self):
wideips = self.client.api.tm.gtm.wideips uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/{3}".format(
collection = getattr(wideips, self.collection) self.client.provider['server'],
resource = getattr(collection, self.want.type) self.client.provider['server_port'],
result = resource.load( self.want.type,
name=self.want.name, transform_name(self.want.partition, self.want.name)
partition=self.want.partition
) )
if result: response = self.client.api.delete(uri)
result.delete() if response.status == 200:
return True
raise F5ModuleError(response.content)
class ArgumentSpec(object): class ArgumentSpec(object):
@ -800,7 +918,8 @@ class ArgumentSpec(object):
), ),
aliases=dict( aliases=dict(
type='list' type='list'
) ),
last_resort_pool=dict(),
) )
self.argument_spec = {} self.argument_spec = {}
self.argument_spec.update(f5_argument_spec) self.argument_spec.update(f5_argument_spec)
@ -812,20 +931,19 @@ def main():
module = AnsibleModule( module = AnsibleModule(
argument_spec=spec.argument_spec, argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode supports_check_mode=spec.supports_check_mode,
) )
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required") client = F5RestClient(**module.params)
try: try:
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client) mm = ModuleManager(module=module, client=client)
results = mm.exec_module() results = mm.exec_module()
cleanup_tokens(client) cleanup_tokens(client)
module.exit_json(**results) exit_json(module, results, client)
except F5ModuleError as e: except F5ModuleError as ex:
cleanup_tokens(client) cleanup_tokens(client)
module.fail_json(msg=str(e)) fail_json(module, ex, client)
if __name__ == '__main__': if __name__ == '__main__':

View file

@ -15,9 +15,6 @@ from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7): if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7") raise SkipTest("F5 Ansible modules require Python >= 2.7")
from units.compat import unittest
from units.compat.mock import Mock
from units.compat.mock import patch
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
try: try:
@ -27,9 +24,15 @@ try:
from library.modules.bigip_gtm_wide_ip import ArgumentSpec from library.modules.bigip_gtm_wide_ip import ArgumentSpec
from library.modules.bigip_gtm_wide_ip import UntypedManager from library.modules.bigip_gtm_wide_ip import UntypedManager
from library.modules.bigip_gtm_wide_ip import TypedManager from library.modules.bigip_gtm_wide_ip import TypedManager
from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
from test.unit.modules.utils import set_module_args # In Ansible 2.8, Ansible changed import paths.
from test.units.compat import unittest
from test.units.compat.mock import Mock
from test.units.compat.mock import patch
from test.units.modules.utils import set_module_args
except ImportError: except ImportError:
try: try:
from ansible.modules.network.f5.bigip_gtm_wide_ip import ApiParameters from ansible.modules.network.f5.bigip_gtm_wide_ip import ApiParameters
@ -38,8 +41,14 @@ except ImportError:
from ansible.modules.network.f5.bigip_gtm_wide_ip import ArgumentSpec from ansible.modules.network.f5.bigip_gtm_wide_ip import ArgumentSpec
from ansible.modules.network.f5.bigip_gtm_wide_ip import UntypedManager from ansible.modules.network.f5.bigip_gtm_wide_ip import UntypedManager
from ansible.modules.network.f5.bigip_gtm_wide_ip import TypedManager from ansible.modules.network.f5.bigip_gtm_wide_ip import TypedManager
from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
# Ansible 2.8 imports
from units.compat import unittest
from units.compat.mock import Mock
from units.compat.mock import patch
from units.modules.utils import set_module_args from units.modules.utils import set_module_args
except ImportError: except ImportError:
raise SkipTest("F5 Ansible modules require the f5-sdk Python library") raise SkipTest("F5 Ansible modules require the f5-sdk Python library")
@ -121,6 +130,17 @@ class TestUntypedManager(unittest.TestCase):
def setUp(self): def setUp(self):
self.spec = ArgumentSpec() self.spec = ArgumentSpec()
try:
self.p1 = patch('library.modules.bigip_gtm_wide_ip.module_provisioned')
self.m1 = self.p1.start()
self.m1.return_value = True
except Exception:
self.p1 = patch('ansible.modules.network.f5.bigip_gtm_wide_ip.module_provisioned')
self.m1 = self.p1.start()
self.m1.return_value = True
def tearDown(self):
self.p1.stop()
def test_create_wideip(self, *args): def test_create_wideip(self, *args):
set_module_args(dict( set_module_args(dict(
@ -158,6 +178,17 @@ class TestTypedManager(unittest.TestCase):
def setUp(self): def setUp(self):
self.spec = ArgumentSpec() self.spec = ArgumentSpec()
try:
self.p1 = patch('library.modules.bigip_gtm_wide_ip.module_provisioned')
self.m1 = self.p1.start()
self.m1.return_value = True
except Exception:
self.p1 = patch('ansible.modules.network.f5.bigip_gtm_wide_ip.module_provisioned')
self.m1 = self.p1.start()
self.m1.return_value = True
def tearDown(self):
self.p1.stop()
def test_create_wideip(self, *args): def test_create_wideip(self, *args):
set_module_args(dict( set_module_args(dict(