Debian Codegraph @

ansible_collections/community/mongodb/plugins/module_utils/mongodb_atlas.py

raw
1 # -*- coding: utf-8 -*-
2
3 from __future__ import absolute_import, division, print_function
4
5 __metaclass__ = type
6
7 import json
8 from collections import defaultdict
9
10 from ansible.module_utils.urls import fetch_url
11
12 try:
13 from urllib import quote
14 except ImportError:
15 # noinspection PyCompatibility, PyUnresolvedReferences
16 from urllib.parse import (
17 quote,
18 ) # pylint: disable=locally-disabled, import-error, no-name-in-module
19
20
21 class AtlasAPIObject:
22 module = None
23
24 def __init__(
25 self, module, object_name, group_id, path, data, data_is_array=False
26 ):
27 self.module = module
28 self.path = path
29 self.data = data
30 self.group_id = group_id
31 self.object_name = object_name
32 self.data_is_array = data_is_array
33
34 self.module.params["url_username"] = self.module.params["api_username"]
35 self.module.params["url_password"] = self.module.params["api_password"]
36
37 def call_url(self, path, data="", method="GET"):
38 headers = {
39 "Accept": "application/json",
40 "Content-Type": "application/json",
41 }
42
43 if self.data_is_array and data != "":
44 data = "[" + data + "]"
45
46 url = (
47 "https://cloud.mongodb.com/api/atlas/v1.0/groups/"
48 + self.group_id
49 + path
50 )
51 rsp, info = fetch_url(
52 module=self.module,
53 url=url,
54 data=data,
55 headers=headers,
56 method=method,
57 )
58
59 content = ""
60 error = ""
61 if rsp and info["status"] not in (204, 404):
62 content = json.loads(rsp.read())
63 if info["status"] >= 400:
64 try:
65 content = json.loads(info["body"])
66 error = content["reason"]
67 if "detail" in content:
68 error += ". Detail: " + content["detail"]
69 except ValueError:
70 error = info["msg"]
71 if info["status"] < 0:
72 error = info["msg"]
73 return {"code": info["status"], "data": content, "error": error}
74
75 def exists(self):
76 additional_path = ""
77 if self.path == "/databaseUsers":
78 additional_path = "/admin"
79 ret = self.call_url(
80 path=self.path
81 + additional_path
82 + "/"
83 + quote(self.data[self.object_name], "")
84 )
85 if ret["code"] == 200:
86 return True
87 return False
88
89 def create(self):
90 ret = self.call_url(
91 path=self.path,
92 data=self.module.jsonify(self.data),
93 method="POST",
94 )
95 return ret
96
97 def delete(self):
98 additional_path = ""
99 if self.path == "/databaseUsers":
100 additional_path = "/admin"
101 ret = self.call_url(
102 path=self.path
103 + additional_path
104 + "/"
105 + quote(self.data[self.object_name], ""),
106 method="DELETE",
107 )
108 return ret
109
110 def modify(self):
111 additional_path = ""
112 if self.path == "/databaseUsers":
113 additional_path = "/admin"
114 ret = self.call_url(
115 path=self.path
116 + additional_path
117 + "/"
118 + quote(self.data[self.object_name], ""),
119 data=self.module.jsonify(self.data),
120 method="PATCH",
121 )
122 return ret
123
124 def diff(self):
125 additional_path = ""
126 if self.path == "/databaseUsers":
127 additional_path = "/admin"
128 ret = self.call_url(
129 path=self.path
130 + additional_path
131 + "/"
132 + quote(self.data[self.object_name], ""),
133 method="GET",
134 )
135
136 data_from_atlas = json.loads(self.module.jsonify(ret["data"]))
137 data_from_task = json.loads(self.module.jsonify(self.data))
138
139 diff = defaultdict(dict)
140 for key, value in data_from_atlas.items():
141 if key in data_from_task.keys() and value != data_from_task[key]:
142 diff["before"][key] = "{val}".format(val=value)
143 diff["after"][key] = "{val}".format(val=data_from_task[key])
144 return diff
145
146 def update(self, state):
147 changed = False
148 diff_result = {"before": "", "after": ""}
149 if self.exists():
150 diff_result.update({"before": "state: present\n"})
151 if state == "absent":
152 if self.module.check_mode:
153 diff_result.update({"after": "state: absent\n"})
154 self.module.exit_json(
155 changed=True,
156 object_name=self.data[self.object_name],
157 diff=diff_result,
158 )
159 else:
160 try:
161 ret = self.delete()
162 if ret["code"] == 204 or ret["code"] == 202:
163 changed = True
164 diff_result.update({"after": "state: absent\n"})
165 else:
166 self.module.fail_json(
167 msg="bad return code while deleting: %d. Error message: %s"
168 % (ret["code"], ret["error"])
169 )
170 except Exception as e:
171 self.module.fail_json(
172 msg="exception when deleting: " + str(e)
173 )
174
175 else:
176 diff_result.update(self.diff())
177 if self.module.check_mode:
178 if diff_result["after"] != "":
179 changed = True
180 self.module.exit_json(
181 changed=changed,
182 object_name=self.data[self.object_name],
183 data=self.data,
184 diff=diff_result,
185 )
186 if diff_result["after"] != "":
187 if self.path == "/whitelist":
188 ret = self.create()
189 else:
190 ret = self.modify()
191 if ret["code"] == 200 or ret["code"] == 201:
192 changed = True
193 else:
194 self.module.fail_json(
195 msg="bad return code while modifying: %d. Error message: %s"
196 % (ret["code"], ret["error"])
197 )
198
199 else:
200 diff_result.update({"before": "state: absent\n"})
201 if state == "present":
202 if self.module.check_mode:
203 changed = True
204 diff_result.update({"after": "state: created\n"})
205 else:
206 try:
207 ret = self.create()
208 if ret["code"] == 201:
209 changed = True
210 diff_result.update({"after": "state: created\n"})
211 else:
212 self.module.fail_json(
213 msg="bad return code while creating: %d. Error message: %s"
214 % (ret["code"], ret["error"])
215 )
216 except Exception as e:
217 self.module.fail_json(
218 msg="exception while creating: " + str(e)
219 )
220 return changed, diff_result