Debian Codegraph @

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