summaryrefslogtreecommitdiff
path: root/lib/ansible/modules/network/f5/bigip_device_license.py
blob: f3c769e3b8d3ae5430e233558994a62a43ef1780 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2016, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type


ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'certified'}

DOCUMENTATION = '''
---
module: bigip_device_license
short_description: Manage license installation and activation on BIG-IP devices
description:
  - Manage license installation and activation on a BIG-IP.
version_added: 2.6
options:
  license_key:
    description:
      - The registration key to use to license the BIG-IP.
      - This parameter is required if the C(state) is equal to C(present).
      - This parameter is not required when C(state) is C(absent) and will be
        ignored if it is provided.
    type: str
  license_server:
    description:
      - The F5 license server to use when getting a license and validating a dossier.
      - This parameter is required if the C(state) is equal to C(present).
      - This parameter is not required when C(state) is C(absent) and will be
        ignored if it is provided.
    type: str
    default: activate.f5.com
  state:
    description:
      - The state of the license on the system.
      - When C(present), only guarantees that a license is there.
      - When C(latest), ensures that the license is always valid.
      - When C(absent), removes the license on the system.
      - When C(revoked), removes the license on the system and revokes its future usage
        on the F5 license servers.
    type: str
    choices:
      - absent
      - present
      - revoked
    default: present
  accept_eula:
    description:
      - Declares whether you accept the BIG-IP EULA or not. By default, this
        value is C(no). You must specifically declare that you have viewed and
        accepted the license. This module will not present you with that EULA
        though, so it is incumbent on you to read it.
      - The EULA can be found here; https://support.f5.com/csp/article/K12902.
      - This parameter is not required when C(state) is C(absent) and will be
        ignored if it is provided.
    type: bool
    default: no
extends_documentation_fragment: f5
author:
  - Tim Rupp (@caphrim007)
'''

EXAMPLES = '''
- name: License BIG-IP using a key
  bigip_device_license:
    license_key: "XXXXX-XXXXX-XXXXX-XXXXX-XXXXXXX"
    provider:
      server: "lb.mydomain.com"
      user: "admin"
      password: "secret"
  delegate_to: localhost

- name: Remove the license from the system
  bigip_device_license:
    state: "absent"
    provider:
      server: "lb.mydomain.com"
      user: "admin"
      password: "secret"
  delegate_to: localhost
'''

RETURN = r'''
# only common fields returned
'''

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six import iteritems

import re
import time
import xml.etree.ElementTree

try:
    from library.module_utils.network.f5.bigip import F5RestClient
    from library.module_utils.network.f5.common import F5ModuleError
    from library.module_utils.network.f5.common import AnsibleF5Parameters
    from library.module_utils.network.f5.common import fq_name
    from library.module_utils.network.f5.common import f5_argument_spec
    from library.module_utils.network.f5.icontrol import iControlRestSession
except ImportError:
    from ansible.module_utils.network.f5.bigip import F5RestClient
    from ansible.module_utils.network.f5.common import F5ModuleError
    from ansible.module_utils.network.f5.common import AnsibleF5Parameters
    from ansible.module_utils.network.f5.common import fq_name
    from ansible.module_utils.network.f5.common import f5_argument_spec
    from ansible.module_utils.network.f5.icontrol import iControlRestSession


