Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_hardware_memory.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: vcenter_vm_hardware_memory
12 short_description: Updates the memory-related settings of a virtual machine.
13 description: Updates the memory-related settings of a virtual machine.
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.vm) instead.
18 options:
19 hot_add_enabled:
20 description:
21 - 'Flag indicating whether adding memory while the virtual machine is running
22 should be enabled. '
23 - ' Some guest operating systems may consume more resources or perform less
24 efficiently when they run on hardware that supports adding memory while
25 the machine is running. '
26 - ''
27 - ' This field may only be modified if the virtual machine is not powered
28 on.'
29 - ''
30 - If unset, the value is unchanged.
31 type: bool
32 session_timeout:
33 description:
34 - 'Timeout settings for client session. '
35 - 'The maximal number of seconds for the whole operation including connection
36 establishment, request sending and response. '
37 - The default value is 300s.
38 type: float
39 version_added: 2.1.0
40 size_MiB:
41 description:
42 - 'New memory size in mebibytes. '
43 - ' The supported range of memory sizes is constrained by the configured guest
44 operating system and virtual hardware version of the virtual machine. '
45 - ''
46 - ' If the virtual machine is running, this value may only be changed if I(hot_add_enabled)
47 is true, and the new memory size must satisfy the constraints specified
48 by I(hot_add_increment_size_mib) and I()'
49 - ''
50 - If unset, the value is unchanged.
51 type: int
52 state:
53 choices:
54 - present
55 default: present
56 description: []
57 type: str
58 vcenter_hostname:
59 description:
60 - The hostname or IP address of the vSphere vCenter
61 - If the value is not specified in the task, the value of environment variable
62 C(VMWARE_HOST) will be used instead.
63 required: true
64 type: str
65 vcenter_password:
66 description:
67 - The vSphere vCenter password
68 - If the value is not specified in the task, the value of environment variable
69 C(VMWARE_PASSWORD) will be used instead.
70 required: true
71 type: str
72 vcenter_rest_log_file:
73 description:
74 - 'You can use this optional parameter to set the location of a log file. '
75 - 'This file will be used to record the HTTP REST interaction. '
76 - 'The file will be stored on the host that runs the module. '
77 - 'If the value is not specified in the task, the value of '
78 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
79 type: str
80 vcenter_username:
81 description:
82 - The vSphere vCenter username
83 - If the value is not specified in the task, the value of environment variable
84 C(VMWARE_USER) will be used instead.
85 required: true
86 type: str
87 vcenter_validate_certs:
88 default: true
89 description:
90 - Allows connection when SSL certificates are not valid. Set to C(false) when
91 certificates are not trusted.
92 - If the value is not specified in the task, the value of environment variable
93 C(VMWARE_VALIDATE_CERTS) will be used instead.
94 type: bool
95 vm:
96 description:
97 - Virtual machine identifier.
98 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
99 This parameter is mandatory.
100 required: true
101 type: str
102 author:
103 - Ansible Cloud Team (@ansible-collections)
104 version_added: 0.1.0
105 requirements:
106 - vSphere 7.0.3 or greater
107 - python >= 3.6
108 - aiohttp
109 notes:
110 - Tested on vSphere 7.0.3
111 """
112
113 EXAMPLES = r"""
114 - name: Look up the VM called test_vm1 in the inventory
115 register: search_result
116 vmware.vmware_rest.vcenter_vm_info:
117 filter_names:
118 - test_vm1
119
120 - name: Collect information about a specific VM
121 vmware.vmware_rest.vcenter_vm_info:
122 vm: '{{ search_result.value[0].vm }}'
123 register: test_vm1_info
124
125 - name: Increase the memory of a VM
126 vmware.vmware_rest.vcenter_vm_hardware_memory:
127 vm: '{{ test_vm1_info.id }}'
128 size_MiB: 1080
129 register: _result
130 """
131 RETURN = r"""
132 # content generated by the update_return_section callback# task: Increase the memory of a VM
133 id:
134 description: moid of the resource
135 returned: On success
136 sample: null
137 type: dict
138 value:
139 description: Increase the memory of a VM
140 returned: On success
141 sample: {}
142 type: dict
143 """
144
145
146 # This structure describes the format of the data expected by the end-points
147 PAYLOAD_FORMAT = {
148 "update": {
149 "query": {},
150 "body": {"hot_add_enabled": "hot_add_enabled", "size_MiB": "size_MiB"},
151 "path": {"vm": "vm"},
152 }
153 } # pylint: disable=line-too-long
154
155 from ansible.module_utils.basic import env_fallback
156 import os
157
158 if os.getenv("VMWARE_ENABLE_TURBO", False):
159 try:
160 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
161 AnsibleTurboModule as AnsibleModule,
162 )
163
164 AnsibleModule.collection_name = "vmware.vmware_rest"
165 except ImportError:
166 from ansible.module_utils.basic import AnsibleModule
167 else:
168 from ansible.module_utils.basic import AnsibleModule
169
170 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
171 open_session,
172 prepare_payload,
173 session_timeout,
174 update_changed_flag,
175 )
176
177
178 def prepare_argument_spec():
179 argument_spec = {
180 "vcenter_hostname": dict(
181 type="str",
182 required=True,
183 fallback=(env_fallback, ["VMWARE_HOST"]),
184 ),
185 "vcenter_username": dict(
186 type="str",
187 required=True,
188 fallback=(env_fallback, ["VMWARE_USER"]),
189 ),
190 "vcenter_password": dict(
191 type="str",
192 required=True,
193 no_log=True,
194 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
195 ),
196 "vcenter_validate_certs": dict(
197 type="bool",
198 required=False,
199 default=True,
200 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
201 ),
202 "vcenter_rest_log_file": dict(
203 type="str",
204 required=False,
205 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
206 ),
207 "session_timeout": dict(
208 type="float",
209 required=False,
210 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
211 ),
212 }
213
214 argument_spec["hot_add_enabled"] = {"type": "bool"}
215 argument_spec["size_MiB"] = {"type": "int"}
216 argument_spec["state"] = {
217 "type": "str",
218 "choices": ["present"],
219 "default": "present",
220 }
221 argument_spec["vm"] = {"required": True, "type": "str"}
222
223 return argument_spec
224
225
226 async def main():
227 required_if = list([])
228
229 module_args = prepare_argument_spec()
230 module = AnsibleModule(
231 argument_spec=module_args, required_if=required_if, supports_check_mode=False
232 )
233 if not module.params["vcenter_hostname"]:
234 module.fail_json("vcenter_hostname cannot be empty")
235 if not module.params["vcenter_username"]:
236 module.fail_json("vcenter_username cannot be empty")
237 if not module.params["vcenter_password"]:
238 module.fail_json("vcenter_password cannot be empty")
239 try:
240 session = await open_session(
241 vcenter_hostname=module.params["vcenter_hostname"],
242 vcenter_username=module.params["vcenter_username"],
243 vcenter_password=module.params["vcenter_password"],
244 validate_certs=module.params["vcenter_validate_certs"],
245 log_file=module.params["vcenter_rest_log_file"],
246 )
247 except Exception as err:
248 if hasattr(err, "get_message"):
249 module.fail_json(err.get_message())
250 else:
251 module.fail_json(str(err))
252 result = await entry_point(module, session)
253 module.exit_json(**result)
254
255
256 # template: default_module.j2
257 def build_url(params):
258 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/memory").format(
259 **params
260 )
261
262
263 async def entry_point(module, session):
264
265 if module.params["state"] == "present":
266 if "_create" in globals():
267 operation = "create"
268 else:
269 operation = "update"
270 elif module.params["state"] == "absent":
271 operation = "delete"
272 else:
273 operation = module.params["state"]
274
275 func = globals()["_" + operation]
276
277 return await func(module.params, session)
278
279
280 async def _update(params, session):
281 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
282 _url = ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/hardware/memory").format(
283 **params
284 )
285 async with session.get(_url, **session_timeout(params)) as resp:
286 _json = await resp.json()
287 if "value" in _json:
288 value = _json["value"]
289 else: # 7.0.2 and greater
290 value = _json
291 for k, v in value.items():
292 if k in payload:
293 if isinstance(payload[k], dict) and isinstance(v, dict):
294 to_delete = True
295 for _k in list(payload[k].keys()):
296 if payload[k][_k] != v.get(_k):
297 to_delete = False
298 if to_delete:
299 del payload[k]
300 elif payload[k] == v:
301 del payload[k]
302 elif payload[k] == {}:
303 del payload[k]
304
305 if payload == {} or payload == {"spec": {}}:
306 # Nothing has changed
307 if "value" not in _json: # 7.0.2
308 _json = {"value": _json}
309 _json["id"] = params.get("None")
310 return await update_changed_flag(_json, resp.status, "get")
311 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
312 try:
313 if resp.headers["Content-Type"] == "application/json":
314 _json = await resp.json()
315 except KeyError:
316 _json = {}
317 if "value" not in _json: # 7.0.2
318 _json = {"value": _json}
319
320 # e.g: content_configuration
321 if not _json and resp.status == 204:
322 async with session.get(_url, **session_timeout(params)) as resp_get:
323 _json_get = await resp_get.json()
324 if _json_get:
325 _json = _json_get
326
327 _json["id"] = params.get("None")
328 return await update_changed_flag(_json, resp.status, "update")
329
330
331 if __name__ == "__main__":
332 import asyncio
333
334 current_loop = asyncio.new_event_loop()
335 try:
336 asyncio.set_event_loop(current_loop)
337 current_loop.run_until_complete(main())
338 finally:
339 current_loop.close()