Debian Codegraph @

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