class LicenseXmlParser(object):
    def __init__(self, content=None):
        self.raw_content = content
        try:
            self.content = xml.etree.ElementTree.fromstring(content)
        except xml.etree.ElementTree.ParseError as ex:
            raise F5ModuleError("Provided XML payload is invalid. Received '{0}'.".format(str(ex)))

    @property
    def namespaces(self):
        result = {
            'xsi': 'http://www.w3.org/2001/XMLSchema-instance'
        }
        return result

    @property
    def eula(self):
        try:
            root = self.content.findall('.//eula', self.namespaces)
            return root[0].text
        except Exception:
            return None

    @property
    def license(self):
        try:
            root = self.content.findall('.//license', self.namespaces)
            return root[0].text
        except Exception:
            return None

    def find_element(self, value):
        root = self.content.findall('.//multiRef', self.namespaces)
        if len(root) == 0:
            return None
        for elem in root:
            for k, v in iteritems(elem.attrib):
                if value in v:
                    return elem

    @property
    def state(self):
        elem = self.find_element('TransactionState')
        if elem is not None:
            return elem.text

    @property
    def fault_number(self):
        fault = self.get_fault()
        return fault.get('faultNumber', None)

    @property
    def fault_text(self):
        fault = self.get_fault()
        return fault.get('faultText', None)

    def get_fault(self):
        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')
        if root is None:
            return result
        for elem in root:
            if elem.tag == 'faultNumber':
                result['faultNumber'] = int(elem.text)
            elif elem.tag == 'faultText':
                tmp = elem.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}nil', None)
                if tmp == 'true':
                    result['faultText'] = None
                else:
                    result['faultText'] = elem.text

    def set_result_for_general_fault(self, 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):
        result = dict(
            eula=self.eula or None,
            license=self.license or None,
            state=self.state or None,
            fault_number=self.fault_number,
            fault_text=self.fault_text or None
        )
        return result


class Parameters(AnsibleF5Parameters):
    api_map = {
        'licenseEndDateTime': 'license_end_date_time',
    }

    api_attributes = [

    ]

    returnables = [

    ]

    updatables = [

    ]


class ApiParameters(Parameters):
    pass


class ModuleParameters(Parameters):
    @property
    def license_options(self):
        result = dict(
            eula=self.eula or '',
            email=self.email or '',
            first_name=self.first_name or '',
            last_name=self.last_name or '',
            company=self.company or '',
            phone=self.phone or '',
            job_title=self.job_title or '',
            address=self.address or '',
            city=self.city or '',
            state=self.state or '',
            postal_code=self.postal_code or '',
            country=self.country or ''
        )
        return result

    @property
    def license_url(self):
        result = 'https://{0}/license/services/urn:com.f5.license.v5b.ActivationService'.format(self.license_server)
        return result

    @property
    def license_envelope(self):
        result = """<?xml version="1.0" encoding="UTF-8"?>
        <SOAP-ENV:Envelope xmlns:ns3="http://www.w3.org/2001/XMLSchema"
                           xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
                           xmlns:ns0="http://schemas.xmlsoap.org/soap/encoding/"
                           xmlns:ns1="https://{0}/license/services/urn:com.f5.license.v5b.ActivationService"
                           xmlns:ns2="http://schemas.xmlsoap.org/soap/envelope/"
                           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                           xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                           SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
          <SOAP-ENV:Header/>
          <ns2:Body>
            <ns1:getLicense>
              <dossier xsi:type="ns3:string">{1}</dossier>
              <eula xsi:type="ns3:string">{eula}</eula>
              <email xsi:type="ns3:string">{email}</email>
              <firstName xsi:type="ns3:string">{first_name}</firstName>
              <lastName xsi:type="ns3:string">{last_name}</lastName>
              <companyName xsi:type="ns3:string">{company}</companyName>
              <phone xsi:type="ns3:string">{phone}</phone>
              <jobTitle xsi:type="ns3:string">{job_title}</jobTitle>
              <address xsi:type="ns3:string">{address}</address>
              <city xsi:type="ns3:string">{city}</city>
              <stateProvince xsi:type="ns3:string">{state}</stateProvince>
              <postalCode xsi:type="ns3:string">{postal_code}</postalCode>
              <country xsi:type="ns3:string">{country}</country>
            </ns1:getLicense>
          </ns2:Body>
        </SOAP-ENV:Envelope>"""
        result = result.format(self.license_server, self.dossier, **self.license_options)
        return result


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


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


