Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_networking_dns_domains.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_domains
12 short_description: Set DNS search domains.
13 description: Set DNS search domains.
14 deprecated:
15 removed_in: 5.0.0
16 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
17 alternative: Use M(vmware.vmware.vcsa_settings) instead.
18 options:
19 domain:
20 description:
21 - Domain to add. Required with I(state=['add'])
22 type: str
23 domains:
24 description:
25 - List of domains. Required with I(state=['set'])
26 elements: str
27 type: list
28 session_timeout:
29 description:
30 - 'Timeout settings for client session. '
31 - 'The maximal number of seconds for the whole operation including connection
32 establishment, request sending and response. '
33 - The default value is 300s.
34 type: float
35 version_added: 2.1.0
36 state:
37 choices:
38 - add
39 - set
40 default: set
41 description: []
42 type: str
43 vcenter_hostname:
44 description:
45 - The hostname or IP address of the vSphere vCenter
46 - If the value is not specified in the task, the value of environment variable
47 C(VMWARE_HOST) will be used instead.
48 required: true
49 type: str
50 vcenter_password:
51 description:
52 - The vSphere vCenter password
53 - If the value is not specified in the task, the value of environment variable
54 C(VMWARE_PASSWORD) will be used instead.
55 required: true
56 type: str
57 vcenter_rest_log_file:
58 description:
59 - 'You can use this optional parameter to set the location of a log file. '
60 - 'This file will be used to record the HTTP REST interaction. '
61 - 'The file will be stored on the host that runs the module. '
62 - 'If the value is not specified in the task, the value of '
63 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
64 type: str
65 vcenter_username:
66 description:
67 - The vSphere vCenter username
68 - If the value is not specified in the task, the value of environment variable
69 C(VMWARE_USER) will be used instead.
70 required: true
71 type: str
72 vcenter_validate_certs:
73 default: true
74 description:
75 - Allows connection when SSL certificates are not valid. Set to C(false) when
76 certificates are not trusted.
77 - If the value is not specified in the task, the value of environment variable
78 C(VMWARE_VALIDATE_CERTS) will be used instead.
79 type: bool
80 author:
81 - Ansible Cloud Team (@ansible-collections)
82 version_added: 2.0.0
83 requirements:
84 - vSphere 7.0.3 or greater
85 - python >= 3.6
86 - aiohttp
87 notes:
88 - Tested on vSphere 7.0.3
89 """
90
91 EXAMPLES = r"""
92 - name: Update the domain configuration
93 vmware.vmware_rest.appliance_networking_dns_domains:
94 domains:
95 - foobar
96 register: result
97
98 - name: Add another domain configuration
99 vmware.vmware_rest.appliance_networking_dns_domains:
100 domain: barfoo
101 state: add
102 register: result
103 """
104 RETURN = r"""
105 # content generated by the update_return_section callback# task: Add another domain configuration
106 value:
107 description: Add another domain configuration
108 returned: On success
109 sample: {}
110 type: dict
111 """
112
113
114 # This structure describes the format of the data expected by the end-points
115 PAYLOAD_FORMAT = {
116 "set": {"query": {}, "body": {"domains": "domains"}, "path": {}},
117 "add": {"query": {}, "body": {"domain": "domain"}, "path": {}},
118 } # pylint: disable=line-too-long
119
120 from ansible.module_utils.basic import env_fallback
121 import os
122
123 if os.getenv("VMWARE_ENABLE_TURBO", False):
124 try:
125 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
126 AnsibleTurboModule as AnsibleModule,
127 )
128
129 AnsibleModule.collection_name = "vmware.vmware_rest"
130 except ImportError:
131 from ansible.module_utils.basic import AnsibleModule
132 else:
133 from ansible.module_utils.basic import AnsibleModule
134
135 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
136 exists,
137 gen_args,
138 get_subdevice_type,
139 open_session,
140 prepare_payload,
141 session_timeout,
142 update_changed_flag,
143 )
144
145
146 def prepare_argument_spec():
147 argument_spec = {
148 "vcenter_hostname": dict(
149 type="str",
150 required=True,
151 fallback=(env_fallback, ["VMWARE_HOST"]),
152 ),
153 "vcenter_username": dict(
154 type="str",
155 required=True,
156 fallback=(env_fallback, ["VMWARE_USER"]),
157 ),
158 "vcenter_password": dict(
159 type="str",
160 required=True,
161 no_log=True,
162 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
163 ),
164 "vcenter_validate_certs": dict(
165 type="bool",
166 required=False,
167 default=True,
168 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
169 ),
170 "vcenter_rest_log_file": dict(
171 type="str",
172 required=False,
173 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
174 ),
175 "session_timeout": dict(
176 type="float",
177 required=False,
178 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
179 ),
180 }
181
182 argument_spec["domain"] = {"type": "str"}
183 argument_spec["domains"] = {"type": "list", "elements": "str"}
184 argument_spec["state"] = {
185 "type": "str",
186 "choices": ["add", "set"],
187 "default": "set",
188 }
189
190 return argument_spec
191
192
193 async def main():
194 required_if = list([])
195
196 module_args = prepare_argument_spec()
197 module = AnsibleModule(
198 argument_spec=module_args, required_if=required_if, supports_check_mode=False
199 )
200 if not module.params["vcenter_hostname"]:
201 module.fail_json("vcenter_hostname cannot be empty")
202 if not module.params["vcenter_username"]:
203 module.fail_json("vcenter_username cannot be empty")
204 if not module.params["vcenter_password"]:
205 module.fail_json("vcenter_password cannot be empty")
206 try:
207 session = await open_session(
208 vcenter_hostname=module.params["vcenter_hostname"],
209 vcenter_username=module.params["vcenter_username"],
210 vcenter_password=module.params["vcenter_password"],
211 validate_certs=module.params["vcenter_validate_certs"],
212 log_file=module.params["vcenter_rest_log_file"],
213 )
214 except Exception as err:
215 if hasattr(err, "get_message"):
216 module.fail_json(err.get_message())
217 else:
218 module.fail_json(str(err))
219 result = await entry_point(module, session)
220 module.exit_json(**result)
221
222
223 # template: default_module.j2
224 def build_url(params):
225 return (
226 "https://{vcenter_hostname}" "/api/appliance/networking/dns/domains"
227 ).format(**params)
228
229
230 async def entry_point(module, session):
231
232 if module.params["state"] == "present":
233 if "_create" in globals():
234 operation = "create"
235 else:
236 operation = "update"
237 elif module.params["state"] == "absent":
238 operation = "delete"
239 else:
240 operation = module.params["state"]
241
242 func = globals()["_" + operation]
243
244 return await func(module.params, session)
245
246
247 async def _add(params, session):
248 _in_query_parameters = PAYLOAD_FORMAT["add"]["query"].keys()
249 payload = prepare_payload(params, PAYLOAD_FORMAT["add"])
250 subdevice_type = get_subdevice_type("/api/appliance/networking/dns/domains")
251 if subdevice_type and not params[subdevice_type]:
252 _json = await exists(params, session, build_url(params))
253 if _json:
254 params[subdevice_type] = _json["id"]
255 _url = (
256 "https://{vcenter_hostname}"
257 # aa
258 "/api/appliance/networking/dns/domains"
259 ).format(**params) + gen_args(params, _in_query_parameters)
260 async with session.post(_url, json=payload, **session_timeout(params)) as resp:
261 try:
262 if resp.headers["Content-Type"] == "application/json":
263 _json = await resp.json()
264 except KeyError:
265 _json = {}
266 if "value" not in _json: # 7.0.2
267 _json = {"value": _json}
268
269 return await update_changed_flag(_json, resp.status, "add")
270
271
272 async def _set(params, session):
273 _in_query_parameters = PAYLOAD_FORMAT["set"]["query"].keys()
274 payload = prepare_payload(params, PAYLOAD_FORMAT["set"])
275 subdevice_type = get_subdevice_type("/api/appliance/networking/dns/domains")
276 if subdevice_type and not params[subdevice_type]:
277 _json = await exists(params, session, build_url(params))
278 if _json:
279 params[subdevice_type] = _json["id"]
280 _url = (
281 "https://{vcenter_hostname}" "/api/appliance/networking/dns/domains"
282 ).format(**params) + gen_args(params, _in_query_parameters)
283 async with session.get(_url, json=payload, **session_timeout(params)) as resp:
284 before = await resp.json()
285
286 async with session.put(_url, json=payload, **session_timeout(params)) as resp:
287 try:
288 if resp.headers["Content-Type"] == "application/json":
289 _json = await resp.json()
290 except KeyError:
291 _json = {}
292 if "value" not in _json: # 7.0.2
293 _json = {"value": _json}
294
295 # The PUT answer does not let us know if the resource has actually been
296 # modified
297 if resp.status < 300:
298 async with session.get(
299 _url, json=payload, **session_timeout(params)
300 ) as resp_get:
301 after = await resp_get.json()
302 if before == after:
303 return await update_changed_flag(after, resp_get.status, "get")
304 return await update_changed_flag(_json, resp.status, "set")
305
306
307 if __name__ == "__main__":
308 import asyncio
309
310 current_loop = asyncio.new_event_loop()
311 try:
312 asyncio.set_event_loop(current_loop)
313 current_loop.run_until_complete(main())
314 finally:
315 current_loop.close()