Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/appliance_access_shell.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_access_shell
12 short_description: Set enabled state of BASH, that is, access to BASH from within
13 the controlled CLI.
14 description: Set enabled state of BASH, that is, access to BASH from within the controlled
15 CLI.
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 enabled:
22 description:
23 - Enabled can be set to true or false This parameter is mandatory.
24 required: true
25 type: bool
26 session_timeout:
27 description:
28 - 'Timeout settings for client session. '
29 - 'The maximal number of seconds for the whole operation including connection
30 establishment, request sending and response. '
31 - The default value is 300s.
32 type: float
33 version_added: 2.1.0
34 state:
35 choices:
36 - set
37 default: set
38 description: []
39 type: str
40 timeout:
41 description:
42 - The timeout (in seconds) specifies how long you enable the Shell access.
43 The maximum timeout is 86400 seconds(1 day). This parameter is mandatory.
44 required: true
45 type: int
46 vcenter_hostname:
47 description:
48 - The hostname or IP address of the vSphere vCenter
49 - If the value is not specified in the task, the value of environment variable
50 C(VMWARE_HOST) will be used instead.
51 required: true
52 type: str
53 vcenter_password:
54 description:
55 - The vSphere vCenter password
56 - If the value is not specified in the task, the value of environment variable
57 C(VMWARE_PASSWORD) will be used instead.
58 required: true
59 type: str
60 vcenter_rest_log_file:
61 description:
62 - 'You can use this optional parameter to set the location of a log file. '
63 - 'This file will be used to record the HTTP REST interaction. '
64 - 'The file will be stored on the host that runs the module. '
65 - 'If the value is not specified in the task, the value of '
66 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
67 type: str
68 vcenter_username:
69 description:
70 - The vSphere vCenter username
71 - If the value is not specified in the task, the value of environment variable
72 C(VMWARE_USER) will be used instead.
73 required: true
74 type: str
75 vcenter_validate_certs:
76 default: true
77 description:
78 - Allows connection when SSL certificates are not valid. Set to C(false) when
79 certificates are not trusted.
80 - If the value is not specified in the task, the value of environment variable
81 C(VMWARE_VALIDATE_CERTS) will be used instead.
82 type: bool
83 author:
84 - Ansible Cloud Team (@ansible-collections)
85 version_added: 2.0.0
86 requirements:
87 - vSphere 7.0.3 or greater
88 - python >= 3.6
89 - aiohttp
90 notes:
91 - Tested on vSphere 7.0.3
92 """
93
94 EXAMPLES = r"""
95 - name: Disable the Shell
96 vmware.vmware_rest.appliance_access_shell:
97 enabled: false
98 timeout: 600
99
100 - name: Enable the Shell with a timeout
101 vmware.vmware_rest.appliance_access_shell:
102 enabled: true
103 timeout: 600
104 register: result
105 """
106 RETURN = r"""
107 # content generated by the update_return_section callback# task: Disable the Shell
108 value:
109 description: Disable the Shell
110 returned: On success
111 sample:
112 enabled: 0
113 timeout: 0
114 type: dict
115 """
116
117
118 # This structure describes the format of the data expected by the end-points
119 PAYLOAD_FORMAT = {
120 "set": {
121 "query": {},
122 "body": {"enabled": "enabled", "timeout": "timeout"},
123 "path": {},
124 }
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["enabled"] = {"required": True, "type": "bool"}
190 argument_spec["state"] = {"type": "str", "choices": ["set"], "default": "set"}
191 argument_spec["timeout"] = {"required": True, "type": "int"}
192
193 return argument_spec
194
195
196 async def main():
197 required_if = list([])
198
199 module_args = prepare_argument_spec()
200 module = AnsibleModule(
201 argument_spec=module_args, required_if=required_if, supports_check_mode=False
202 )
203 if not module.params["vcenter_hostname"]:
204 module.fail_json("vcenter_hostname cannot be empty")
205 if not module.params["vcenter_username"]:
206 module.fail_json("vcenter_username cannot be empty")
207 if not module.params["vcenter_password"]:
208 module.fail_json("vcenter_password cannot be empty")
209 try:
210 session = await open_session(
211 vcenter_hostname=module.params["vcenter_hostname"],
212 vcenter_username=module.params["vcenter_username"],
213 vcenter_password=module.params["vcenter_password"],
214 validate_certs=module.params["vcenter_validate_certs"],
215 log_file=module.params["vcenter_rest_log_file"],
216 )
217 except Exception as err:
218 if hasattr(err, "get_message"):
219 module.fail_json(err.get_message())
220 else:
221 module.fail_json(str(err))
222 result = await entry_point(module, session)
223 module.exit_json(**result)
224
225
226 # template: default_module.j2
227 def build_url(params):
228 return ("https://{vcenter_hostname}" "/api/appliance/access/shell").format(**params)
229
230
231 async def entry_point(module, session):
232
233 if module.params["state"] == "present":
234 if "_create" in globals():
235 operation = "create"
236 else:
237 operation = "update"
238 elif module.params["state"] == "absent":
239 operation = "delete"
240 else:
241 operation = module.params["state"]
242
243 func = globals()["_" + operation]
244
245 return await func(module.params, session)
246
247
248 async def _set(params, session):
249 _in_query_parameters = PAYLOAD_FORMAT["set"]["query"].keys()
250 payload = prepare_payload(params, PAYLOAD_FORMAT["set"])
251 subdevice_type = get_subdevice_type("/api/appliance/access/shell")
252 if subdevice_type and not params[subdevice_type]:
253 _json = await exists(params, session, build_url(params))
254 if _json:
255 params[subdevice_type] = _json["id"]
256 _url = ("https://{vcenter_hostname}" "/api/appliance/access/shell").format(
257 **params
258 ) + gen_args(params, _in_query_parameters)
259 async with session.get(_url, json=payload, **session_timeout(params)) as resp:
260 before = await resp.json()
261
262 async with session.put(_url, json=payload, **session_timeout(params)) as resp:
263 try:
264 if resp.headers["Content-Type"] == "application/json":
265 _json = await resp.json()
266 except KeyError:
267 _json = {}
268 if "value" not in _json: # 7.0.2
269 _json = {"value": _json}
270
271 # The PUT answer does not let us know if the resource has actually been
272 # modified
273 if resp.status < 300:
274 async with session.get(
275 _url, json=payload, **session_timeout(params)
276 ) as resp_get:
277 after = await resp_get.json()
278 if before == after:
279 return await update_changed_flag(after, resp_get.status, "get")
280 return await update_changed_flag(_json, resp.status, "set")
281
282
283 if __name__ == "__main__":
284 import asyncio
285
286 current_loop = asyncio.new_event_loop()
287 try:
288 asyncio.set_event_loop(current_loop)
289 current_loop.run_until_complete(main())
290 finally:
291 current_loop.close()