Debian Codegraph @

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