Debian Codegraph @

ansible_collections/community/grafana/plugins/modules/grafana_organization_user.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17 #
18 # Copyright: (c) 2021
19
20 from __future__ import absolute_import, division, print_function
21
22 DOCUMENTATION = """
23 ---
24 module: grafana_organization_user
25 author:
26 - Aliaksandr Mianzhynski (@amenzhinsky)
27 version_added: "1.6.0"
28 short_description: Manage Grafana Organization Users.
29 description:
30 - Add or remove users or change their roles in Grafana organizations through org API.
31 - The user has to exist before using this module. See U(https://docs.ansible.com/ansible/latest/collections/community/grafana/grafana_user_module.html).
32 options:
33 login:
34 type: str
35 required: True
36 description:
37 - Username or email.
38 role:
39 type: str
40 choices:
41 - viewer
42 - editor
43 - admin
44 default: viewer
45 description:
46 - User's role in the organization.
47 state:
48 type: str
49 default: present
50 choices:
51 - present
52 - absent
53 description:
54 - Status of a user's organization membership.
55 org_id:
56 type: int
57 default: 1
58 description:
59 - Organization ID.
60 - Mutually exclusive with C(org_name).
61 org_name:
62 type: str
63 description:
64 - Organization name.
65 - Mutually exclusive with C(org_id).
66
67 extends_documentation_fragment:
68 - community.grafana.basic_auth
69 """
70
71 EXAMPLES = """
72 ---
73 - name: Add user to organization
74 community.grafana.grafana_organization_user:
75 url: "{{ grafana_url }}"
76 url_username: "{{ grafana_username }}"
77 url_password: "{{ grafana_password }}"
78 login: john
79 role: admin
80
81 - name: Remove user from organization
82 community.grafana.grafana_organization_user:
83 url: "{{ grafana_url }}"
84 url_username: "{{ grafana_username }}"
85 url_password: "{{ grafana_password }}"
86 login: john
87 state: absent
88 """
89
90 RETURN = """
91 ---
92 user:
93 description: Information about the organization user
94 returned: when state present
95 type: complex
96 contains:
97 email:
98 description: The User email address
99 returned: always
100 type: str
101 sample:
102 - "[email protected]"
103 login:
104 description: The User login
105 returned: always
106 type: str
107 sample:
108 - "batman"
109 name:
110 description: The User name (same as login)
111 returned: always
112 type: str
113 sample:
114 - "batman"
115 orgId:
116 description: The organization id that the team is part of.
117 returned: always
118 type: int
119 sample:
120 - 1
121 role:
122 description: The user role in the organization
123 returned: always
124 type: str
125 choices:
126 - Viewer
127 - Editor
128 - Admin
129 sample:
130 - Viewer
131 """
132
133
134 import json
135
136 from ansible.module_utils.basic import AnsibleModule
137 from ansible.module_utils.urls import fetch_url
138 from ansible.module_utils._text import to_text
139 from ansible_collections.community.grafana.plugins.module_utils.base import (
140 grafana_argument_spec,
141 clean_url,
142 )
143 from ansible.module_utils.urls import basic_auth_header
144
145 __metaclass__ = type
146
147
148 class GrafanaAPIException(Exception):
149 pass
150
151
152 class GrafanaOrganizationUserInterface(object):
153 def __init__(self, module):
154 self._module = module
155 # {{{ Authentication header
156 self.headers = {"Content-Type": "application/json"}
157 self.headers["Authorization"] = basic_auth_header(
158 module.params["url_username"], module.params["url_password"]
159 )
160 # }}}
161 self.grafana_url = clean_url(module.params.get("url"))
162
163 def _api_call(self, method, path, payload):
164 data = None
165 if payload:
166 data = json.dumps(payload)
167 return fetch_url(
168 self._module,
169 self.grafana_url + "/api/" + path,
170 headers=self.headers,
171 method=method,
172 data=data,
173 )
174
175 def _organization_by_name(self, org_name):
176 r, info = self._api_call("GET", "orgs/name/%s" % org_name, None)
177 if info["status"] != 200:
178 raise GrafanaAPIException("Unable to retrieve organization: %s" % info)
179 return json.loads(to_text(r.read()))
180
181 def _organization_users(self, org_id):
182 r, info = self._api_call("GET", "orgs/%d/users" % org_id, None)
183 if info["status"] != 200:
184 raise GrafanaAPIException(
185 "Unable to retrieve organization users: %s" % info
186 )
187 return json.loads(to_text(r.read()))
188
189 def _create_organization_user(self, org_id, login, role):
190 return self._api_call(
191 "POST",
192 "orgs/%d/users" % org_id,
193 {
194 "loginOrEmail": login,
195 "role": role,
196 },
197 )
198
199 def _update_organization_user_role(self, org_id, user_id, role):
200 return self._api_call(
201 "PATCH",
202 "orgs/%d/users/%s" % (org_id, user_id),
203 {
204 "role": role,
205 },
206 )
207
208 def _remove_organization_user(self, org_id, user_id):
209 return self._api_call("DELETE", "orgs/%d/users/%s" % (org_id, user_id), None)
210
211 def _organization_user_by_login(self, org_id, login):
212 for user in self._organization_users(org_id):
213 if login in (user["login"], user["email"]):
214 return user
215
216 def create_or_update_user(self, org_id, login, role):
217 r, info = self._create_organization_user(org_id, login, role)
218 if info["status"] == 200:
219 return {
220 "state": "present",
221 "changed": True,
222 "user": self._organization_user_by_login(org_id, login),
223 }
224 if info["status"] == 409: # already member
225 user = self._organization_user_by_login(org_id, login)
226 if not user:
227 raise Exception("[BUG] User not found in organization")
228
229 if user["role"] == role:
230 return {"changed": False}
231
232 r, info = self._update_organization_user_role(org_id, user["userId"], role)
233 if info["status"] == 200:
234 return {
235 "changed": True,
236 "user": self._organization_user_by_login(org_id, login),
237 }
238 else:
239 raise GrafanaAPIException(
240 "Unable to update organization user: %s" % info
241 )
242 else:
243 raise GrafanaAPIException("Unable to add user to organization: %s" % info)
244
245 def remove_user(self, org_id, login):
246 user = self._organization_user_by_login(org_id, login)
247 if not user:
248 return {"changed": False}
249
250 r, info = self._remove_organization_user(org_id, user["userId"])
251 if info["status"] == 200:
252 return {"state": "absent", "changed": True}
253 else:
254 raise GrafanaAPIException("Unable to delete organization user: %s" % info)
255
256
257 def main():
258 argument_spec = grafana_argument_spec()
259 argument_spec.pop("grafana_api_key")
260 argument_spec.update(
261 org_id=dict(type="int", default=1),
262 org_name=dict(type="str"),
263 login=dict(type="str", required=True),
264 role=dict(type="str", choices=["viewer", "editor", "admin"], default="viewer"),
265 )
266 module = AnsibleModule(
267 argument_spec=argument_spec,
268 supports_check_mode=False,
269 mutually_exclusive=[
270 ("org_id", "org_name"),
271 ],
272 required_if=[
273 ["state", "present", ["role"]],
274 ],
275 )
276
277 org_id = module.params["org_id"]
278 login = module.params["login"]
279 iface = GrafanaOrganizationUserInterface(module)
280 if module.params["org_name"]:
281 org_name = module.params["org_name"]
282 organization = iface._organization_by_name(org_name)
283 org_id = organization["id"]
284 if module.params["state"] == "present":
285 role = module.params["role"].capitalize()
286 result = iface.create_or_update_user(org_id, login, role)
287 module.exit_json(failed=False, **result)
288 else:
289 result = iface.remove_user(org_id, login)
290 module.exit_json(failed=False, **result)
291
292
293 if __name__ == "__main__":
294 main()