Debian Codegraph @

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