Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2018, Simon Weald <[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: memset_zone_domain
11 author: "Simon Weald (@glitchcrab)"
12 short_description: Create and delete domains in Memset DNS zones
13 notes:
14 - Zone domains can be thought of as a collection of domains, all of which share the same DNS records (in other words, they
15 point to the same IP). An API key generated using the Memset customer control panel is needed with the following minimum
16 scope - C(dns.zone_domain_create), C(dns.zone_domain_delete), C(dns.zone_domain_list).
17 - Currently this module can only create one domain at a time. Multiple domains should be created using C(loop).
18 description:
19 - Manage DNS zone domains in a Memset account.
20 extends_documentation_fragment:
21 - community.general._attributes
22 attributes:
23 check_mode:
24 support: full
25 diff_mode:
26 support: none
27 options:
28 state:
29 default: present
30 description:
31 - Indicates desired state of resource.
32 type: str
33 choices: [absent, present]
34 api_key:
35 required: true
36 description:
37 - The API key obtained from the Memset control panel.
38 type: str
39 domain:
40 required: true
41 description:
42 - The zone domain name. Ensure this value has at most 250 characters.
43 type: str
44 aliases: ['name']
45 zone:
46 required: true
47 description:
48 - The zone to add the domain to (this must already exist).
49 type: str
50 """
51
52 EXAMPLES = r"""
53 # Create the zone domain 'test.com'
54 - name: Create zone domain
55 community.general.memset_zone_domain:
56 domain: test.com
57 zone: testzone
58 state: present
59 api_key: 5eb86c9196ab03919abcf03857163741
60 delegate_to: localhost
61 """
62
63 RETURN = r"""
64 memset_api:
65 description: Domain info from the Memset API.
66 returned: when changed or state == present
67 type: complex
68 contains:
69 domain:
70 description: Domain name.
71 returned: always
72 type: str
73 sample: "example.com"
74 id:
75 description: Domain ID.
76 returned: always
77 type: str
78 sample: "b0bb1ce851aeea6feeb2dc32fe83bf9c"
79 """
80
81 from ansible.module_utils.basic import AnsibleModule
82
83 from ansible_collections.community.general.plugins.module_utils._memset import (
84 check_zone_domain,
85 get_zone_id,
86 memset_api_call,
87 )
88
89
90 def api_validation(args=None):
91 """
92 Perform some validation which will be enforced by Memset's API (see:
93 https://www.memset.com/apidocs/methods_dns.html#dns.zone_domain_create)
94 """
95 # zone domain length must be less than 250 chars
96 if len(args["domain"]) > 250:
97 stderr = "Zone domain must be less than 250 characters in length."
98 module.fail_json(failed=True, msg=stderr)
99
100
101 def check(args=None):
102 """
103 Support for running with check mode.
104 """
105 retvals = dict()
106 has_changed = False
107
108 api_method = "dns.zone_domain_list"
109 has_failed, msg, response = memset_api_call(api_key=args["api_key"], api_method=api_method)
110
111 domain_exists = check_zone_domain(data=response, domain=args["domain"])
112
113 # set changed to true if the operation would cause a change.
114 has_changed = (domain_exists and args["state"] == "absent") or (not domain_exists and args["state"] == "present")
115
116 retvals["changed"] = has_changed
117 retvals["failed"] = has_failed
118
119 return retvals
120
121
122 def create_zone_domain(args=None, zone_exists=None, zone_id=None, payload=None):
123 """
124 At this point we already know whether the containing zone exists,
125 so we just need to create the domain (or exit if it already exists).
126 """
127 has_changed, has_failed = False, False
128 msg = None
129
130 api_method = "dns.zone_domain_list"
131 _has_failed, _msg, response = memset_api_call(api_key=args["api_key"], api_method=api_method)
132
133 for zone_domain in response.json():
134 if zone_domain["domain"] == args["domain"]:
135 # zone domain already exists, nothing to change.
136 has_changed = False
137 break
138 else:
139 # we need to create the domain
140 api_method = "dns.zone_domain_create"
141 payload["domain"] = args["domain"]
142 payload["zone_id"] = zone_id
143 has_failed, msg, response = memset_api_call(api_key=args["api_key"], api_method=api_method, payload=payload)
144 if not has_failed:
145 has_changed = True
146
147 return has_failed, has_changed, msg
148
149
150 def delete_zone_domain(args=None, payload=None):
151 """
152 Deletion is pretty simple, domains are always unique so we
153 we don't need to do any sanity checking to avoid deleting the
154 wrong thing.
155 """
156 has_changed, has_failed = False, False
157 msg, memset_api = None, None
158
159 api_method = "dns.zone_domain_list"
160 _has_failed, _msg, response = memset_api_call(api_key=args["api_key"], api_method=api_method)
161
162 domain_exists = check_zone_domain(data=response, domain=args["domain"])
163
164 if domain_exists:
165 api_method = "dns.zone_domain_delete"
166 payload["domain"] = args["domain"]
167 has_failed, msg, response = memset_api_call(api_key=args["api_key"], api_method=api_method, payload=payload)
168 if not has_failed:
169 has_changed = True
170 memset_api = response.json()
171 # unset msg as we don't want to return unnecessary info to the user.
172 msg = None
173
174 return has_failed, has_changed, memset_api, msg
175
176
177 def create_or_delete_domain(args=None):
178 """
179 We need to perform some initial sanity checking and also look
180 up required info before handing it off to create or delete.
181 """
182 retvals, payload = dict(), dict()
183 has_changed, has_failed = False, False
184 msg, stderr, memset_api = None, None, None
185
186 # get the zones and check if the relevant zone exists.
187 api_method = "dns.zone_list"
188 has_failed, msg, response = memset_api_call(api_key=args["api_key"], api_method=api_method)
189
190 if has_failed:
191 # this is the first time the API is called; incorrect credentials will
192 # manifest themselves at this point so we need to ensure the user is
193 # informed of the reason.
194 retvals["failed"] = has_failed
195 retvals["msg"] = msg
196 if response.status_code is not None:
197 retvals["stderr"] = f"API returned an error: {response.status_code}"
198 else:
199 retvals["stderr"] = response.stderr
200 return retvals
201
202 zone_exists, msg, counter, zone_id = get_zone_id(zone_name=args["zone"], current_zones=response.json())
203
204 if not zone_exists:
205 # the zone needs to be unique - this isn't a requirement of Memset's API but it
206 # makes sense in the context of this module.
207 has_failed = True
208 if counter == 0:
209 stderr = f"DNS zone '{args['zone']}' does not exist, cannot create domain."
210 elif counter > 1:
211 stderr = f"{args['zone']} matches multiple zones, cannot create domain."
212
213 retvals["failed"] = has_failed
214 retvals["msg"] = stderr
215 return retvals
216
217 if args["state"] == "present":
218 has_failed, has_changed, msg = create_zone_domain(
219 args=args, zone_exists=zone_exists, zone_id=zone_id, payload=payload
220 )
221
222 if args["state"] == "absent":
223 has_failed, has_changed, memset_api, msg = delete_zone_domain(args=args, payload=payload)
224
225 retvals["changed"] = has_changed
226 retvals["failed"] = has_failed
227 for val in ["msg", "stderr", "memset_api"]:
228 if val is not None:
229 retvals[val] = eval(val)
230
231 return retvals
232
233
234 def main():
235 global module
236 module = AnsibleModule(
237 argument_spec=dict(
238 state=dict(default="present", choices=["present", "absent"], type="str"),
239 api_key=dict(required=True, type="str", no_log=True),
240 domain=dict(required=True, aliases=["name"], type="str"),
241 zone=dict(required=True, type="str"),
242 ),
243 supports_check_mode=True,
244 )
245
246 # populate the dict with the user-provided vars.
247 args = dict(module.params)
248 args["check_mode"] = module.check_mode
249
250 # validate some API-specific limitations.
251 api_validation(args=args)
252
253 if module.check_mode:
254 retvals = check(args)
255 else:
256 retvals = create_or_delete_domain(args)
257
258 # we would need to populate the return values with the API's response
259 # in several places so it is easier to do it at the end instead.
260 if not retvals["failed"]:
261 if args["state"] == "present" and not module.check_mode:
262 payload = dict()
263 payload["domain"] = args["domain"]
264 api_method = "dns.zone_domain_info"
265 _has_failed, _msg, response = memset_api_call(
266 api_key=args["api_key"], api_method=api_method, payload=payload
267 )
268 retvals["memset_api"] = response.json()
269
270 if retvals["failed"]:
271 module.fail_json(**retvals)
272 else:
273 module.exit_json(**retvals)
274
275
276 if __name__ == "__main__":
277 main()