summaryrefslogtreecommitdiffstats
path: root/ansible_collections/community/mongodb/plugins/module_utils/mongodb_atlas.py
blob: a32f3e1dedb38156b2916c3048a73799a420ae1d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# -*- coding: utf-8 -*-

from __future__ import absolute_import, division, print_function

__metaclass__ = type

import json
from collections import defaultdict

from ansible.module_utils.urls import fetch_url

try:
    from urllib import quote
except ImportError:
    # noinspection PyCompatibility, PyUnresolvedReferences
    from urllib.parse import (
        quote,
    )  # pylint: disable=locally-disabled, import-error, no-name-in-module


class AtlasAPIObject:
    module = None

    def __init__(
        self, module, object_name, group_id, path, data, data_is_array=False
    ):
        self.module = module
        self.path = path
        self.data = data
        self.group_id = group_id
        self.object_name = object_name
        self.data_is_array = data_is_array

        self.module.params["url_username"] = self.module.params["api_username"]
        self.module.params["url_password"] = self.module.params["api_password"]

    def call_url(self, path, data="", method="GET"):
        headers = {
            "Accept": "application/json",
            "Content-Type": "application/json",
        }

        if self.data_is_array and data != "":
            data = "[" + data + "]"

        url = (
            "https://cloud.mongodb.com/api/atlas/v1.0/groups/"
            + self.group_id
            + path
        )
        rsp, info = fetch_url(
            module=self.module,
            url=url,
            data=data,
            headers=headers,
            method=method,
        )

        content = ""
        error = ""
        if rsp and info["status"] not in (204, 404):
            content = json.loads(rsp.read())
        if info["status"] >= 400:
            try:
                content = json.loads(info["body"])
                error = content["reason"]
                if "detail" in content:
                    error += ". Detail: " + content["detail"]
            except ValueError:
                error = info["msg"]
        if info["status"] < 0:
            error = info["msg"]
        return {"code": info["status"], "data": content, "error": error}

    def exists(self):
        additional_path = ""
        if self.path == "/databaseUsers":
            additional_path = "/admin"
        ret = self.call_url(
            path=self.path
            + additional_path
            + "/"
            + quote(self.data[self.object_name], "")
        )
        if ret["code"] == 200:
            return True
        return False

    def create(self):
        ret = self.call_url(
            path=self.path,
            data=self.module.jsonify(self.data),
            method="POST",
        )
        return ret

    def delete(self):
        additional_path = ""
        if self.path == "/databaseUsers":
            additional_path = "/admin"
        ret = self.call_url(
            path=self.path
            + additional_path
            + "/"
            + quote(self.data[self.object_name], ""),
            method="DELETE",
        )
        return ret

    def modify(self):
        additional_path = ""
        if self.path == "/databaseUsers":
            additional_path = "/admin"
        ret = self.call_url(
            path=self.path
            + additional_path
            + "/"
            + quote(self.data[self.object_name], ""),
            data=self.module.jsonify(self.data),
            method="PATCH",
        )
        return ret

    def diff(self):
        additional_path = ""
        if self.path == "/databaseUsers":
            additional_path = "/admin"
        ret = self.call_url(
            path=self.path
            + additional_path
            + "/"
            + quote(self.data[self.object_name], ""),
            method="GET",
        )

        data_from_atlas = json.loads(self.module.jsonify(ret["data"]))
        data_from_task = json.loads(self.module.jsonify(self.data))

        diff = defaultdict(dict)
        for key, value in data_from_atlas.items():
            if key in data_from_task.keys() and value != data_from_task[key]:
                diff["before"][key] = "{val}".format(val=value)
                diff["after"][key] = "{val}".format(val=data_from_task[key])
        return diff

    def update(self, state):
        changed = False
        diff_result = {"before": "", "after": ""}
        if self.exists():
            diff_result.update({"before": "state: present\n"})
            if state == "absent":
                if self.module.check_mode:
                    diff_result.update({"after": "state: absent\n"})
                    self.module.exit_json(
                        changed=True,
                        object_name=self.data[self.object_name],
                        diff=diff_result,
                    )
                else:
                    try:
                        ret = self.delete()
                        if ret["code"] == 204 or ret["code"] == 202:
                            changed = True
                            diff_result.update({"after": "state: absent\n"})
                        else:
                            self.module.fail_json(
                                msg="bad return code while deleting: %d. Error message: %s"
                                % (ret["code"], ret["error"])
                            )
                    except Exception as e:
                        self.module.fail_json(
                            msg="exception when deleting: " + str(e)
                        )

            else:
                diff_result.update(self.diff())
                if self.module.check_mode:
                    if diff_result["after"] != "":
                        changed = True
                    self.module.exit_json(
                        changed=changed,
                        object_name=self.data[self.object_name],
                        data=self.data,
                        diff=diff_result,
                    )
                if diff_result["after"] != "":
                    if self.path == "/whitelist":
                        ret = self.create()
                    else:
                        ret = self.modify()
                    if ret["code"] == 200 or ret["code"] == 201:
                        changed = True
                    else:
                        self.module.fail_json(
                            msg="bad return code while modifying: %d. Error message: %s"
                            % (ret["code"], ret["error"])
                        )

        else:
            diff_result.update({"before": "state: absent\n"})
            if state == "present":
                if self.module.check_mode:
                    changed = True
                    diff_result.update({"after": "state: created\n"})
                else:
                    try:
                        ret = self.create()
                        if ret["code"] == 201:
                            changed = True
                            diff_result.update({"after": "state: created\n"})
                        else:
                            self.module.fail_json(
                                msg="bad return code while creating: %d. Error message: %s"
                                % (ret["code"], ret["error"])
                            )
                    except Exception as e:
                        self.module.fail_json(
                            msg="exception while creating: " + str(e)
                        )
        return changed, diff_result