Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_networking_dns_servers.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2021, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # template: header.j2
6 # This module is autogenerated using the ansible.content_builder.
7 # See: https://github.com/ansible-community/ansible.content_builder
8
9
10 DOCUMENTATION = r"""
11 module: appliance_networking_dns_servers
12 short_description: Set the DNS server configuration
13 description: Set the DNS server configuration. If you set the mode argument to "DHCP",
14 a DHCP refresh is forced.
15 deprecated:
16 removed_in: 5.0.0
17 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
18 alternative: Use M(vmware.vmware.vcsa_settings) instead.
19 options:
20 mode:
21 choices:
22 - dhcp
23 - is_static
24 description:
25 - I(dns_server_mode) enumerated type Describes DNS Server source (DHCP,static)
26 Required with I(state=['set'])
27 type: str
28 server:
29 description:
30 - DNS server. Required with I(state=['add'])
31 type: str
32 servers:
33 description:
34 - List of the currently used DNS servers. Required with I(state=['set', 'test'])
35 elements: str
36 type: list
37 session_timeout:
38 description:
39 - 'Timeout settings for client session. '
40 - 'The maximal number of seconds for the whole operation including connection
41 establishment, request sending and response. '
42 - The default value is 300s.
43 type: float
44 version_added: 2.1.0
45 state:
46 choices:
47 - add
48 - set
49 - test
50 default: set
51 description: []
52 type: str
53 vcenter_hostname:
54 description:
55 - The hostname or IP address of the vSphere vCenter
56 - If the value is not specified in the task, the value of environment variable
57 C(VMWARE_HOST) will be used instead.
58 required: true
59 type: str
60 vcenter_password:
61 description:
62 - The vSphere vCenter password
63 - If the value is not specified in the task, the value of environment variable
64 C(VMWARE_PASSWORD) will be used instead.
65 required: true
66 type: str
67 vcenter_rest_log_file:
68 description:
69 - 'You can use this optional parameter to set the location of a log file. '
70 - 'This file will be used to record the HTTP REST interaction. '
71 - 'The file will be stored on the host that runs the module. '
72 - 'If the value is not specified in the task, the value of '
73 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
74 type: str
75 vcenter_username:
76 description:
77 - The vSphere vCenter username
78 - If the value is not specified in the task, the value of environment variable
79 C(VMWARE_USER) will be used instead.
80 required: true
81 type: str
82 vcenter_validate_certs:
83 default: true
84 description:
85 - Allows connection when SSL certificates are not valid. Set to C(false) when
86 certificates are not trusted.
87 - If the value is not specified in the task, the value of environment variable
88 C(VMWARE_VALIDATE_CERTS) will be used instead.
89 type: bool
90 author:
91 - Ansible Cloud Team (@ansible-collections)
92 version_added: 2.0.0
93 requirements:
94 - vSphere 7.0.3 or greater
95 - python >= 3.6
96 - aiohttp
97 seealso:
98 - module: vmware.vmware.vcsa_settings
99 notes:
100 - Tested on vSphere 7.0.3
101 """
102
103 EXAMPLES = r"""
104 - name: Set static DNS servers
105 vmware.vmware_rest.appliance_networking_dns_servers:
106 servers:
107 - 1.1.1.1
108 mode: is_static
109 state: set
110 register: result
111
112 - name: Add another DNS server
113 vmware.vmware_rest.appliance_networking_dns_servers:
114 server: 8.8.4.4
115 state: add
116 register: result
117
118 - name: Use the DNS servers from the DHCP
119 vmware.vmware_rest.appliance_networking_dns_servers:
120 mode: dhcp
121 servers: []
122 state: set
123 register: result
124
125 - name: Test the DNS servers
126 vmware.vmware_rest.appliance_networking_dns_servers:
127 state: test
128 servers:
129 - google.com
130 register: result
131 """
132 RETURN = r"""
133 # content generated by the update_return_section callback# task: Add another DNS server
134 value:
135 description: Add another DNS server
136 returned: On success
137 sample:
138 mode: is_static
139 servers:
140 - 1.1.1.1
141 - 192.168.123.1
142 - 8.8.4.4
143 type: dict
144 """
145
146
147 # This structure describes the format of the data expected by the end-points
148 PAYLOAD_FORMAT = {
149 "set": {"query": {}, "body": {"mode": "mode", "servers": "servers"}, "path": {}},
150 "add": {"query": {}, "body": {"server": "server"}, "path": {}},
151 "test": {"query": {}, "body": {"servers": "servers"}, "path": {}},
152 } # pylint: disable=line-too-long
153
154 from ansible.module_utils.basic import env_fallback
155 import os
156
157 if os.getenv("VMWARE_ENABLE_TURBO", False):
158 try:
159 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
160 AnsibleTurboModule as AnsibleModule,
161 )
162
163 AnsibleModule.collection_name = "vmware.vmware_rest"
164 except ImportError:
165 from ansible.module_utils.basic import AnsibleModule
166 else:
167 from ansible.module_utils.basic import AnsibleModule
168
169 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
170 exists,
171 gen_args,
172 get_subdevice_type,
173 open_session,
174 prepare_payload,
175 session_timeout,
176 update_changed_flag,
177 )
178
179
180 def prepare_argument_spec():
181 argument_spec = {
182 "vcenter_hostname": dict(
183 type="str",
184 required=True,
185 fallback=(env_fallback, ["VMWARE_HOST"]),
186 ),
187 "vcenter_username": dict(
188 type="str",
189 required=True,
190 fallback=(env_fallback, ["VMWARE_USER"]),
191 ),
192 "vcenter_password": dict(
193 type="str",
194 required=True,
195 no_log=True,
196 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
197 ),
198 "vcenter_validate_certs": dict(
199 type="bool",
200 required=False,
201 default=True,
202 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
203 ),
204 "vcenter_rest_log_file": dict(
205 type="str",
206 required=False,
207 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
208 ),
209 "session_timeout": dict(
210 type="float",
211 required=False,
212 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
213 ),
214 }
215
216 argument_spec["mode"] = {"type": "str", "choices": ["dhcp", "is_static"]}
217 argument_spec["server"] = {"type": "str"}
218 argument_spec["servers"] = {"type": "list", "elements": "str"}
219 argument_spec["state"] = {
220 "type": "str",
221 "choices": ["add", "set", "test"],
222 "default": "set",
223 }
224
225 return argument_spec
226
227
228 async def main():
229 required_if = list([])
230
231 module_args = prepare_argument_spec()
232 module = AnsibleModule(
233 argument_spec=module_args, required_if=required_if, supports_check_mode=False
234 )
235 if not module.params["vcenter_hostname"]:
236 module.fail_json("vcenter_hostname cannot be empty")
237 if not module.params["vcenter_username"]:
238 module.fail_json("vcenter_username cannot be empty")
239 if not module.params["vcenter_password"]:
240 module.fail_json("vcenter_password cannot be empty")
241 try:
242 session = await open_session(
243 vcenter_hostname=module.params["vcenter_hostname"],
244 vcenter_username=module.params["vcenter_username"],
245 vcenter_password=module.params["vcenter_password"],
246 validate_certs=module.params["vcenter_validate_certs"],
247 log_file=module.params["vcenter_rest_log_file"],
248 )
249 except Exception as err:
250 if hasattr(err, "get_message"):
251 module.fail_json(err.get_message())
252 else:
253 module.fail_json(str(err))
254 result = await entry_point(module, session)
255 module.exit_json(**result)
256
257
258 # template: default_module.j2
259 def build_url(params):
260 return (
261 "https://{vcenter_hostname}" "/api/appliance/networking/dns/servers"
262 ).format(**params)
263
264
265 async def entry_point(module, session):
266
267 if module.params["state"] == "present":
268 if "_create" in globals():
269 operation = "create"
270 else:
271 operation = "update"
272 elif module.params["state"] == "absent":
273 operation = "delete"
274 else:
275 operation = module.params["state"]
276
277 func = globals()["_" + operation]
278
279 return await func(module.params, session)
280
281
282 async def _add(params, session):
283 _in_query_parameters = PAYLOAD_FORMAT["add"]["query"].keys()
284 payload = prepare_payload(params, PAYLOAD_FORMAT["add"])
285 subdevice_type = get_subdevice_type("/api/appliance/networking/dns/servers")
286 if subdevice_type and not params[subdevice_type]:
287 _json = await exists(params, session, build_url(params))
288 if _json:
289 params[subdevice_type] = _json["id"]
290 _url = (
291 "https://{vcenter_hostname}"
292 # aa
293 "/api/appliance/networking/dns/servers"
294 ).format(**params) + gen_args(params, _in_query_parameters)
295 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
296 try:
297 if resp.headers["Content-Type"] == "application/json":
298 _json = await resp.json()
299 except KeyError:
300 _json = {}
301 if "value" not in _json: # 7.0.2
302 _json = {"value": _json}
303
304 if (
305 resp.status == 500
306 and "messages" in _json["value"]
307 and _json["value"]["messages"]
308 and "id" in _json["value"]["messages"][0]
309 and _json["value"]["messages"][0]["id"]
310 == "com.vmware.applmgmt.err_operation_failed"
311 and "args" in _json["value"]["messages"][0]
312 and "changing state RUNNING → CLOSED"
313 in _json["value"]["messages"][0]["args"][0]
314 ):
315 # vSphere 7.0.2, a network configuration changes of the appliance raise a systemd error,
316 # but the change is applied. The problem can be resolved by a yum update.
317 async with session.get(
318 _url, json=payload, **session_timeout(params)
319 ) as resp:
320 _json = {"value": await resp.json()}
321
322 return await update_changed_flag(_json, resp.status, "add")
323
324
325 async def _set(params, session):
326 _in_query_parameters = PAYLOAD_FORMAT["set"]["query"].keys()
327 payload = prepare_payload(params, PAYLOAD_FORMAT["set"])
328 subdevice_type = get_subdevice_type("/api/appliance/networking/dns/servers")
329 if subdevice_type and not params[subdevice_type]:
330 _json = await exists(params, session, build_url(params))
331 if _json:
332 params[subdevice_type] = _json["id"]
333 _url = (
334 "https://{vcenter_hostname}" "/api/appliance/networking/dns/servers"
335 ).format(**params) + gen_args(params, _in_query_parameters)
336 async with session.get(_url, json=payload, **session_timeout(params)) as resp:
337 before = await resp.json()
338
339 async with session.put(_url, json=payload, **session_timeout(params)) as resp:
340 try:
341 if resp.headers["Content-Type"] == "application/json":
342 _json = await resp.json()
343 except KeyError:
344 _json = {}
345 if "value" not in _json: # 7.0.2
346 _json = {"value": _json}
347
348 if (
349 resp.status == 500
350 and "messages" in _json["value"]
351 and _json["value"]["messages"]
352 and "id" in _json["value"]["messages"][0]
353 and _json["value"]["messages"][0]["id"]
354 == "com.vmware.applmgmt.err_operation_failed"
355 and "args" in _json["value"]["messages"][0]
356 and "changing state RUNNING → CLOSED"
357 in _json["value"]["messages"][0]["args"][0]
358 ):
359 # vSphere 7.0.2, a network configuration changes of the appliance raise a systemd error,
360 # but the change is applied. The problem can be resolved by a yum update.
361 async with session.get(
362 _url, json=payload, **session_timeout(params)
363 ) as resp:
364 _json = {"value": await resp.json()}
365
366 # The PUT answer does not let us know if the resource has actually been
367 # modified
368 if resp.status < 300:
369 async with session.get(
370 _url, json=payload, **session_timeout(params)
371 ) as resp_get:
372 after = await resp_get.json()
373 if before == after:
374 return await update_changed_flag(after, resp_get.status, "get")
375 return await update_changed_flag(_json, resp.status, "set")
376
377
378 async def _test(params, session):
379 _in_query_parameters = PAYLOAD_FORMAT["test"]["query"].keys()
380 payload = prepare_payload(params, PAYLOAD_FORMAT["test"])
381 subdevice_type = get_subdevice_type(
382 "/api/appliance/networking/dns/servers?action=test"
383 )
384 if subdevice_type and not params[subdevice_type]:
385 _json = await exists(params, session, build_url(params))
386 if _json:
387 params[subdevice_type] = _json["id"]
388 _url = (
389 "https://{vcenter_hostname}"
390 # aa
391 "/api/appliance/networking/dns/servers?action=test"
392 ).format(**params) + gen_args(params, _in_query_parameters)
393 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
394 try:
395 if resp.headers["Content-Type"] == "application/json":
396 _json = await resp.json()
397 except KeyError:
398 _json = {}
399 if "value" not in _json: # 7.0.2
400 _json = {"value": _json}
401
402 return await update_changed_flag(_json, resp.status, "test")
403
404
405 if __name__ == "__main__":
406 import asyncio
407
408 current_loop = asyncio.new_event_loop()
409 try:
410 asyncio.set_event_loop(current_loop)
411 current_loop.run_until_complete(main())
412 finally:
413 current_loop.close()