Debian Codegraph @

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