1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Removes f5-sdk from bigip_device_license (#48476)

This commit is contained in:
Tim Rupp 2018-11-10 12:06:32 -08:00 committed by GitHub
parent 0873043e5a
commit ccb6349e70
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 241 additions and 77 deletions

View file

@ -1,7 +1,7 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
# Copyright (c) 2016 F5 Networks Inc. # Copyright: (c) 2016, 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
@ -90,31 +90,25 @@ import time
import xml.etree.ElementTree import xml.etree.ElementTree
try: try:
from library.module_utils.network.f5.bigip import HAS_F5SDK from library.module_utils.network.f5.bigip import F5RestClient
from library.module_utils.network.f5.bigip import F5Client
from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import fq_name
from library.module_utils.network.f5.common import f5_argument_spec from library.module_utils.network.f5.common import f5_argument_spec
from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import fail_json
from library.module_utils.network.f5.icontrol import iControlRestSession from library.module_utils.network.f5.icontrol import iControlRestSession
try:
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError
from f5.sdk_exception import UtilError
except ImportError:
HAS_F5SDK = False
except ImportError: except ImportError:
from ansible.module_utils.network.f5.bigip import HAS_F5SDK from ansible.module_utils.network.f5.bigip import F5RestClient
from ansible.module_utils.network.f5.bigip import F5Client
from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import fq_name
from ansible.module_utils.network.f5.common import f5_argument_spec from ansible.module_utils.network.f5.common import f5_argument_spec
from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import fail_json
from ansible.module_utils.network.f5.icontrol import iControlRestSession from ansible.module_utils.network.f5.icontrol import iControlRestSession
try:
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError
from f5.sdk_exception import UtilError
except ImportError:
HAS_F5SDK = False
class LicenseXmlParser(object): class LicenseXmlParser(object):
@ -176,10 +170,17 @@ class LicenseXmlParser(object):
def get_fault(self): def get_fault(self):
result = dict() result = dict()
self.set_result_for_license_fault(result)
self.set_result_for_general_fault(result)
if 'faultNumber' not in result:
result['faultNumber'] = None
return result
def set_result_for_license_fault(self, result):
root = self.find_element('LicensingFault') root = self.find_element('LicensingFault')
if root is None: if root is None:
return result return result
for elem in root: for elem in root:
if elem.tag == 'faultNumber': if elem.tag == 'faultNumber':
result['faultNumber'] = int(elem.text) result['faultNumber'] = int(elem.text)
@ -189,9 +190,17 @@ class LicenseXmlParser(object):
result['faultText'] = None result['faultText'] = None
else: else:
result['faultText'] = elem.text result['faultText'] = elem.text
if 'faultNumber' not in result:
result['faultNumber'] = None def set_result_for_general_fault(self, result):
return result namespaces = {
'ns2': 'http://schemas.xmlsoap.org/soap/envelope/'
}
root = self.content.findall('.//ns2:Fault', namespaces)
if len(root) == 0:
return None
for elem in root[0]:
if elem.tag == 'faultstring':
result['faultText'] = elem.text
def json(self): def json(self):
result = dict( result = dict(
@ -206,7 +215,7 @@ class LicenseXmlParser(object):
class Parameters(AnsibleF5Parameters): class Parameters(AnsibleF5Parameters):
api_map = { api_map = {
'licenseEndDateTime': 'license_end_date_time' 'licenseEndDateTime': 'license_end_date_time',
} }
api_attributes = [ api_attributes = [
@ -372,13 +381,10 @@ class ModuleManager(object):
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))
reportable = ReportableChanges(params=self.changes.to_return()) reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return() changes = reportable.to_return()
@ -410,25 +416,45 @@ class ModuleManager(object):
return True return True
def read_dossier_from_device(self): def read_dossier_from_device(self):
result = self.client.api.tm.util.get_dossier.exec_cmd( params = dict(
'run', utilCmdArgs='-b {0}'.format(self.want.license_key) command='run',
utilCmdArgs='-b "{0}"'.format(self.want.license_key)
) )
uri = "https://{0}:{1}/mgmt/tm/util/get-dossier".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try: try:
return result.commandResult response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
try:
return response['commandResult']
except Exception: except Exception:
return None return None
def generate_license_from_remote(self): def generate_license_from_remote(self):
mgmt = iControlRestSession() mgmt = iControlRestSession(
mgmt.verify = False validate_certs=False,
mgmt.headers = { headers={
'SOAPAction': '""', 'SOAPAction': '""',
'Content-Type': 'text/xml; charset=utf-8', 'Content-Type': 'text/xml; charset=utf-8',
} }
)
for x in range(0, 10): for x in range(0, 10):
try: try:
resp = mgmt.post(self.want.license_url, data=self.want.license_envelope) resp = mgmt.post(
self.want.license_url,
data=self.want.license_envelope,
)
except Exception as ex: except Exception as ex:
continue continue
@ -493,9 +519,24 @@ class ModuleManager(object):
return False return False
def exists(self): def exists(self):
resource = self.client.api.tm.shared.licensing.registration.load() uri = "https://{0}:{1}/mgmt/tm/shared/licensing/registration".format(
self.client.provider['server'],
self.client.provider['server_port'],
)
resp = self.client.api.get(uri)
try: try:
if resource.registrationKey == self.want.license_key: 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)
try:
if response['registrationKey'] == self.want.license_key:
return True return True
except Exception: except Exception:
pass pass
@ -519,20 +560,51 @@ class ModuleManager(object):
def _is_mcpd_ready_on_device(self): def _is_mcpd_ready_on_device(self):
try: try:
output = self.client.api.tm.util.bash.exec_cmd( command = "tmsh show sys mcp-state | grep running"
'run', params = dict(
utilCmdArgs='-c "tmsh show sys mcp-state | grep running"' command='run',
utilCmdArgs='-c "{0}"'.format(command)
) )
if hasattr(output, 'commandResult'): uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
if 'commandResult' in response:
return True return True
except Exception as ex: except Exception as ex:
pass pass
return False return False
def any_license_exists(self): def any_license_exists(self):
resource = self.client.api.tm.shared.licensing.registration.load() uri = "https://{0}:{1}/mgmt/tm/shared/licensing/registration".format(
self.client.provider['server'],
self.client.provider['server_port'],
)
resp = self.client.api.get(uri)
try: try:
if resource.registrationKey is not None: 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)
try:
if response['registrationKey'] is not None:
return True return True
except Exception: except Exception:
pass pass
@ -562,21 +634,75 @@ class ModuleManager(object):
def upload_license_to_device(self, license): def upload_license_to_device(self, license):
license_payload = re.sub(self.escape_patterns, r'\\\1', license['license']) license_payload = re.sub(self.escape_patterns, r'\\\1', license['license'])
command = """cat > /config/bigip.license <<EOF\n{0}\nEOF""".format(license_payload) command_arg = """cat > /config/bigip.license <<EOF\n{0}\nEOF""".format(license_payload)
command = '-c "{0}"'.format(command) command = '-c "{0}"'.format(command_arg)
self.client.api.tm.util.bash.exec_cmd('run', utilCmdArgs=command) params = dict(
command='run',
utilCmdArgs=command
)
uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return True return True
def upload_eula_to_device(self, license): def upload_eula_to_device(self, license):
eula_payload = re.sub(self.escape_patterns, r'\\\1', license['eula']) eula_payload = re.sub(self.escape_patterns, r'\\\1', license['eula'])
command = """cat > /LICENSE.F5 <<EOF\n{0}\nEOF""".format(eula_payload) command_arg = """cat > /LICENSE.F5 <<EOF\n{0}\nEOF""".format(eula_payload)
command = '-c "{0}"'.format(command) command = '-c "{0}"'.format(command_arg)
self.client.api.tm.util.bash.exec_cmd('run', utilCmdArgs=command) params = dict(
command='run',
utilCmdArgs=command
)
uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return True return True
def reload_license(self): def reload_license(self):
command = '-c "{0}"'.format("/usr/bin/reloadlic") command = '-c "{0}"'.format("/usr/bin/reloadlic")
self.client.api.tm.util.bash.exec_cmd('run', utilCmdArgs=command) params = dict(
command='run',
utilCmdArgs=command
)
uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return True return True
def remove_from_device(self): def remove_from_device(self):
@ -597,27 +723,61 @@ class ModuleManager(object):
) )
def remove_license_from_device(self): def remove_license_from_device(self):
# UtilError should be raised when non-existent file is mentioned params = dict(
command='run',
utilCmdArgs='/config/bigip.license'
)
uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try: try:
self.client.api.tm.util.unix_rm.exec_cmd( response = resp.json()
'run', utilCmdArgs='/config/bigip.license' except ValueError as ex:
) raise F5ModuleError(str(ex))
except UtilError as ex:
if 'No such file or directory' in 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)
if 'commandResult' in response:
if 'No such file or directory' in response['commandResult']:
return True return True
else: else:
raise F5ModuleError(str(ex)) raise F5ModuleError(response['commandResult'])
return True return True
def remove_eula_from_device(self): def remove_eula_from_device(self):
# UtilError should be raised when non-existent file is mentioned params = dict(
command='run',
utilCmdArgs='/LICENSE.F5'
)
uri = "https://{0}:{1}/mgmt/tm/util/bash".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try: try:
self.client.api.tm.util.unix_rm.exec_cmd('run', utilCmdArgs='/LICENSE.F5') response = resp.json()
except UtilError as ex: except ValueError as ex:
if 'No such file or directory' in str(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)
if 'commandResult' in response:
if 'No such file or directory' in response['commandResult']:
return True return True
else: else:
raise F5ModuleError(str(ex)) raise F5ModuleError(response['commandResult'])
return True return True
@ -653,18 +813,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__':

