Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/lookup/license_hopper.py

raw symbols SCIP
1 # (c) 2013, Michael DeHaan <[email protected]>
2 # (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 from __future__ import (absolute_import, division, print_function)
5 __metaclass__ = type
6
7 DOCUMENTATION = """
8 name: license_hopper
9 author: Tim Rupp (@caphrim007)
10 version_added: "1.0.0"
11 short_description: Return random license from list
12 description:
13 - Select a random license key from a file and remove it from future lookups.
14 - Can optionally remove the key if C(remove=True) is specified.
15 """
16
17 EXAMPLES = """
18 - name: Get a regkey license from a stash without deleting it
19 bigiq_regkey_license:
20 key: "{{ lookup('license_hopper', 'filename=/path/to/licenses.txt') }}"
21 state: present
22 pool: regkey1
23
24 - name: Get a regkey license from a stash and delete the key from the file
25 bigiq_regkey_license:
26 key: "{{ lookup('license_hopper', 'filename=/path/to/licenses.txt', remove=True) }}"
27 state: present
28 pool: regkey1
29 """
30
31 RETURN = """
32 _raw:
33 description:
34 - random item
35 """
36
37 import random
38
39 from ansible.errors import AnsibleError
40 from ansible.module_utils._text import to_native
41 from ansible.plugins.lookup import LookupBase
42
43 BOOLEANS_TRUE = frozenset(('y', 'yes', 'on', '1', 'true', 'True', 't', 1, 1.0, True))
44
45
46 class LookupModule(LookupBase):
47 def __init__(self, loader=None, templar=None, **kwargs):
48
49 super(LookupModule, self).__init__(loader, templar, **kwargs)
50
51 self.filename = None
52 self.remove = False
53
54 def run(self, terms, variables=None, **kwargs):
55 self.filename = kwargs.pop('filename', None)
56 self.remove = kwargs.pop('remove', False)
57 if self.filename is None:
58 raise AnsibleError("No 'filename' was specified")
59 lookupfile = self.find_file_in_search_path(variables, 'files', self.filename)
60 if lookupfile is None:
61 raise AnsibleError("Could not find the specified 'filename'")
62 fh = open(lookupfile, 'r')
63 lines = [x.strip() for x in fh.readlines()]
64 fh.close()
65 try:
66 ret = [random.choice(lines)]
67 except Exception as e:
68 raise AnsibleError("Unable to choose random license: %s" % to_native(e))
69 if self.remove:
70 to_write = [x + "\n" for x in lines if x != ret[0]]
71 fh = open(lookupfile, 'w')
72 fh.writelines(to_write)
73 return ret