Removes f5-sdk from bigip_ssl_key module (#48019)

pull/48024/head
Tim Rupp 6 years ago committed by GitHub
parent c6823b9849
commit 0ac57b97b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,7 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
# Copyright (c) 2017 F5 Networks Inc. # Copyright: (c) 2017, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function from __future__ import absolute_import, division, print_function
@ -13,6 +13,7 @@ ANSIBLE_METADATA = {'metadata_version': '1.1',
'supported_by': 'certified'} 'supported_by': 'certified'}
DOCUMENTATION = r''' DOCUMENTATION = r'''
---
module: bigip_ssl_key module: bigip_ssl_key
short_description: Import/Delete SSL keys from BIG-IP short_description: Import/Delete SSL keys from BIG-IP
description: description:
@ -59,6 +60,7 @@ requirements:
- BIG-IP >= v12 - BIG-IP >= v12
author: author:
- Tim Rupp (@caphrim007) - Tim Rupp (@caphrim007)
- Wojciech Wypior (@wojtek0806)
''' '''
EXAMPLES = r''' EXAMPLES = r'''
@ -111,27 +113,25 @@ from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback from ansible.module_utils.basic import env_fallback
try: try:
from library.module_utils.network.f5.bigip import HAS_F5SDK from library.module_utils.network.f5.bigip import F5RestClient
from library.module_utils.network.f5.bigip import F5Client
from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import f5_argument_spec from library.module_utils.network.f5.common import f5_argument_spec
try: from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError from library.module_utils.network.f5.common import fail_json
except ImportError: from library.module_utils.network.f5.common import transform_name
HAS_F5SDK = False from library.module_utils.network.f5.icontrol import upload_file
except ImportError: except ImportError:
from ansible.module_utils.network.f5.bigip import HAS_F5SDK from ansible.module_utils.network.f5.bigip import F5RestClient
from ansible.module_utils.network.f5.bigip import F5Client
from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import f5_argument_spec from ansible.module_utils.network.f5.common import f5_argument_spec
try: from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError from ansible.module_utils.network.f5.common import fail_json
except ImportError: from ansible.module_utils.network.f5.common import transform_name
HAS_F5SDK = False from ansible.module_utils.network.f5.icontrol import upload_file
try: try:
from StringIO import StringIO from StringIO import StringIO
@ -146,22 +146,37 @@ class Parameters(AnsibleF5Parameters):
'sourcePath': 'key_source_path' 'sourcePath': 'key_source_path'
} }
updatables = ['key_source_path'] updatables = [
'key_checksum',
'key_source_path',
]
returnables = ['key_filename', 'key_checksum', 'key_source_path'] returnables = [
'key_filename',
'key_checksum',
'key_source_path',
]
api_attributes = ['passphrase', 'sourcePath'] api_attributes = [
'passphrase',
'sourcePath',
]
class ApiParameters(Parameters):
@property
def checksum(self):
if self._values['checksum'] is None:
return None
pattern = r'SHA1:\d+:(?P<value>[\w+]{40})'
matches = re.match(pattern, self._values['checksum'])
if matches:
return matches.group('value')
else:
return None
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class ModuleParameters(Parameters):
def _get_hash(self, content): def _get_hash(self, content):
k = hashlib.sha1() k = hashlib.sha1()
s = StringIO(content) s = StringIO(content)
@ -193,76 +208,144 @@ class Parameters(AnsibleF5Parameters):
) )
return result return result
@property
def checksum(self):
if self._values['checksum'] is None:
return None
pattern = r'SHA1:\d+:(?P<value>[\w+]{40})'
matches = re.match(pattern, self._values['checksum'])
if matches:
return matches.group('value')
else:
return None
class Changes(Parameters): class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class UsableChanges(Changes):
pass
class ReportableChanges(Changes):
pass pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
@property
def key_checksum(self):
if self.want.key_checksum is None:
return None
if self.want.key_checksum != self.have.checksum:
return self.want.key_checksum
@property
def key_source_path(self):
if self.want.key_source_path is None:
return None
if self.want.key_source_path == self.have.key_source_path:
if self.key_checksum:
return self.want.key_source_path
if self.want.key_source_path != self.have.key_source_path:
return self.want.key_source_path
class ModuleManager(object): class ModuleManager(object):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None) self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None) self.client = kwargs.get('client', None)
self.have = None self.want = ModuleParameters(params=self.module.params)
self.want = Parameters(params=self.module.params) self.have = ApiParameters()
self.changes = Changes() self.changes = UsableChanges()
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def exec_module(self): def exec_module(self):
changed = False changed = False
result = dict() result = dict()
state = self.want.state state = self.want.state
try:
if state == "present": if state == "present":
changed = self.present() changed = self.present()
elif state == "absent": elif state == "absent":
changed = self.absent() changed = self.absent()
except iControlUnexpectedHTTPError as e:
raise F5ModuleError(str(e))
changes = self.changes.to_return() reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes) result.update(**changes)
result.update(dict(changed=changed)) result.update(dict(changed=changed))
self._announce_deprecations(result)
return result return result
def _set_changed_options(self): def present(self):
changed = {} if self.exists():
try: return self.update()
for key in Parameters.returnables: else:
if getattr(self.want, key) is not None: return self.create()
changed[key] = getattr(self.want, key)
if changed:
self.changes = Changes(params=changed)
except Exception:
pass
def _update_changed_options(self): def absent(self):
changed = {} if self.exists():
try: return self.remove()
for key in Parameters.updatables: return False
if getattr(self.want, key) is not None:
attr1 = getattr(self.want, key) def update(self):
attr2 = getattr(self.have, key) self.have = self.read_current_from_device()
if attr1 != attr2: if not self.should_update():
changed[key] = attr1
if self.want.key_checksum != self.have.checksum:
changed['key_checksum'] = self.want.key_checksum
if changed:
self.changes = Changes(params=changed)
return True
except Exception:
pass
return False return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def should_update(self): def should_update(self):
result = self._update_changed_options() result = self._update_changed_options()
@ -270,30 +353,6 @@ class ModuleManager(object):
return True return True
return False return False
def update_on_device(self):
content = StringIO(self.want.content)
self.client.api.shared.file_transfer.uploads.upload_stringio(
content, self.want.key_filename
)
resource = self.client.api.tm.sys.file.ssl_keys.ssl_key.load(
name=self.want.key_filename,
partition=self.want.partition
)
resource.update()
def exists(self):
result = self.client.api.tm.sys.file.ssl_keys.ssl_key.exists(
name=self.want.key_filename,
partition=self.want.partition
)
return result
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def create(self): def create(self):
if self.want.content is None: if self.want.content is None:
return False return False
@ -303,53 +362,113 @@ class ModuleManager(object):
self.create_on_device() self.create_on_device()
return True return True
def read_current_from_device(self): def remove(self):
resource = self.client.api.tm.sys.file.ssl_keys.ssl_key.load(
name=self.want.key_filename,
partition=self.want.partition
)
result = resource.attrs
return Parameters(params=result)
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode: if self.module.check_mode:
return True return True
self.update_on_device() self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the key")
return True return True
def exists(self):
uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.key_filename)
)
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 upload_file_to_device(self, content, name):
url = 'https://{0}:{1}/mgmt/shared/file-transfer/uploads'.format(
self.client.provider['server'],
self.client.provider['server_port']
)
try:
upload_file(self.client, url, content, name)
except F5ModuleError:
raise F5ModuleError(
"Failed to upload the file."
)
def update_on_device(self):
content = StringIO(self.want.content)
self.upload_file_to_device(content, self.want.key_filename)
params = self.changes.api_params()
uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.key_filename)
)
resp = self.client.api.put(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 create_on_device(self): def create_on_device(self):
params = self.changes.api_params()
content = StringIO(self.want.content) content = StringIO(self.want.content)
self.client.api.shared.file_transfer.uploads.upload_stringio( self.upload_file_to_device(content, self.want.key_filename)
content, self.want.key_filename params['name'] = self.want.key_filename
params['partition'] = self.want.partition
uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/".format(
self.client.provider['server'],
self.client.provider['server_port'],
) )
self.client.api.tm.sys.file.ssl_keys.ssl_key.create( resp = self.client.api.post(uri, json=params)
sourcePath=self.want.key_source_path, try:
name=self.want.key_filename, response = resp.json()
partition=self.want.partition 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)
def read_current_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.key_filename)
) )
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
def absent(self): if 'code' in response and response['code'] == 400:
if self.exists(): if 'message' in response:
return self.remove() raise F5ModuleError(response['message'])
return False else:
raise F5ModuleError(resp.content)
return ApiParameters(params=response)
def remove_from_device(self): def remove_from_device(self):
resource = self.client.api.tm.sys.file.ssl_keys.ssl_key.load( uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/{2}".format(
name=self.want.key_filename, self.client.provider['server'],
partition=self.want.partition self.client.provider['server_port'],
transform_name(self.want.partition, self.want.key_filename)
) )
resource.delete() response = self.client.api.delete(uri)
if response.status == 200:
def remove(self):
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the key")
return True return True
raise F5ModuleError(response.content)
class ArgumentSpec(object): class ArgumentSpec(object):
@ -387,18 +506,17 @@ def main():
argument_spec=spec.argument_spec, argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode supports_check_mode=spec.supports_check_mode
) )
if not HAS_F5SDK:
module.fail_json(msg="The python f5-sdk module is required") client = F5RestClient(**module.params)
try: try:
client = F5Client(**module.params)
mm = ModuleManager(module=module, client=client) mm = ModuleManager(module=module, client=client)
results = mm.exec_module() results = mm.exec_module()
cleanup_tokens(client) cleanup_tokens(client)
module.exit_json(**results) exit_json(module, results, client)
except F5ModuleError as ex: except F5ModuleError as ex:
cleanup_tokens(client) cleanup_tokens(client)
module.fail_json(msg=str(ex)) fail_json(module, ex, client)
if __name__ == '__main__': if __name__ == '__main__':

Loading…
Cancel
Save