Debian Codegraph @

ansible_collections/vmware/vmware_rest/plugins/modules/vcenter_vm_storage_policy.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_storage_policy
12 short_description: Updates the storage policy configuration of a virtual machine and/or
13 its associated virtual hard disks.
14 description: Updates the storage policy configuration of a virtual machine and/or
15 its associated virtual hard disks.
16 options:
17 disks:
18 description:
19 - Storage policy or policies to be used when reconfiguring virtual machine
20 diks.
21 - if unset the current storage policy is retained.
22 - 'When clients pass a value of this structure as a parameter, the key in
23 the field map must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_hardware_disk). '
24 type: dict
25 session_timeout:
26 description:
27 - 'Timeout settings for client session. '
28 - 'The maximal number of seconds for the whole operation including connection
29 establishment, request sending and response. '
30 - The default value is 300s.
31 type: float
32 version_added: 2.1.0
33 state:
34 choices:
35 - present
36 default: present
37 description: []
38 type: str
39 vcenter_hostname:
40 description:
41 - The hostname or IP address of the vSphere vCenter
42 - If the value is not specified in the task, the value of environment variable
43 C(VMWARE_HOST) will be used instead.
44 required: true
45 type: str
46 vcenter_password:
47 description:
48 - The vSphere vCenter password
49 - If the value is not specified in the task, the value of environment variable
50 C(VMWARE_PASSWORD) will be used instead.
51 required: true
52 type: str
53 vcenter_rest_log_file:
54 description:
55 - 'You can use this optional parameter to set the location of a log file. '
56 - 'This file will be used to record the HTTP REST interaction. '
57 - 'The file will be stored on the host that runs the module. '
58 - 'If the value is not specified in the task, the value of '
59 - environment variable C(VMWARE_REST_LOG_FILE) will be used instead.
60 type: str
61 vcenter_username:
62 description:
63 - The vSphere vCenter username
64 - If the value is not specified in the task, the value of environment variable
65 C(VMWARE_USER) will be used instead.
66 required: true
67 type: str
68 vcenter_validate_certs:
69 default: true
70 description:
71 - Allows connection when SSL certificates are not valid. Set to C(false) when
72 certificates are not trusted.
73 - If the value is not specified in the task, the value of environment variable
74 C(VMWARE_VALIDATE_CERTS) will be used instead.
75 type: bool
76 vm:
77 description:
78 - Virtual machine identifier.
79 - The parameter must be the id of a resource returned by M(vmware.vmware_rest.vcenter_vm_info).
80 This parameter is mandatory.
81 required: true
82 type: str
83 vm_home:
84 description:
85 - Storage policy to be used when reconfiguring the virtual machine home.
86 - if unset the current storage policy is retained. This parameter is mandatory.
87 - 'Valid attributes are:'
88 - ' - C(type) (str): This option defines the choices for how to specify the
89 policy to be associated with the virtual machine home''s directory. ([''present''])'
90 - ' This key is required with [''present''].'
91 - ' - Accepted values:'
92 - ' - USE_DEFAULT_POLICY'
93 - ' - USE_SPECIFIED_POLICY'
94 - ' - C(policy) (str): Storage Policy identification.'
95 - This field is optional and it is only relevant when the value of I(type)
96 is USE_SPECIFIED_POLICY.
97 - When clients pass a value of this structure as a parameter, the field must
98 be the id of a resource returned by M(vmware.vmware_rest.vcenter_storage_policies_info).
99 (['present'])
100 required: true
101 type: dict
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: Prepare the disk policy dict
126 ansible.builtin.set_fact:
127 vm_disk_policy: "{{ {} | combine({ my_new_disk.id: {'policy': my_storage_policy.policy, 'type': 'USE_SPECIFIED_POLICY'} }) }}"
128
129 - name: Adjust VM storage policy
130 vmware.vmware_rest.vcenter_vm_storage_policy:
131 vm: '{{ test_vm1_info.id }}'
132 vm_home:
133 type: USE_DEFAULT_POLICY
134 disks: '{{ vm_disk_policy }}'
135 register: _result
136 """
137 RETURN = r"""
138 # content generated by the update_return_section callback# task: Adjust VM storage policy
139 id:
140 description: moid of the resource
141 returned: On success
142 sample: null
143 type: dict
144 value:
145 description: Adjust VM storage policy
146 returned: On success
147 sample: {}
148 type: dict
149 """
150
151
152 # This structure describes the format of the data expected by the end-points
153 PAYLOAD_FORMAT = {
154 "update": {
155 "query": {},
156 "body": {"disks": "disks", "vm_home": "vm_home"},
157 "path": {"vm": "vm"},
158 }
159 } # pylint: disable=line-too-long
160
161 from ansible.module_utils.basic import env_fallback
162 import os
163
164 if os.getenv("VMWARE_ENABLE_TURBO", False):
165 try:
166 from ansible_collections.cloud.common.plugins.module_utils.turbo.module import (
167 AnsibleTurboModule as AnsibleModule,
168 )
169
170 AnsibleModule.collection_name = "vmware.vmware_rest"
171 except ImportError:
172 from ansible.module_utils.basic import AnsibleModule
173 else:
174 from ansible.module_utils.basic import AnsibleModule
175
176 from ansible_collections.vmware.vmware_rest.plugins.module_utils.vmware_rest import (
177 open_session,
178 prepare_payload,
179 session_timeout,
180 update_changed_flag,
181 )
182
183
184 def prepare_argument_spec():
185 argument_spec = {
186 "vcenter_hostname": dict(
187 type="str",
188 required=True,
189 fallback=(env_fallback, ["VMWARE_HOST"]),
190 ),
191 "vcenter_username": dict(
192 type="str",
193 required=True,
194 fallback=(env_fallback, ["VMWARE_USER"]),
195 ),
196 "vcenter_password": dict(
197 type="str",
198 required=True,
199 no_log=True,
200 fallback=(env_fallback, ["VMWARE_PASSWORD"]),
201 ),
202 "vcenter_validate_certs": dict(
203 type="bool",
204 required=False,
205 default=True,
206 fallback=(env_fallback, ["VMWARE_VALIDATE_CERTS"]),
207 ),
208 "vcenter_rest_log_file": dict(
209 type="str",
210 required=False,
211 fallback=(env_fallback, ["VMWARE_REST_LOG_FILE"]),
212 ),
213 "session_timeout": dict(
214 type="float",
215 required=False,
216 fallback=(env_fallback, ["VMWARE_SESSION_TIMEOUT"]),
217 ),
218 }
219
220 argument_spec["disks"] = {"type": "dict"}
221 argument_spec["state"] = {
222 "type": "str",
223 "choices": ["present"],
224 "default": "present",
225 }
226 argument_spec["vm"] = {"required": True, "type": "str"}
227 argument_spec["vm_home"] = {"required": True, "type": "dict"}
228
229 return argument_spec
230
231
232 async def main():
233 required_if = list([])
234
235 module_args = prepare_argument_spec()
236 module = AnsibleModule(
237 argument_spec=module_args, required_if=required_if, supports_check_mode=False
238 )
239 if not module.params["vcenter_hostname"]:
240 module.fail_json("vcenter_hostname cannot be empty")
241 if not module.params["vcenter_username"]:
242 module.fail_json("vcenter_username cannot be empty")
243 if not module.params["vcenter_password"]:
244 module.fail_json("vcenter_password cannot be empty")
245 try:
246 session = await open_session(
247 vcenter_hostname=module.params["vcenter_hostname"],
248 vcenter_username=module.params["vcenter_username"],
249 vcenter_password=module.params["vcenter_password"],
250 validate_certs=module.params["vcenter_validate_certs"],
251 log_file=module.params["vcenter_rest_log_file"],
252 )
253 except Exception as err:
254 if hasattr(err, "get_message"):
255 module.fail_json(err.get_message())
256 else:
257 module.fail_json(str(err))
258 result = await entry_point(module, session)
259 module.exit_json(**result)
260
261
262 # template: default_module.j2
263 def build_url(params):
264 return ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/storage/policy").format(
265 **params
266 )
267
268
269 async def entry_point(module, session):
270
271 if module.params["state"] == "present":
272 if "_create" in globals():
273 operation = "create"
274 else:
275 operation = "update"
276 elif module.params["state"] == "absent":
277 operation = "delete"
278 else:
279 operation = module.params["state"]
280
281 func = globals()["_" + operation]
282
283 return await func(module.params, session)
284
285
286 async def _update(params, session):
287 payload = prepare_payload(params, PAYLOAD_FORMAT["update"])
288 _url = ("https://{vcenter_hostname}" "/api/vcenter/vm/{vm}/storage/policy").format(
289 **params
290 )
291 async with session.get(_url, **session_timeout(params)) as resp:
292 _json = await resp.json()
293 if "value" in _json:
294 value = _json["value"]
295 else: # 7.0.2 and greater
296 value = _json
297 for k, v in value.items():
298 if k in payload:
299 if isinstance(payload[k], dict) and isinstance(v, dict):
300 to_delete = True
301 for _k in list(payload[k].keys()):
302 if payload[k][_k] != v.get(_k):
303 to_delete = False
304 if to_delete:
305 del payload[k]
306 elif payload[k] == v:
307 del payload[k]
308 elif payload[k] == {}:
309 del payload[k]
310
311 if payload == {} or payload == {"spec": {}}:
312 # Nothing has changed
313 if "value" not in _json: # 7.0.2
314 _json = {"value": _json}
315 _json["id"] = params.get("None")
316 return await update_changed_flag(_json, resp.status, "get")
317 async with session.patch(_url, json=payload, **session_timeout(params)) as resp:
318 try:
319 if resp.headers["Content-Type"] == "application/json":
320 _json = await resp.json()
321 except KeyError:
322 _json = {}
323 if "value" not in _json: # 7.0.2
324 _json = {"value": _json}
325
326 # e.g: content_configuration
327 if not _json and resp.status == 204:
328 async with session.get(_url, **session_timeout(params)) as resp_get:
329 _json_get = await resp_get.json()
330 if _json_get:
331 _json = _json_get
332
333 _json["id"] = params.get("None")
334 return await update_changed_flag(_json, resp.status, "update")
335
336
337 if __name__ == "__main__":
338 import asyncio
339
340 current_loop = asyncio.new_event_loop()
341 try:
342 asyncio.set_event_loop(current_loop)
343 current_loop.run_until_complete(main())
344 finally:
345 current_loop.close()