Debian Codegraph @

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