Various F5 related fixes for traceback raising (#34820)

The main purpose of this patch is to do the refactor that
supports replacing tracebacks with fail_json. Additionally, the
following was done.

* Removed re-def of cleanup_tokens.
* Changed parameter args to be keywords.
* Changed imports to include new module_util locations.
* Imports also include developing (sideband) module_util locations.
* Changed to using F5Client and plain AnsibleModule to prevent tracebacks caused by missing libraries.
* Removed init and update methods from most Parameter classes (optimization) as its now included in module_utils.
* Changed module and module param references to take into account the new self.module arg.
* Minor bug fixes made during this refactor.
This commit is contained in:
Tim Rupp 2018-01-12 14:43:35 -08:00 committed by GitHub
commit 0e4e7de000
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
23 changed files with 1149 additions and 1388 deletions

View file

@ -88,12 +88,17 @@ options:
- Device partition to manage resources on.
default: Common
version_added: 2.5
state:
description:
- When C(present), ensures that the monitor exists.
- When C(absent), ensures the monitor is removed.
default: present
choices:
- present
- absent
version_added: 2.5
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
- Requires BIG-IP software version >= 12
requirements:
- f5-sdk >= 2.2.3
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
@ -159,7 +164,38 @@ time_until_up:
sample: 2
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
HAS_DEVEL_IMPORTS = False
try:
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
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.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 fqdn_name
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
try:
import netaddr
@ -167,18 +203,6 @@ try:
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 = {
@ -202,36 +226,6 @@ class Parameters(AnsibleF5Parameters):
'target_username', 'target_password'
]
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 _fqdn_name(self, value):
if value is not None and not value.startswith('/'):
return '/{0}/{1}'.format(self.partition, value)
@ -247,16 +241,6 @@ class Parameters(AnsibleF5Parameters):
pass
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
@property
def destination(self):
if self.ip is None and self.port is None:
@ -409,10 +393,11 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(self.client.module.params)
self.want = Parameters(params=self.module.params)
self.changes = Changes()
def _set_changed_options(self):
@ -421,7 +406,7 @@ class ModuleManager(object):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Changes(changed)
self.changes = Changes(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -437,7 +422,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = Changes(changed)
self.changes = Changes(params=changed)
return True
return False
@ -448,7 +433,7 @@ class ModuleManager(object):
if self.have:
warnings += self.have._values.get('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -492,7 +477,7 @@ class ModuleManager(object):
self.want.update({'port': '*'})
if self.want.send is None:
self.want.update({'send': 'GET /\r\n'})
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
return True
@ -507,7 +492,7 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
return True
@ -518,7 +503,7 @@ class ModuleManager(object):
return False
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -531,7 +516,7 @@ class ModuleManager(object):
partition=self.want.partition
)
result = resource.attrs
return Parameters(result)
return Parameters(params=result)
def exists(self):
result = self.client.api.tm.ltm.monitor.https.http.exists(
@ -568,7 +553,7 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(required=True),
parent=dict(default='/Common/http'),
send=dict(),
@ -581,48 +566,41 @@ class ArgumentSpec(object):
time_until_up=dict(type='int'),
target_username=dict(),
target_password=dict(no_log=True),
# Deprecated params
parent_partition=dict(
removed_in_version='2.4'
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
def cleanup_tokens(client):
try:
resource = client.api.shared.authz.tokens_s.token.load(
name=client.api.icrs.token
)
resource.delete()
except Exception:
pass
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
if not HAS_NETADDR:
module.fail_json(msg="The python netaddr module is required")
try:
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
if not HAS_NETADDR:
raise F5ModuleError("The python netaddr module is required")
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
client.module.exit_json(**results)
except F5ModuleError as e:
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
client.module.fail_json(msg=str(e))
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -86,14 +86,18 @@ options:
partition:
description:
- Device partition to manage resources on.
required: False
default: 'Common'
default: Common
state:
description:
- When C(present), ensures that the monitor exists.
- When C(absent), ensures the monitor is removed.
default: present
choices:
- present
- absent
version_added: 2.5
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
- Requires BIG-IP software version >= 12
requirements:
- f5-sdk >= 2.2.3
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
@ -148,7 +152,38 @@ time_until_up:
sample: 2
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
HAS_DEVEL_IMPORTS = False
try:
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
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.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 fqdn_name
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
try:
import netaddr
@ -156,18 +191,6 @@ try:
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 = {
@ -191,36 +214,6 @@ class Parameters(AnsibleF5Parameters):
'target_username', 'target_password'
]
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 _fqdn_name(self, value):
if value is not None and not value.startswith('/'):
return '/{0}/{1}'.format(self.partition, value)
@ -236,16 +229,6 @@ class Parameters(AnsibleF5Parameters):
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
@property
def username(self):
return self._values['target_username']
@ -326,6 +309,10 @@ class Parameters(AnsibleF5Parameters):
return 'https'
class Changes(Parameters):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
@ -394,11 +381,12 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters()
self.want = Parameters(params=self.module.params)
self.changes = Changes()
def _set_changed_options(self):
changed = {}
@ -406,7 +394,7 @@ class ModuleManager(object):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -419,7 +407,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
return True
return False
@ -430,7 +418,7 @@ class ModuleManager(object):
if self.have:
warnings += self.have._values.get('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -474,7 +462,7 @@ class ModuleManager(object):
self.want.update({'port': '*'})
if self.want.send is None:
self.want.update({'send': 'GET /\r\n'})
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
return True
@ -489,7 +477,7 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
return True
@ -500,7 +488,7 @@ class ModuleManager(object):
return False
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -513,7 +501,7 @@ class ModuleManager(object):
partition=self.want.partition
)
result = resource.attrs
return Parameters(result)
return Parameters(params=result)
def exists(self):
result = self.client.api.tm.ltm.monitor.https_s.https.exists(
@ -550,7 +538,7 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(required=True),
parent=dict(default='/Common/https'),
send=dict(),
@ -562,44 +550,42 @@ class ArgumentSpec(object):
timeout=dict(type='int'),
time_until_up=dict(type='int'),
target_username=dict(),
target_password=dict(no_log=True)
target_password=dict(no_log=True),
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
def cleanup_tokens(client):
try:
resource = client.api.shared.authz.tokens_s.token.load(
name=client.api.icrs.token
)
resource.delete()
except Exception:
pass
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
if not HAS_NETADDR:
module.fail_json(msg="The python netaddr module is required")
try:
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
if not HAS_NETADDR:
raise F5ModuleError("The python netaddr module is required")
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
client.module.exit_json(**results)
except F5ModuleError as e:
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
client.module.fail_json(msg=str(e))
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -113,16 +113,21 @@ options:
description:
- Device partition to manage resources on.
default: Common
state:
description:
- When C(present), ensures that the monitor exists.
- When C(absent), ensures the monitor is removed.
default: present
choices:
- present
- absent
version_added: 2.5
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
- Requires BIG-IP software version >= 12
- This module does not support the C(variables) option because this option
is broken in the REST API and does not function correctly in C(tmsh); for
example you cannot remove user-defined params. Therefore, there is no way
to automatically configure it.
requirements:
- f5-sdk >= 2.2.3
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
@ -216,19 +221,38 @@ disk_threshold:
sample: 34
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
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
HAS_DEVEL_IMPORTS = False
try:
from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
HAS_F5SDK = False
# Upstream Ansible
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.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 fqdn_name
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
class Parameters(AnsibleF5Parameters):
@ -262,36 +286,6 @@ class Parameters(AnsibleF5Parameters):
'memory_threshold', 'disk_coefficient', 'disk_threshold'
]
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 _fqdn_name(self, value):
if value is not None and not value.startswith('/'):
return '/{0}/{1}'.format(self.partition, value)
@ -307,16 +301,6 @@ class Parameters(AnsibleF5Parameters):
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
@property
def interval(self):
if self._values['interval'] is None:
@ -392,6 +376,10 @@ class Parameters(AnsibleF5Parameters):
return 'snmp_dca'
class Changes(Parameters):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
@ -450,11 +438,12 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters()
self.want = Parameters(params=self.module.params)
self.changes = Changes()
def _set_changed_options(self):
changed = {}
@ -462,7 +451,7 @@ class ModuleManager(object):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -475,7 +464,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
return True
return False
@ -486,7 +475,7 @@ class ModuleManager(object):
if self.have:
warnings += self.have._values.get('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -544,7 +533,7 @@ class ModuleManager(object):
if self.want.disk_threshold is None:
self.want.update({'disk_threshold': '90'})
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
return True
@ -559,7 +548,7 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
return True
@ -570,7 +559,7 @@ class ModuleManager(object):
return False
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -583,7 +572,7 @@ class ModuleManager(object):
partition=self.want.partition
)
result = resource.attrs
return Parameters(result)
return Parameters(params=result)
def exists(self):
result = self.client.api.tm.ltm.monitor.snmp_dcas.snmp_dca.exists(
@ -620,7 +609,7 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(required=True),
description=dict(),
parent=dict(default='/Common/snmp_dca'),
@ -638,41 +627,40 @@ class ArgumentSpec(object):
memory_coefficient=dict(),
memory_threshold=dict(type='int'),
disk_coefficient=dict(),
disk_threshold=dict(type='int')
disk_threshold=dict(type='int'),
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
def cleanup_tokens(client):
try:
resource = client.api.shared.authz.tokens_s.token.load(
name=client.api.icrs.token
)
resource.delete()
except Exception:
pass
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
try:
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
client.module.exit_json(**results)
except F5ModuleError as e:
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
client.module.fail_json(msg=str(e))
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -91,12 +91,17 @@ options:
- Device partition to manage resources on.
default: Common
version_added: 2.5
state:
description:
- When C(present), ensures that the monitor exists.
- When C(absent), ensures the monitor is removed.
default: present
choices:
- present
- absent
version_added: 2.5
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
- Requires BIG-IP software version >= 12
requirements:
- f5-sdk >= 2.2.3
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
@ -168,7 +173,38 @@ time_until_up:
sample: 2
'''
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
HAS_DEVEL_IMPORTS = False
try:
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
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.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 fqdn_name
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
try:
import netaddr
@ -176,18 +212,6 @@ try:
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 = {
@ -210,36 +234,6 @@ class Parameters(AnsibleF5Parameters):
'destination', 'send', 'receive', 'interval', 'timeout', 'time_until_up'
]
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 _fqdn_name(self, value):
if value is not None and not value.startswith('/'):
return '/{0}/{1}'.format(self.partition, value)
@ -334,6 +328,10 @@ class Parameters(AnsibleF5Parameters):
return 'tcp'
class Changes(Parameters):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
@ -402,11 +400,12 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters()
self.want = Parameters(params=self.module.params)
self.changes = Changes()
def _set_changed_options(self):
changed = {}
@ -414,7 +413,7 @@ class ModuleManager(object):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -427,7 +426,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
return True
return False
@ -438,7 +437,7 @@ class ModuleManager(object):
if self.have:
warnings += self.have._values.get('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -471,7 +470,7 @@ class ModuleManager(object):
def create(self):
self._set_changed_options()
self._set_default_creation_values()
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
return True
@ -486,7 +485,7 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
return True
@ -497,7 +496,7 @@ class ModuleManager(object):
return False
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -522,7 +521,7 @@ class ModuleManager(object):
partition=self.want.partition
)
result = resource.attrs
return Parameters(result)
return Parameters(params=result)
def exists(self):
result = self.client.api.tm.ltm.monitor.tcps.tcp.exists(
@ -559,7 +558,7 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(required=True),
parent=dict(default='/Common/tcp'),
send=dict(),
@ -568,48 +567,46 @@ class ArgumentSpec(object):
port=dict(type='int'),
interval=dict(type='int'),
timeout=dict(type='int'),
time_until_up=dict(type='int')
time_until_up=dict(type='int'),
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
self.mutually_exclusive = [
['parent', 'parent_partition']
]
def cleanup_tokens(client):
try:
resource = client.api.shared.authz.tokens_s.token.load(
name=client.api.icrs.token
)
resource.delete()
except Exception:
pass
def main():
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name,
mutually_exclusive=spec.mutually_exclusive
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
if not HAS_NETADDR:
module.fail_json(msg="The python netaddr module is required")
try:
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
if not HAS_NETADDR:
raise F5ModuleError("The python netaddr module is required")
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
client.module.exit_json(**results)
except F5ModuleError as e:
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
client.module.fail_json(msg=str(e))
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -65,12 +65,17 @@ options:
- Device partition to manage resources on.
default: Common
version_added: 2.5
state:
description:
- When C(present), ensures that the monitor exists.
- When C(absent), ensures the monitor is removed.
default: present
choices:
- present
- absent
version_added: 2.5
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
- Requires BIG-IP software version >= 12
requirements:
- f5-sdk >= 2.2.3
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
@ -127,24 +132,45 @@ time_until_up:
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
HAS_DEVEL_IMPORTS = False
try:
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
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.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 fqdn_name
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
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 = {
@ -164,36 +190,6 @@ class Parameters(AnsibleF5Parameters):
'ip', 'interval', 'timeout', 'time_until_up'
]
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 _fqdn_name(self, value):
if value is not None and not value.startswith('/'):
return '/{0}/{1}'.format(self.partition, value)
@ -209,16 +205,6 @@ class Parameters(AnsibleF5Parameters):
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
@property
def interval(self):
if self._values['interval'] is None:
@ -279,6 +265,10 @@ class Parameters(AnsibleF5Parameters):
return 'tcp_echo'
class Changes(Parameters):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
@ -337,11 +327,12 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters()
self.want = Parameters(params=self.module.params)
self.changes = Changes()
def _set_changed_options(self):
changed = {}
@ -349,7 +340,7 @@ class ModuleManager(object):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -362,7 +353,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
return True
return False
@ -373,7 +364,7 @@ class ModuleManager(object):
if self.have:
warnings += self.have._values.get('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -413,7 +404,7 @@ class ModuleManager(object):
self.want.update({'time_until_up': 0})
if self.want.ip is None:
self.want.update({'ip': '*'})
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
return True
@ -428,7 +419,7 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
return True
@ -439,7 +430,7 @@ class ModuleManager(object):
return False
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -452,7 +443,7 @@ class ModuleManager(object):
partition=self.want.partition
)
result = resource.attrs
return Parameters(result)
return Parameters(params=result)
def exists(self):
result = self.client.api.tm.ltm.monitor.tcp_echos.tcp_echo.exists(
@ -489,50 +480,48 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(required=True),
parent=dict(default='/Common/tcp_echo'),
ip=dict(),
interval=dict(type='int'),
timeout=dict(type='int'),
time_until_up=dict(type='int')
time_until_up=dict(type='int'),
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
def cleanup_tokens(client):
try:
resource = client.api.shared.authz.tokens_s.token.load(
name=client.api.icrs.token
)
resource.delete()
except Exception:
pass
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
if not HAS_NETADDR:
module.fail_json(msg="The python netaddr module is required")
try:
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
if not HAS_NETADDR:
raise F5ModuleError("The python netaddr module is required")
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
client.module.exit_json(**results)
except F5ModuleError as e:
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
client.module.fail_json(msg=str(e))
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -72,12 +72,17 @@ options:
- Device partition to manage resources on.
default: Common
version_added: 2.5
state:
description:
- When C(present), ensures that the monitor exists.
- When C(absent), ensures the monitor is removed.
default: present
choices:
- present
- absent
version_added: 2.5
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
- Requires BIG-IP software version >= 12
requirements:
- f5-sdk >= 2.2.3
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
@ -143,24 +148,45 @@ time_until_up:
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
HAS_DEVEL_IMPORTS = False
try:
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
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.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 fqdn_name
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
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 = {
@ -183,36 +209,6 @@ class Parameters(AnsibleF5Parameters):
'destination', 'send', 'receive', 'interval', 'timeout', 'time_until_up'
]
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 _fqdn_name(self, value):
if value is not None and not value.startswith('/'):
return '/{0}/{1}'.format(self.partition, value)
@ -228,16 +224,6 @@ class Parameters(AnsibleF5Parameters):
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
@property
def destination(self):
if self.ip is None and self.port is None:
@ -314,6 +300,10 @@ class Parameters(AnsibleF5Parameters):
return 'tcp_half_open'
class Changes(Parameters):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
@ -382,11 +372,12 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters()
self.want = Parameters(params=self.module.params)
self.changes = Changes()
def _set_changed_options(self):
changed = {}
@ -394,7 +385,7 @@ class ModuleManager(object):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -407,7 +398,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = Parameters(changed)
self.changes = Changes(params=changed)
return True
return False
@ -418,7 +409,7 @@ class ModuleManager(object):
if self.have:
warnings += self.have._values.get('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -460,7 +451,7 @@ class ModuleManager(object):
self.want.update({'ip': '*'})
if self.want.port is None:
self.want.update({'port': '*'})
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
return True
@ -475,7 +466,7 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
return True
@ -486,7 +477,7 @@ class ModuleManager(object):
return False
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -499,7 +490,7 @@ class ModuleManager(object):
partition=self.want.partition
)
result = resource.attrs
return Parameters(result)
return Parameters(params=result)
def exists(self):
result = self.client.api.tm.ltm.monitor.tcp_half_opens.tcp_half_open.exists(
@ -536,51 +527,49 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(required=True),
parent=dict(default='/Common/tcp_half_open'),
ip=dict(),
port=dict(type='int'),
interval=dict(type='int'),
timeout=dict(type='int'),
time_until_up=dict(type='int')
time_until_up=dict(type='int'),
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
def cleanup_tokens(client):
try:
resource = client.api.shared.authz.tokens_s.token.load(
name=client.api.icrs.token
)
resource.delete()
except Exception:
pass
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
if not HAS_NETADDR:
module.fail_json(msg="The python netaddr module is required")
try:
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
if not HAS_NETADDR:
raise F5ModuleError("The python netaddr module is required")
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
client.module.exit_json(**results)
except F5ModuleError as e:
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
client.module.fail_json(msg=str(e))
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -82,12 +82,17 @@ options:
- Device partition to manage resources on.
default: Common
version_added: 2.5
state:
description:
- When C(present), ensures that the monitor exists.
- When C(absent), ensures the monitor is removed.
default: present
choices:
- present
- absent
version_added: 2.5
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
- Requires BIG-IP software version >= 12
requirements:
- f5-sdk >= 2.2.3
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
@ -144,24 +149,45 @@ time_until_up:
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
HAS_DEVEL_IMPORTS = False
try:
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
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.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 fqdn_name
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
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 = {
@ -184,36 +210,6 @@ class Parameters(AnsibleF5Parameters):
'destination', 'send', 'receive', 'interval', 'timeout', 'time_until_up'
]
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 _fqdn_name(self, value):
if value is not None and not value.startswith('/'):
return '/{0}/{1}'.format(self.partition, value)
@ -229,16 +225,6 @@ class Parameters(AnsibleF5Parameters):
pass
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
@property
def destination(self):
if self.ip is None and self.port is None:
@ -387,10 +373,11 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(self.client.module.params)
self.want = Parameters(params=self.module.params)
self.changes = Changes()
def _set_changed_options(self):
@ -399,7 +386,7 @@ class ModuleManager(object):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Changes(changed)
self.changes = Changes(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -415,7 +402,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = Changes(changed)
self.changes = Changes(params=changed)
return True
return False
@ -447,7 +434,7 @@ class ModuleManager(object):
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -472,7 +459,7 @@ class ModuleManager(object):
self.want.update({'port': '*'})
if self.want.send is None:
self.want.update({'send': 'default send string'})
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
return True
@ -488,13 +475,13 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
return True
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -536,13 +523,13 @@ class ModuleManager(object):
partition=self.want.partition
)
result = resource.attrs
return Parameters(result)
return Parameters(params=result)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(required=True),
parent=dict(default='/Common/udp'),
send=dict(),
@ -553,48 +540,41 @@ class ArgumentSpec(object):
interval=dict(type='int'),
timeout=dict(type='int'),
time_until_up=dict(type='int'),
# Deprecated params
parent_partition=dict(
removed_in_version='2.4'
state=dict(
default='present',
choices=['present', 'absent']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
def cleanup_tokens(client):
try:
resource = client.api.shared.authz.tokens_s.token.load(
name=client.api.icrs.token
)
resource.delete()
except Exception:
pass
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
if not HAS_NETADDR:
module.fail_json(msg="The python netaddr module is required")
try:
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
if not HAS_NETADDR:
raise F5ModuleError("The python netaddr module is required")
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
client.module.exit_json(**results)
except F5ModuleError as e:
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
client.module.fail_json(msg=str(e))
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -96,13 +96,9 @@ options:
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)
'''
@ -217,24 +213,45 @@ state:
import re
import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
HAS_DEVEL_IMPORTS = False
try:
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
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.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 fqdn_name
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
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 = {
@ -264,36 +281,6 @@ class Parameters(AnsibleF5Parameters):
'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:
@ -304,16 +291,6 @@ class Parameters(AnsibleF5Parameters):
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)
@ -488,10 +465,11 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(self.client.module.params)
self.want = Parameters(params=self.module.params)
self.changes = Changes()
def _set_changed_options(self):
@ -500,7 +478,7 @@ class ModuleManager(object):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Changes(changed)
self.changes = Changes(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -516,7 +494,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = Changes(changed)
self.changes = Changes(params=changed)
return True
return False
@ -527,7 +505,7 @@ class ModuleManager(object):
if self.have:
warnings += self.have._values.get('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -605,7 +583,7 @@ class ModuleManager(object):
self._check_required_creation_vars()
self._munge_creation_state_for_device()
self._set_changed_options()
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
if not self.exists():
@ -626,7 +604,7 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
if self.want.state == 'offline':
@ -639,7 +617,7 @@ class ModuleManager(object):
return False
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -652,7 +630,7 @@ class ModuleManager(object):
partition=self.want.partition
)
result = resource.attrs
return Parameters(result)
return Parameters(params=result)
def exists(self):
result = self.client.api.tm.ltm.nodes.node.exists(
@ -709,7 +687,7 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(required=True),
address=dict(
aliases=['host', 'ip']
@ -728,31 +706,38 @@ class ArgumentSpec(object):
state=dict(
choices=['absent', 'present', 'enabled', 'disabled', 'offline'],
default='present'
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
if not HAS_NETADDR:
module.fail_json(msg="The python netaddr module is required")
try:
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
if not HAS_NETADDR:
raise F5ModuleError("The python netaddr module is required")
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
client.module.exit_json(**results)
except F5ModuleError as e:
client.module.fail_json(msg=str(e))
cleanup_tokens(client)
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -36,11 +36,7 @@ options:
- present
- absent
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
- Requires BIG-IP software version >= 12
requirements:
- f5-sdk >= 2.2.3
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
@ -105,17 +101,37 @@ description:
sample: Example partition
'''
from ansible.module_utils.f5_utils import AnsibleF5Client
from ansible.module_utils.f5_utils import AnsibleF5Parameters
from ansible.module_utils.f5_utils import F5ModuleError
from ansible.module_utils.six import iteritems
from collections import defaultdict
from ansible.module_utils.basic import AnsibleModule
HAS_DEVEL_IMPORTS = False
try:
from ansible.module_utils.f5_utils import HAS_F5SDK
from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
HAS_F5SDK = False
# Upstream Ansible
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.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 fqdn_name
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
class Parameters(AnsibleF5Parameters):
@ -135,36 +151,6 @@ class Parameters(AnsibleF5Parameters):
'description', 'route_domain'
]
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:
@ -175,16 +161,6 @@ class Parameters(AnsibleF5Parameters):
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
@property
def partition(self):
# Cannot create a partition in a partition, so nullify this
@ -197,6 +173,10 @@ class Parameters(AnsibleF5Parameters):
return int(self._values['route_domain'])
class Changes(Parameters):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
@ -221,11 +201,12 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(self.client.module.params)
self.changes = Parameters()
self.want = Parameters(params=self.module.params)
self.changes = Changes()
def _set_changed_options(self):
changed = {}
@ -233,7 +214,7 @@ class ModuleManager(object):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = Parameters(changed)
self.changes = Parameters(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -246,7 +227,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = Parameters(changed)
self.changes = Parameters(params=changed)
return True
return False
@ -275,7 +256,7 @@ class ModuleManager(object):
return self.create()
def create(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
if not self.exists():
@ -292,7 +273,7 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
return True
@ -303,7 +284,7 @@ class ModuleManager(object):
return False
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -315,7 +296,7 @@ class ModuleManager(object):
name=self.want.name
)
result = resource.attrs
return Parameters(result)
return Parameters(params=result)
def exists(self):
result = self.client.api.tm.auth.partitions.partition.exists(
@ -348,44 +329,39 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(required=True),
description=dict(),
route_domain=dict(type='int'),
state=dict(
choices=['absent', 'present'],
default='present'
)
)
self.f5_product_name = 'bigip'
def cleanup_tokens(client):
try:
resource = client.api.shared.authz.tokens_s.token.load(
name=client.api.icrs.token
)
resource.delete()
except Exception:
pass
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
try:
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
client.module.exit_json(**results)
except F5ModuleError as e:
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
client.module.fail_json(msg=str(e))
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -72,11 +72,6 @@ options:
description:
- Device partition to manage resources on.
default: Common
notes:
- Requires the f5-sdk Python package on the host. This is as easy as
pip install f5-sdk
requirements:
- f5-sdk
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
@ -166,54 +161,50 @@ rules:
type: list
sample: ['/Common/rule1', '/Common/rule2']
'''
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
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
from distutils.version import LooseVersion
HAS_DEVEL_IMPORTS = False
try:
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
# Upstream Ansible
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.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 fqdn_name
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
try:
from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError
from f5.sdk_exception import NonExtantPolicyRule
except ImportError:
HAS_F5SDK = False
class Parameters(AnsibleF5Parameters):
def __init__(self, params=None):
self._values = defaultdict(lambda: None)
if params:
self.update(params=params)
self._values['__warning'] = []
self._values['__deprecated'] = []
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 = {}
for returnable in self.returnables:
@ -221,16 +212,6 @@ class Parameters(AnsibleF5Parameters):
result = self._filter_params(result)
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
@property
def strategy(self):
if self._values['strategy'] is None:
@ -261,9 +242,7 @@ class Parameters(AnsibleF5Parameters):
return self._get_custom_strategy_name()
def _get_builtin_strategy(self, strategy):
return '/{0}/{1}-match'.format(
self.partition, strategy
)
return '/Common/{0}-match'.format(strategy)
def _get_custom_strategy_name(self):
strategy = self._values['strategy']
@ -314,9 +293,11 @@ class ComplexParameters(Parameters):
class BaseManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.have = None
self.want = Parameters(params=self.module.params)
def _announce_deprecations(self):
warnings = []
@ -325,7 +306,7 @@ class BaseManager(object):
if self.have:
warnings += self.have._values.get('__deprecated', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -337,7 +318,7 @@ class BaseManager(object):
if self.have:
warnings += self.have._values.get('__warning', [])
for warning in warnings:
self.client.module.warn(warning['msg'])
self.module.warn(warning['msg'])
def present(self):
if self.exists():
@ -386,9 +367,9 @@ class BaseManager(object):
class SimpleManager(BaseManager):
def __init__(self, client):
super(SimpleManager, self).__init__(client)
self.want = SimpleParameters(self.client.module.params)
def __init__(self, *args, **kwargs):
super(SimpleManager, self).__init__(**kwargs)
self.want = SimpleParameters(params=self.module.params)
self.have = SimpleParameters()
self.changes = SimpleChanges()
@ -398,7 +379,7 @@ class SimpleManager(BaseManager):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = SimpleChanges(changed)
self.changes = SimpleChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -411,7 +392,7 @@ class SimpleManager(BaseManager):
else:
changed[k] = change
if changed:
self.changes = SimpleChanges(changed)
self.changes = SimpleChanges(params=changed)
return True
return False
@ -445,7 +426,7 @@ class SimpleManager(BaseManager):
partition=self.want.partition
)
rules = self._get_rule_names(resource)
result = SimpleParameters(resource.attrs)
result = SimpleParameters(params=resource.attrs)
result.update(dict(rules=rules))
return result
@ -470,7 +451,7 @@ class SimpleManager(BaseManager):
def create(self):
self._validate_creation_parameters()
self._set_changed_options()
if self.client.check_mode:
if self.module.check_mode:
return True
self.create_on_device()
return True
@ -491,7 +472,7 @@ class SimpleManager(BaseManager):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
self.update_on_device()
return True
@ -503,7 +484,7 @@ class SimpleManager(BaseManager):
return changed
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
@ -519,9 +500,9 @@ class SimpleManager(BaseManager):
class ComplexManager(BaseManager):
def __init__(self, client):
super(ComplexManager, self).__init__(client)
self.want = ComplexParameters(self.client.module.params)
def __init__(self, *args, **kwargs):
super(ComplexManager, self).__init__(**kwargs)
self.want = ComplexParameters(params=self.module.params)
self.have = ComplexParameters()
self.changes = ComplexChanges()
@ -531,7 +512,7 @@ class ComplexManager(BaseManager):
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = ComplexChanges(changed)
self.changes = ComplexChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
@ -544,7 +525,7 @@ class ComplexManager(BaseManager):
else:
changed[k] = change
if changed:
self.changes = ComplexChanges(changed)
self.changes = ComplexChanges(params=changed)
return True
return False
@ -595,7 +576,7 @@ class ComplexManager(BaseManager):
return changed
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
self.remove_from_device()
if self.draft_exists() or self.policy_exists():
@ -631,7 +612,7 @@ class ComplexManager(BaseManager):
)
rules = self._get_rule_names(resource)
result = ComplexParameters(resource.attrs)
result = ComplexParameters(params=resource.attrs)
result.update(dict(rules=rules))
return result
@ -697,7 +678,7 @@ class ComplexManager(BaseManager):
self._validate_creation_parameters()
self._set_changed_options()
if self.client.check_mode:
if self.module.check_mode:
return True
if not self.draft_exists():
@ -716,7 +697,7 @@ class ComplexManager(BaseManager):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
if not self.draft_exists():
@ -787,8 +768,10 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.kwargs = kwargs
def exec_module(self):
if self.version_is_less_than_12():
@ -799,9 +782,9 @@ class ModuleManager(object):
def get_manager(self, type):
if type == 'simple':
return SimpleManager(self.client)
return SimpleManager(**self.kwargs)
elif type == 'complex':
return ComplexManager(self.client)
return ComplexManager(**self.kwargs)
def version_is_less_than_12(self):
version = self.client.api.tmos_version
@ -814,7 +797,7 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
name=dict(
required=True
),
@ -824,32 +807,38 @@ class ArgumentSpec(object):
choices=['first', 'all', 'best']
),
state=dict(
required=False,
default='present',
choices=['absent', 'present', 'draft']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
try:
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
client.module.exit_json(**results)
except F5ModuleError as e:
client.module.fail_json(msg=str(e))
cleanup_tokens(client)
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
module.fail_json(msg=str(ex))
if __name__ == '__main__':

View file

@ -93,12 +93,8 @@ options:
description:
- Device partition to manage resources on.
default: Common
notes:
- Requires the f5-sdk Python package on the host. This is as easy as pip
install f5-sdk.
extends_documentation_fragment: f5
requirements:
- f5-sdk >= 3.0.0
- BIG-IP >= v12.1.0
author:
- Tim Rupp (@caphrim007)
@ -194,18 +190,39 @@ description:
sample: My rule
'''
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.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.six import iteritems
from collections import defaultdict
HAS_DEVEL_IMPORTS = False
try:
from ansible.module_utils.f5_utils import iControlUnexpectedHTTPError
# Sideband repository used for dev
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.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 fqdn_name
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
HAS_DEVEL_IMPORTS = True
except ImportError:
HAS_F5SDK = False
# Upstream Ansible
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.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 fqdn_name
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
class Parameters(AnsibleF5Parameters):
@ -221,45 +238,6 @@ class Parameters(AnsibleF5Parameters):
'actions', 'conditions', 'description'
]
def __init__(self, params=None):
self._values = defaultdict(lambda: None)
if params:
self.update(params=params)
self._values['__warnings'] = []
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 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)
@ -613,9 +591,10 @@ class Difference(object):
class ModuleManager(object):
def __init__(self, client):
self.client = client
self.want = ModuleParameters(params=self.client.module.params)
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.want = ModuleParameters(params=self.module.params)
self.have = ApiParameters()
self.changes = UsableChanges()
@ -633,7 +612,7 @@ class ModuleManager(object):
else:
changed[k] = change
if changed:
self.changes = UsableChanges(changed)
self.changes = UsableChanges(params=changed)
return True
return False
@ -656,7 +635,7 @@ class ModuleManager(object):
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
reportable = ReportableChanges(self.changes.to_return())
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
@ -666,7 +645,7 @@ class ModuleManager(object):
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
self.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
@ -722,7 +701,7 @@ class ModuleManager(object):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.client.check_mode:
if self.module.check_mode:
return True
if self.draft_exists():
redraft = True
@ -735,7 +714,7 @@ class ModuleManager(object):
return True
def remove(self):
if self.client.check_mode:
if self.module.check_mode:
return True
if self.draft_exists():
redraft = True
@ -751,7 +730,7 @@ class ModuleManager(object):
def create(self):
self.should_update()
if self.client.check_mode:
if self.module.check_mode:
return True
if self.draft_exists():
redraft = True
@ -824,7 +803,7 @@ class ModuleManager(object):
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
self.argument_spec = dict(
argument_spec = dict(
description=dict(),
actions=dict(
type='list',
@ -860,40 +839,39 @@ class ArgumentSpec(object):
),
name=dict(required=True),
policy=dict(required=True),
state=dict(
default='present',
choices=['absent', 'present']
),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
)
)
self.f5_product_name = 'bigip'
def cleanup_tokens(client):
try:
resource = client.api.shared.authz.tokens_s.token.load(
name=client.api.icrs.token
)
resource.delete()
except Exception:
pass
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
if not HAS_F5SDK:
raise F5ModuleError("The python f5-sdk module is required")
spec = ArgumentSpec()
client = AnsibleF5Client(
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
f5_product_name=spec.f5_product_name
supports_check_mode=spec.supports_check_mode
)
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required")
try:
mm = ModuleManager(client)
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
client.module.exit_json(**results)
except F5ModuleError as e:
module.exit_json(**results)
except F5ModuleError as ex:
cleanup_tokens(client)
client.module.fail_json(msg=str(e))
module.fail_json(msg=str(ex))
if __name__ == '__main__':