class ModuleManager(object):
    def __init__(self, *args, **kwargs):
        self.module = kwargs.get('module', None)
        self.client = F5RestClient(**self.module.params)
        self.want = ModuleParameters(params=self.module.params, client=self.client)
        self.have = ApiParameters(client=self.client)
        self.changes = UsableChanges()
        self.escape_patterns = r'([$"' + "'])"

    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 should_update(self):
        result = self._update_changed_options()
        if result:
            return True
        return False

    def exec_module(self):
        changed = False
        result = dict()
        state = self.want.state

        if state == "present":
            changed = self.present()
        elif state == "absent":
            changed = self.absent()
        elif state == "revoked":
            changed = self.revoke()

        reportable = ReportableChanges(params=self.changes.to_return())
        changes = reportable.to_return()
        result.update(**changes)
        result.update(dict(changed=changed))
        self._announce_deprecations(result)
        return result

    def _announce_deprecations(self, result):
        warnings = result.pop('__warnings', [])
        for warning in warnings:
            self.client.module.deprecate(
                msg=warning['msg'],
                version=warning['version']
            )

    def present(self):
        if self.exists() and not self.is_revoked():
            return False
        else:
            return self.create()

    def remove(self):
        if self.module.check_mode:
            return True
        self.remove_from_device()
        if self.exists():
            raise F5ModuleError("Failed to delete the resource.")
        return True

    def revoke(self):
        if self.is_revoked():
            return False
        else:
            # When revoking a license, it should be acceptable to auto-accept the
            # license since you accepted it the first time when you activated the
            # license you are now revoking.
            self.want.update({'accept_eula': True})

            # Revoking seems to just be another way of saying "get me a new license".
            # There appear to be revoke-specific wording in the license and I assume
            # some special revoke-like signing is happening, but the process is essentially
            # just another form of "create".
            return self.create()

    def revoke_from_device(self):
        if self.module.check_mode:
            return True

        dossier = self.read_dossier_from_device()
        if dossier:
            self.want.update({'dossier': dossier})
        else:
            raise F5ModuleError("Dossier not generated.")

        if self.is_revoked():
            return False

    def is_revoked(self):
        command = '-c "egrep Revoked /config/bigip.license"'
        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)
        if 'commandResult' in response and 'Revoked' in response['commandResult']:
            return True
        return False

    def read_dossier_from_device(self):
        params = dict(
            command='run',
            utilCmdArgs='-b "{0}"'.format(self.want.license_key)
        )
        if self.want.state == 'revoked':
            params['utilCmdArgs'] = '-r ' + params['utilCmdArgs']

        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:
            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:
            if self.want.state == 'revoked':
                return response['commandResult'][8:]
            else:
                return response['commandResult']
        except Exception:
            return None

    def generate_license_from_remote(self):
        mgmt = iControlRestSession(
            validate_certs=False,
            headers={
                'SOAPAction': '""',
                'Content-Type': 'text/xml; charset=utf-8',
            }
        )

        for x in range(0, 10):
            try:
                resp = mgmt.post(
                    self.want.license_url,
                    data=self.want.license_envelope,
                )
            except Exception:
                continue

            try:
                resp = LicenseXmlParser(content=resp.content)
                result = resp.json()
            except F5ModuleError:
                # This error occurs when there is a problem with the license server and it
                # starts returning invalid XML (like if they upgraded something and the server
                # is redirecting improperly.
                #
                # There's no way to recover from this error except by notifying F5 that there
                # is an issue with the license server.
                raise
            except Exception:
                continue

            if result['state'] == 'EULA_REQUIRED':
                self.want.update({'eula': result['eula']})
                continue
            if result['state'] == 'LICENSE_RETURNED':
                return result
            elif result['state'] == 'EMAIL_REQUIRED':
                raise F5ModuleError("Email must be provided")
            elif result['state'] == 'CONTACT_INFO_REQUIRED':
                raise F5ModuleError("Contact info must be provided")
            else:
                raise F5ModuleError(result['fault_text'])

    def create(self):
        self._set_changed_options()
        if not self.want.accept_eula:
            raise F5ModuleError(
                "You must read and accept the product EULA to license the box."
            )
        if self.module.check_mode:
            return True

        dossier = self.read_dossier_from_device()
        if dossier:
            self.want.update({'dossier': dossier})
        else:
            raise F5ModuleError("Dossier not generated.")

        self.create_on_device()
        self.wait_for_mcpd()
        if not self.exists():
            raise F5ModuleError(
                "Failed to license the device."
            )
        return True

    def absent(self):
        if self.any_license_exists():
            self.remove()
            self.wait_for_mcpd()
            if self.exists():
                raise F5ModuleError(
                    "Failed to remove the license from the device."
                )
            return True
        return False

    def exists(self):
        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:
            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
        except Exception:
            pass
        return False

    def wait_for_mcpd(self):
        nops = 0

        # Sleep a little to let mcpd settle and begin properly
        time.sleep(5)

        while nops < 4:
            try:
                if self._is_mcpd_ready_on_device():
                    nops += 1
                else:
                    nops = 0
            except Exception:
                pass
            time.sleep(5)

    def _is_mcpd_ready_on_device(self):
        try:
            command = "tmsh show sys mcp-state | grep running"
            params = dict(
                command='run',
                utilCmdArgs='-c "{0}"'.format(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)

            if 'commandResult' in response:
                return True
        except Exception:
            pass
        return False

    def any_license_exists(self):
        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:
            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
        except Exception:
            pass
        return False

    def create_on_device(self):
        license = self.generate_license_from_remote()
        if license is None:
            raise F5ModuleError(
                "Failed to generate license from F5 activation servers."
            )
        result = self.upload_license_to_device(license)
        if not result:
            raise F5ModuleError(
                "Failed to install license on device."
            )
        result = self.upload_eula_to_device(license)
        if not result:
            raise F5ModuleError(
                "Failed to upload EULA file to device."
            )
        result = self.reload_license()
        if not result:
            raise F5ModuleError(
                "Failed to reload license configuration."
            )

    def upload_license_to_device(self, license):
        license_payload = re.sub(self.escape_patterns, r'\\\1', license['license'])
        command_arg = """cat > /config/bigip.license <<EOF\n{0}\nEOF""".format(license_payload)
        command = '-c "{0}"'.format(command_arg)
        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

    def upload_eula_to_device(self, license):
        eula_payload = re.sub(self.escape_patterns, r'\\\1', license['eula'])
        command_arg = """cat > /LICENSE.F5 <<EOF\n{0}\nEOF""".format(eula_payload)
        command = '-c "{0}"'.format(command_arg)
        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

    def reload_license(self):
        command = '-c "{0}"'.format("/usr/bin/reloadlic")
        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

    def remove_from_device(self):
        result = self.remove_license_from_device()
        if not result:
            raise F5ModuleError(
                "Failed to remove license from device."
            )
        result = self.remove_eula_from_device()
        if not result:
            raise F5ModuleError(
                "Failed to remove EULA file from device."
            )
        result = self.reload_license()
        if not result:
            raise F5ModuleError(
                "Failed to reload the empty license configuration."
            )

    def remove_license_from_device(self):
        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:
            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:
            if 'No such file or directory' in response['commandResult']:
                return True
            else:
                raise F5ModuleError(response['commandResult'])
        return True

    def remove_eula_from_device(self):
        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:
            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:
            if 'No such file or directory' in response['commandResult']:
                return True
            else:
                raise F5ModuleError(response['commandResult'])
        return True


class ArgumentSpec(object):
    def __init__(self):
        self.supports_check_mode = True
        argument_spec = dict(
            license_key=dict(),
            license_server=dict(
                default='activate.f5.com'
            ),
            state=dict(
                choices=['absent', 'present', 'revoked'],
                default='present'
            ),
            accept_eula=dict(
                type='bool',
                default='no'
            )
        )
        self.argument_spec = {}
        self.argument_spec.update(f5_argument_spec)
        self.argument_spec.update(argument_spec)
        self.required_if = [
            ['state', 'present', ['accept_eula', 'license_key']]
        ]


def main():
    spec = ArgumentSpec()

    module = AnsibleModule(
        argument_spec=spec.argument_spec,
        supports_check_mode=spec.supports_check_mode,
        required_if=spec.required_if
    )

    try:
        mm = ModuleManager(module=module)
        results = mm.exec_module()
        module.exit_json(**results)
    except F5ModuleError as ex:
        module.fail_json(msg=str(ex))


if __name__ == '__main__':
    main()