View file

@ -14,9 +14,6 @@ from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7): if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7") raise SkipTest("F5 Ansible modules require Python >= 2.7")
from units.compat import unittest
from units.compat.mock import Mock
from units.compat.mock import patch
from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import AnsibleModule
try: try:
@ -24,17 +21,25 @@ try:
from library.modules.bigip_device_license import ModuleParameters from library.modules.bigip_device_license import ModuleParameters
from library.modules.bigip_device_license import ModuleManager from library.modules.bigip_device_license import ModuleManager
from library.modules.bigip_device_license import ArgumentSpec from library.modules.bigip_device_license import ArgumentSpec
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import iControlUnexpectedHTTPError # In Ansible 2.8, Ansible changed import paths.
from test.unit.modules.utils import set_module_args from test.units.compat import unittest
from test.units.compat.mock import Mock
from test.units.compat.mock import patch
from test.units.modules.utils import set_module_args
except ImportError: except ImportError:
try: try:
from ansible.modules.network.f5.bigip_device_license import ApiParameters from ansible.modules.network.f5.bigip_device_license import ApiParameters
from ansible.modules.network.f5.bigip_device_license import ModuleParameters from ansible.modules.network.f5.bigip_device_license import ModuleParameters
from ansible.modules.network.f5.bigip_device_license import ModuleManager from ansible.modules.network.f5.bigip_device_license import ModuleManager
from ansible.modules.network.f5.bigip_device_license import ArgumentSpec from ansible.modules.network.f5.bigip_device_license import ArgumentSpec
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError # Ansible 2.8 imports
from units.compat import unittest
from units.compat.mock import Mock
from units.compat.mock import patch
from units.modules.utils import set_module_args from units.modules.utils import set_module_args
except ImportError: except ImportError:
raise SkipTest("F5 Ansible modules require the f5-sdk Python library") raise SkipTest("F5 Ansible modules require the f5-sdk Python library")