Debian Codegraph @

ansible_collections/community/general/plugins/modules/nomad_token.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2023, Pedro Nascimento <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: nomad_token
11 author: Pedro Nascimento (@apecnascimento)
12 version_added: "8.1.0"
13 short_description: Manage Nomad ACL tokens
14 description:
15 - This module allows to create Bootstrap tokens, create ACL tokens, update ACL tokens, and delete ACL tokens.
16 requirements:
17 - python-nomad
18 extends_documentation_fragment:
19 - community.general._nomad
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: none
24 diff_mode:
25 support: none
26 options:
27 name:
28 description:
29 - Name of ACL token to create.
30 type: str
31 token_type:
32 description:
33 - The type of the token can be V(client), V(management), or V(bootstrap).
34 choices: ["client", "management", "bootstrap"]
35 type: str
36 default: "client"
37 policies:
38 description:
39 - A list of the policies assigned to the token.
40 type: list
41 elements: str
42 default: []
43 global_replicated:
44 description:
45 - Indicates whether or not the token was created with the C(--global).
46 type: bool
47 default: false
48 state:
49 description:
50 - Create or remove ACL token.
51 choices: ["present", "absent"]
52 required: true
53 type: str
54
55 seealso:
56 - name: Nomad ACL documentation
57 description: Complete documentation for Nomad API ACL.
58 link: https://developer.hashicorp.com/nomad/api-docs/acl/tokens
59 """
60
61 EXAMPLES = r"""
62 - name: Create boostrap token
63 community.general.nomad_token:
64 host: localhost
65 token_type: bootstrap
66 state: present
67
68 - name: Create ACL token
69 community.general.nomad_token:
70 host: localhost
71 name: "Dev token"
72 token_type: client
73 policies:
74 - readonly
75 global_replicated: false
76 state: absent
77
78 - name: Update ACL token Dev token
79 community.general.nomad_token:
80 host: localhost
81 name: "Dev token"
82 token_type: client
83 policies:
84 - readonly
85 - devpolicy
86 global_replicated: false
87 state: absent
88
89 - name: Delete ACL token
90 community.general.nomad_token:
91 host: localhost
92 name: "Dev token"
93 state: absent
94 """
95
96 RETURN = r"""
97 result:
98 description: Result returned by nomad.
99 returned: always
100 type: dict
101 sample:
102 {
103 "accessor_id": "0d01c55f-8d63-f832-04ff-1866d4eb594e",
104 "create_index": 14,
105 "create_time": "2023-11-12T18:48:34.248857001Z",
106 "expiration_time": null,
107 "expiration_ttl": "",
108 "global": true,
109 "hash": "eSn8H8RVqh8As8WQNnC2vlBRqXy6DECogc5umzX0P30=",
110 "modify_index": 836,
111 "name": "devs",
112 "policies": [
113 "readonly"
114 ],
115 "roles": null,
116 "secret_id": "12e878ab-e1f6-e103-b4c4-3b5173bb4cea",
117 "type": "client"
118 }
119 """
120
121 from ansible.module_utils.basic import AnsibleModule
122
123 from ansible_collections.community.general.plugins.module_utils._nomad import argument_spec as nomad_argument_spec
124 from ansible_collections.community.general.plugins.module_utils._nomad import nomad, setup_nomad_client
125
126
127 def get_token(name, nomad_client):
128 tokens = nomad_client.acl.get_tokens()
129 token = next((token for token in tokens if token.get("Name") == name), None)
130 return token
131
132
133 def transform_response(nomad_response):
134 transformed_response = {
135 "accessor_id": nomad_response["AccessorID"],
136 "create_index": nomad_response["CreateIndex"],
137 "create_time": nomad_response["CreateTime"],
138 "expiration_ttl": nomad_response["ExpirationTTL"],
139 "expiration_time": nomad_response["ExpirationTime"],
140 "global": nomad_response["Global"],
141 "hash": nomad_response["Hash"],
142 "modify_index": nomad_response["ModifyIndex"],
143 "name": nomad_response["Name"],
144 "policies": nomad_response["Policies"],
145 "roles": nomad_response["Roles"],
146 "secret_id": nomad_response["SecretID"],
147 "type": nomad_response["Type"],
148 }
149
150 return transformed_response
151
152
153 argument_spec = {
154 **nomad_argument_spec,
155 "state": dict(required=True, choices=["present", "absent"]),
156 "name": dict(type="str"),
157 "token_type": dict(choices=["client", "management", "bootstrap"], default="client"),
158 "policies": dict(type="list", elements="str", default=[]),
159 "global_replicated": dict(type="bool", default=False),
160 }
161
162
163 def setup_module_object():
164 module = AnsibleModule(
165 argument_spec=argument_spec,
166 supports_check_mode=False,
167 required_one_of=[["name", "token_type"]],
168 required_if=[
169 ("token_type", "client", ("name",)),
170 ("token_type", "management", ("name",)),
171 ],
172 )
173 return module
174
175
176 def run(module):
177 nomad_client = setup_nomad_client(module)
178
179 msg = ""
180 result = {}
181 changed = False
182 if module.params["state"] == "present":
183 if module.params["token_type"] == "bootstrap":
184 try:
185 current_token = get_token("Bootstrap Token", nomad_client)
186 if current_token:
187 msg = "ACL bootstrap already exist."
188 else:
189 nomad_result = nomad_client.acl.generate_bootstrap()
190 msg = "Boostrap token created."
191 result = transform_response(nomad_result)
192 changed = True
193
194 except nomad.api.exceptions.URLNotAuthorizedNomadException:
195 try:
196 nomad_result = nomad_client.acl.generate_bootstrap()
197 msg = "Boostrap token created."
198 result = transform_response(nomad_result)
199 changed = True
200
201 except Exception as e:
202 module.fail_json(msg=f"{e}")
203 else:
204 try:
205 token_info = {
206 "Name": module.params["name"],
207 "Type": module.params["token_type"],
208 "Policies": module.params["policies"],
209 "Global": module.params["global_replicated"],
210 }
211
212 current_token = get_token(token_info["Name"], nomad_client)
213
214 if current_token:
215 token_info["AccessorID"] = current_token["AccessorID"]
216 nomad_result = nomad_client.acl.update_token(current_token["AccessorID"], token_info)
217 msg = "ACL token updated."
218 result = transform_response(nomad_result)
219 changed = True
220
221 else:
222 nomad_result = nomad_client.acl.create_token(token_info)
223 msg = "ACL token Created."
224 result = transform_response(nomad_result)
225 changed = True
226
227 except Exception as e:
228 module.fail_json(msg=f"{e}")
229
230 if module.params["state"] == "absent":
231 if not module.params["name"]:
232 module.fail_json(msg="name is needed to delete token.")
233
234 if module.params["token_type"] == "bootstrap" or module.params["name"] == "Bootstrap Token":
235 module.fail_json(msg="Delete ACL bootstrap token is not allowed.")
236
237 try:
238 token = get_token(module.params["name"], nomad_client)
239 if token:
240 nomad_client.acl.delete_token(token.get("AccessorID"))
241 msg = "ACL token deleted."
242 changed = True
243 else:
244 msg = f"No token with name '{module.params['name']}' found"
245
246 except Exception as e:
247 module.fail_json(msg=f"{e}")
248
249 module.exit_json(changed=changed, msg=msg, result=result)
250
251
252 def main():
253 module = setup_module_object()
254 run(module)
255
256
257 if __name__ == "__main__":
258 main()