Debian Codegraph @

ansible_collections/community/grafana/plugins/modules/grafana_organization.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
25 author:
26 - paytroff (@paytroff)
27 version_added: "1.3.0"
28 short_description: Manage Grafana Organization
29 description:
30 - Create/delete Grafana organization through org API.
31 - Tested with Grafana v6.5.0
32 options:
33 name:
34 description:
35 - The name of the Grafana Organization.
36 required: true
37 type: str
38 state:
39 description:
40 - State if the organization should be present in Grafana or not
41 default: present
42 type: str
43 choices: ["present", "absent"]
44 extends_documentation_fragment:
45 - community.grafana.basic_auth
46 """
47
48 EXAMPLES = """
49 ---
50 - name: Create a Grafana organization
51 community.grafana.grafana_organization:
52 url: "https://grafana.example.com"
53 url_username: admin
54 url_password: changeme
55 name: orgtest
56 state: present
57
58 - name: Delete a Grafana organization
59 community.grafana.grafana_organization:
60 url: "https://grafana.example.com"
61 url_username: admin
62 url_password: changeme
63 name: orgtest
64 state: absent
65 """
66
67 RETURN = """
68 ---
69 org:
70 description: Information about the organization
71 returned: when state present
72 type: complex
73 contains:
74 id:
75 description: The org id
76 returned: always
77 type: int
78 sample:
79 - 42
80 name:
81 description: The org name
82 returned: always
83 type: str
84 sample:
85 - "org42"
86 address:
87 description: The org address
88 returned: always
89 type: dict
90 sample:
91 address1: ""
92 address2: ""
93 city: ""
94 country: ""
95 state: ""
96 zipCode: ""
97 """
98
99 import json
100
101 from ansible.module_utils.basic import AnsibleModule
102 from ansible.module_utils.urls import fetch_url, basic_auth_header
103 from ansible_collections.community.grafana.plugins.module_utils import base
104 from ansible.module_utils.six.moves.urllib.parse import quote
105
106 __metaclass__ = type
107
108
109 class GrafanaOrgInterface(object):
110 def __init__(self, module):
111 self._module = module
112 # {{{ Authentication header
113 self.headers = {"Content-Type": "application/json"}
114 self.headers["Authorization"] = basic_auth_header(
115 module.params["url_username"], module.params["url_password"]
116 )
117 # }}}
118 self.grafana_url = base.clean_url(module.params.get("url"))
119
120 def _send_request(self, url, data=None, headers=None, method="GET"):
121 if data is not None:
122 data = json.dumps(data, sort_keys=True)
123 if not headers:
124 headers = []
125
126 full_url = "{grafana_url}{path}".format(grafana_url=self.grafana_url, path=url)
127 resp, info = fetch_url(
128 self._module, full_url, data=data, headers=headers, method=method
129 )
130 status_code = info["status"]
131 if status_code == 404:
132 return None
133 elif status_code == 401:
134 self._module.fail_json(
135 failed=True,
136 msg="Unauthorized to perform action '%s' on '%s' header: %s"
137 % (method, full_url, self.headers),
138 )
139 elif status_code == 403:
140 self._module.fail_json(failed=True, msg="Permission Denied")
141 elif status_code == 200:
142 return self._module.from_json(resp.read())
143 if resp is None:
144 self._module.fail_json(
145 failed=True,
146 msg="Cannot connect to API Grafana %s" % info["msg"],
147 status=status_code,
148 url=info["url"],
149 )
150 else:
151 self._module.fail_json(
152 failed=True,
153 msg="Grafana Org API answered with HTTP %d" % status_code,
154 body=self._module.from_json(resp.read()),
155 )
156
157 def get_actual_org(self, name):
158 # https://grafana.com/docs/grafana/latest/http_api/org/#get-organization-by-name
159 url = "/api/orgs/name/{name}".format(name=quote(name))
160 return self._send_request(url, headers=self.headers, method="GET")
161
162 def create_org(self, name):
163 # https://grafana.com/docs/http_api/org/#create-organization
164 url = "/api/orgs"
165 org = dict(name=name)
166 self._send_request(url, data=org, headers=self.headers, method="POST")
167 return self.get_actual_org(name)
168
169 def delete_org(self, org_id):
170 # https://grafana.com/docs/http_api/org/#delete-organization
171 url = "/api/orgs/{org_id}".format(org_id=org_id)
172 return self._send_request(url, headers=self.headers, method="DELETE")
173
174
175 def setup_module_object():
176 module = AnsibleModule(
177 argument_spec=argument_spec,
178 supports_check_mode=False,
179 required_together=base.grafana_required_together(),
180 )
181 return module
182
183
184 argument_spec = base.grafana_argument_spec()
185 argument_spec.update(
186 state=dict(choices=["present", "absent"], default="present"),
187 name=dict(type="str", required=True),
188 )
189 argument_spec.pop("grafana_api_key")
190
191
192 def main():
193 module = setup_module_object()
194 state = module.params["state"]
195 name = module.params["name"]
196
197 grafana_iface = GrafanaOrgInterface(module)
198
199 # search org by name
200 actual_org = grafana_iface.get_actual_org(name)
201 if state == "present":
202 has_changed = False
203
204 if actual_org is None:
205 # create new org
206 actual_org = grafana_iface.create_org(name)
207 has_changed = True
208 module.exit_json(
209 changed=has_changed,
210 msg="Organization %s created." % name,
211 org=actual_org,
212 )
213 else:
214 module.exit_json(
215 changed=has_changed,
216 msg="Organization %s already created." % name,
217 org=actual_org,
218 )
219
220 elif state == "absent":
221 if actual_org is None:
222 module.exit_json(msg="No org found, nothing to do")
223 # delete org
224 result = grafana_iface.delete_org(actual_org.get("id"))
225 module.exit_json(changed=True, msg=result.get("message"))
226
227
228 if __name__ == "__main__":
229 main()