Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_timesync.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_timesync
12 short_description: Set time synchronization mode.
13 description: Set time synchronization mode.
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 mode:
20 choices:
21 - DISABLED
22 - HOST
23 - NTP
24 description:
25 - The I(time_sync_mode) enumerated type defines time synchronization modes
26 This parameter is mandatory.
27 required: true
28 type: str
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 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: Ensure we use NTP
93 vmware.vmware_rest.appliance_timesync:
94 mode: NTP
95 """
96 RETURN = r"""
97 # content generated by the update_return_section callback# task: Ensure we use NTP
98 value:
99 description: Ensure we use NTP
100 returned: On success
101 sample: NTP
102 type: str
103 """
104
105
106 # This structure describes the format of the data expected by the end-points
107 PAYLOAD_FORMAT = {
108 "set": {"query": {}, "body": {"mode": "mode"}, "path": {}}
109 } # pylint: disable=line-too-long
110
111 from ansible.module_utils.basic import env_fallback
112 import os
113
114 if os.getenv("VMWARE_ENABLE_TURBO", False):
115 try:
116 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
117 AnsibleTurboModule as AnsibleModule,
118 )
119
120 AnsibleModule.collection_name = "vmware.vmware_rest"
121 except ImportError:
122 from ansible.module_utils.basic import AnsibleModule
123 else:
124 from ansible.module_utils.basic import AnsibleModule
125
126 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
127 exists,
128 gen_args,
129 get_subdevice_type,
130 open_session,
131 prepare_payload,
132 session_timeout,
133 update_changed_flag,
134 )
135
136
137 def prepare_argument_spec():
138 argument_spec = {
139 "vcenter_hostname": dict(
140 type="str",
141 required=True,
142 fallback=(env_fallback, ["VMWARE_HOST"]),
143 ),
144 "vcenter_username": dict(
145 type="str",
146 required=True,
147 fallback=(env_fallback, ["VMWARE_USER"]),
148 ),
149 "vcenter_password": dict(
150 type="str",
151 required=True,
152 no_log=True,
153 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
154 ),
155 "vcenter_validate_certs": dict(
156 type="bool",
157 required=False,
158 default=True,
159 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
160 ),
161 "vcenter_rest_log_file": dict(
162 type="str",
163 required=False,
164 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
165 ),
166 "session_timeout": dict(
167 type="float",
168 required=False,
169 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
170 ),
171 }
172
173 argument_spec["mode"] = {
174 "required": True,
175 "type": "str",
176 "choices": ["DISABLED", "HOST", "NTP"],
177 }
178 argument_spec["state"] = {"type": "str", "choices": ["set"], "default": "set"}
179
180 return argument_spec
181
182
183 async def main():
184 required_if = list([])
185
186 module_args = prepare_argument_spec()
187 module = AnsibleModule(
188 argument_spec=module_args, required_if=required_if, supports_check_mode=False
189 )
190 if not module.params["vcenter_hostname"]:
191 module.fail_json("vcenter_hostname cannot be empty")
192 if not module.params["vcenter_username"]:
193 module.fail_json("vcenter_username cannot be empty")
194 if not module.params["vcenter_password"]:
195 module.fail_json("vcenter_password cannot be empty")
196 try:
197 session = await open_session(
198 vcenter_hostname=module.params["vcenter_hostname"],
199 vcenter_username=module.params["vcenter_username"],
200 vcenter_password=module.params["vcenter_password"],
201 validate_certs=module.params["vcenter_validate_certs"],
202 log_file=module.params["vcenter_rest_log_file"],
203 )
204 except Exception as err:
205 if hasattr(err, "get_message"):
206 module.fail_json(err.get_message())
207 else:
208 module.fail_json(str(err))
209 result = await entry_point(module, session)
210 module.exit_json(**result)
211
212
213 # template: default_module.j2
214 def build_url(params):
215 return ("https://{vcenter_hostname}" "/api/appliance/timesync").format(**params)
216
217
218 async def entry_point(module, session):
219
220 if module.params["state"] == "present":
221 if "_create" in globals():
222 operation = "create"
223 else:
224 operation = "update"
225 elif module.params["state"] == "absent":
226 operation = "delete"
227 else:
228 operation = module.params["state"]
229
230 func = globals()["_" + operation]
231
232 return await func(module.params, session)
233
234
235 async def _set(params, session):
236 _in_query_parameters = PAYLOAD_FORMAT["set"]["query"].keys()
237 payload = prepare_payload(params, PAYLOAD_FORMAT["set"])
238 subdevice_type = get_subdevice_type("/api/appliance/timesync")
239 if subdevice_type and not params[subdevice_type]:
240 _json = await exists(params, session, build_url(params))
241 if _json:
242 params[subdevice_type] = _json["id"]
243 _url = ("https://{vcenter_hostname}" "/api/appliance/timesync").format(
244 **params
245 ) + gen_args(params, _in_query_parameters)
246 async with session.get(_url, json=payload, **session_timeout(params)) as resp:
247 before = await resp.json()
248
249 async with session.put(_url, json=payload, **session_timeout(params)) as resp:
250 try:
251 if resp.headers["Content-Type"] == "application/json":
252 _json = await resp.json()
253 except KeyError:
254 _json = {}
255 if "value" not in _json: # 7.0.2
256 _json = {"value": _json}
257
258 # The PUT answer does not let us know if the resource has actually been
259 # modified
260 if resp.status < 300:
261 async with session.get(
262 _url, json=payload, **session_timeout(params)
263 ) as resp_get:
264 after = await resp_get.json()
265 if before == after:
266 return await update_changed_flag(after, resp_get.status, "get")
267 return await update_changed_flag(_json, resp.status, "set")
268
269
270 if __name__ == "__main__":
271 import asyncio
272
273 current_loop = asyncio.new_event_loop()
274 try:
275 asyncio.set_event_loop(current_loop)
276 current_loop.run_until_complete(main())
277 finally:
278 current_loop.close()