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
# -*- 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)
from __future__ import absolute_import, division, print_function
@ -11,6 +11,7 @@ __metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_gtm_wide_ip
@ -104,9 +105,17 @@ options:
- You can use the same wildcard characters for aliases as you can for actual
wide IP names.
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
author:
- Tim Rupp (@caphrim007)
- Wojciech Wypior (@wojtek0806)
'''
EXAMPLES = r'''
@ -194,38 +203,38 @@ from ansible.module_utils.six import iteritems
from distutils.version import LooseVersion
try:
from library.module_utils.network.f5.bigip import HAS_F5SDK
from library.module_utils.network.f5.bigip import F5Client
from library.module_utils.network.f5.bigip import F5RestClient
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 cleanup_tokens
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
try:
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
except ImportError:
HAS_F5SDK = False
from library.module_utils.network.f5.common import transform_name
from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import fail_json
from library.module_utils.network.f5.common import is_valid_fqdn
from library.module_utils.network.f5.icontrol import tmos_version
from library.module_utils.network.f5.icontrol import module_provisioned
except ImportError:
from ansible.module_utils.network.f5.bigip import HAS_F5SDK
from ansible.module_utils.network.f5.bigip import F5Client
from ansible.module_utils.network.f5.bigip import F5RestClient
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 cleanup_tokens
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
try:
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
except ImportError:
HAS_F5SDK = False
from ansible.module_utils.network.f5.common import transform_name
from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import fail_json
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):
api_map = {
'poolLbMode': 'pool_lb_method',
'rules': 'irules',
'lastResortPool': 'last_resort_pool',
}
updatables = [
@ -236,6 +245,7 @@ class Parameters(AnsibleF5Parameters):
'enabled',
'disabled',
'aliases',
'last_resort_pool',
]
returnables = [
@ -245,6 +255,7 @@ class Parameters(AnsibleF5Parameters):
'pools',
'irules',
'aliases',
'last_resort_pool',
]
api_attributes = [
@ -254,6 +265,7 @@ class Parameters(AnsibleF5Parameters):
'pools',
'rules',
'aliases',
'lastResortPool',
]
@ -274,7 +286,7 @@ class ApiParameters(Parameters):
def pools(self):
result = []
if self._values['pools'] is None:
return None
return []
pools = sorted(self._values['pools'], key=lambda x: x['order'])
for item in pools:
pool = dict()
@ -288,8 +300,22 @@ class ApiParameters(Parameters):
result.append(pool)
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):
@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
def pool_lb_method(self):
if self._values['pool_lb_method'] is None:
@ -431,6 +457,14 @@ class ReportableChanges(Changes):
)
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):
def __init__(self, want, have=None):
@ -472,6 +506,15 @@ class Difference(object):
else:
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
def state(self):
if self.want.state == 'disabled' and self.have.enabled:
@ -516,6 +559,10 @@ class ModuleManager(object):
self.kwargs = kwargs
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():
manager = self.get_manager('untyped')
else:
@ -529,7 +576,7 @@ class ModuleManager(object):
return UntypedManager(**self.kwargs)
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'):
return True
else:
@ -575,13 +622,10 @@ class BaseManager(object):
result = dict()
state = self.want.state
try:
if state in ["present", "disabled"]:
changed = self.present()
elif state == "absent":
changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
if state in ["present", "disabled"]:
changed = self.present()
elif state == "absent":
changed = self.absent()
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
@ -646,42 +690,89 @@ class BaseManager(object):
class UntypedManager(BaseManager):
def exists(self):
return self.client.api.tm.gtm.wideips.wideip.exists(
name=self.want.name,
partition=self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}".format(
self.client.provider['server'],
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):
params = self.changes.api_params()
result = self.client.api.tm.gtm.wideips.wipeip.load(
name=self.want.name,
partition=self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}".format(
self.client.provider['server'],
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):
resource = self.client.api.tm.gtm.wideips.wideip.load(
name=self.want.name,
partition=self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
result = resource.attrs
return ApiParameters(params=result)
resp = self.client.api.get(uri)
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):
params = self.changes.api_params()
self.client.api.tm.gtm.wideips.wideip.create(
name=self.want.name,
partition=self.want.partition,
**params
params['name'] = self.want.name
params['partition'] = self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/".format(
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):
result = self.client.api.tm.gtm.wideips.wideip.load(
name=self.want.name,
partition=self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
if result:
result.delete()
response = self.client.api.delete(uri)
if response.status == 200:
return True
raise F5ModuleError(response.content)
class TypedManager(BaseManager):
@ -692,69 +783,96 @@ class TypedManager(BaseManager):
"The 'type' option is required for BIG-IP instances "
"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):
wideips = self.client.api.tm.gtm.wideips
collection = getattr(wideips, self.collection)
resource = getattr(collection, self.want.type)
result = resource.exists(
name=self.want.name,
partition=self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/{3}".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.type,
transform_name(self.want.partition, self.want.name)
)
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):
params = self.changes.api_params()
wideips = self.client.api.tm.gtm.wideips
collection = getattr(wideips, self.collection)
resource = getattr(collection, self.want.type)
result = resource.load(
name=self.want.name,
partition=self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/{3}".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.type,
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):
wideips = self.client.api.tm.gtm.wideips
collection = getattr(wideips, self.collection)
resource = getattr(collection, self.want.type)
result = resource.load(
name=self.want.name,
partition=self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/{3}".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.type,
transform_name(self.want.partition, self.want.name)
)
result = result.attrs
return ApiParameters(params=result)
resp = self.client.api.get(uri)
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):
params = self.changes.api_params()
wideips = self.client.api.tm.gtm.wideips
collection = getattr(wideips, self.collection)
resource = getattr(collection, self.want.type)
resource.create(
name=self.want.name,
partition=self.want.partition,
**params
params['name'] = self.want.name
params['partition'] = self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.type
)
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):
wideips = self.client.api.tm.gtm.wideips
collection = getattr(wideips, self.collection)
resource = getattr(collection, self.want.type)
result = resource.load(
name=self.want.name,
partition=self.want.partition
uri = "https://{0}:{1}/mgmt/tm/gtm/wideip/{2}/{3}".format(
self.client.provider['server'],
self.client.provider['server_port'],
self.want.type,
transform_name(self.want.partition, self.want.name)
)
if result:
result.delete()
response = self.client.api.delete(uri)
if response.status == 200:
return True
raise F5ModuleError(response.content)
class ArgumentSpec(object):
@ -800,7 +918,8 @@ class ArgumentSpec(object):
),
aliases=dict(
type='list'
)
),
last_resort_pool=dict(),
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
@ -812,20 +931,19 @@ def main():
module = AnsibleModule(
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:
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
module.exit_json(**results)
except F5ModuleError as e:
exit_json(module, results, client)
except F5ModuleError as ex:
cleanup_tokens(client)
module.fail_json(msg=str(e))
fail_json(module, ex, client)
if __name__ == '__main__':

View file

@ -15,9 +15,6 @@ from nose.plugins.skip import SkipTest
if sys.version_info < (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
try:
@ -27,9 +24,15 @@ try:
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 TypedManager
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:
try:
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 UntypedManager
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 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
except ImportError:
raise SkipTest("F5 Ansible modules require the f5-sdk Python library")
@ -121,6 +130,17 @@ class TestUntypedManager(unittest.TestCase):
def setUp(self):
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):
set_module_args(dict(
@ -158,6 +178,17 @@ class TestTypedManager(unittest.TestCase):
def setUp(self):
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):
set_module_args(dict(