Debian Codegraph @

ansible_collections/community/libvirt/plugins/modules/virt_volume.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2015, Maciej Delmanowski <[email protected]>
5 # (c) 2025, Dougal Seeley <[email protected]>
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11 DOCUMENTATION = '''
12 ---
13 module: virt_volume
14 version_added: '1.4.0'
15 author:
16 - Leonardo Galli (@galli-leo)
17 - Niclas Kretschmer (@NK308)
18 - Dougal Seeley (@dseeley)
19 short_description: Manage libvirt volumes inside a storage pool
20 description:
21 - Manage I(libvirt) volumes inside a storage pool.
22 options:
23 name:
24 aliases: [ "volume" ]
25 description:
26 - Name of the volume being managed. Note that the volume must be previously defined with xml.
27 type: str
28 pool:
29 required: true
30 description:
31 - Name of the storage pool, where the volume is located.
32 type: str
33 state:
34 choices: [ "present", "absent" ]
35 description:
36 - If C(present), Creates a new volume with the XML provided, optionally cloning from the image in C(clone_source). The name of the volume is specified
37 in the XML (if a C(name) parameter is provided, it is ignored). C(xml) must be provided.
38 - If C(absent), Deletes the volume specified by C(name) from the storage pool. If C(wipe) is set to C(true), the volume will be wiped before deletion.
39 - Mutually exclusive with C(command).
40 - Can be used to resize existing volumes if C(xml) has bigger capacity than current volume capacity.
41 type: str
42 command:
43 choices: [ "create", "delete", "wipe", "list_volumes", "get_xml", "create_cidata_cdrom" ]
44 description:
45 - C(create) - Analagous to C(state) / C(present)
46 - C(delete) - Analagous to C(state) / C(absent)
47 - C(wipe) - Performs a wipe *only* of the volume specified by C(name) - *does not delete* the volume.
48 - C(list_volumes) - Lists all volumes in the storage pool.
49 - C(get_xml) - Retrieves the XML of the volume specified by C(name).
50 - C(create_cidata_cdrom) - Creates a CIDATA CDROM with the provided C(cloudinit_config) data. Enables bootstrapping of cloud-init enabled VMs.
51 - Mutually exclusive with C(state).
52 type: str
53 xml:
54 description:
55 - XML definition of the volume to be created.
56 - This is required if C(command) is C(create)
57 type: str
58 cloudinit_config:
59 description:
60 - Ansible dict of cloud-init data to create a CIDATA CDROM.
61 - The data should contain the keys C(METADATA), C(USERDATA), and/or C(NETWORK_CONFIG).
62 - This is required if C(command) is C(create_cidata_cdrom).
63 type: dict
64 clone_source:
65 description:
66 - Name of the volume to clone from.
67 - Optionally provided with C(state) C(present) or C(command) C(create).
68 type: str
69 wipe:
70 description: Whether to wipe the volume before deleting it.
71 default: False
72 type: bool
73 extends_documentation_fragment:
74 - community.libvirt.virt.options_uri
75 - community.libvirt.virt.options_xml
76 - community.libvirt.requirements
77 requirements:
78 - "libvirt"
79 - "lxml"
80 - "pycdlib"
81 '''
82
83 EXAMPLES = '''
84 - name: Create volume in existing default pool
85 community.libvirt.virt_volume:
86 state: present
87 pool: default
88 xml: |
89 <volume>
90 <name>testing-volume</name>
91 <allocation>0</allocation>
92 <capacity unit="M">10</capacity>
93 <target>
94 <permissions>
95 <mode>0644</mode>
96 <label>virt_image_t</label>
97 </permissions>
98 </target>
99 </volume>
100
101 - name: Create a volume from a template
102 community.libvirt.virt_volume:
103 pool: default
104 xml: "{{ lookup('ansible.builtin.template', 'volume-template.xml.j2') }}"
105 state: present
106
107 - name: List volumes in default pool
108 community.libvirt.virt_volume:
109 pool: default
110 command: list_volumes
111
112 - name: Get volume XML
113 community.libvirt.virt_volume:
114 pool: default
115 command: get_xml
116 name: testing-volume
117 register: r__virt_volume__get_xml
118
119 - name: Wipe a volume
120 community.libvirt.virt_volume:
121 pool: default
122 command: wipe
123 name: testing-volume
124
125 - name: Delete volume from default pool, wiping it first (using state parameter)
126 community.libvirt.virt_volume:
127 pool: default
128 state: absent
129 name: testing-volume
130 wipe: true
131
132 - name: Delete volume from default pool (using command parameter)
133 community.libvirt.virt_volume:
134 pool: default
135 command: delete
136 name: testing-volume
137
138 - name: Create a volume from an existing image (clone)
139 community.libvirt.virt_volume:
140 pool: default
141 command: create
142 clone_source: gold-ubuntu2404-base-image
143 xml: |
144 <volume type='file'>
145 <name>testing_volume--boot</name>
146 <capacity unit='G'>10</capacity>
147 <target><format type='qcow2'/></target>
148 </volume>
149
150 - name: Create CIDATA (cloud-init) cdrom
151 community.libvirt.virt_volume:
152 pool: default
153 command: create_cidata_cdrom
154 name: testing_cidata.iso
155 cloudinit_config:
156 NETWORK_CONFIG: {version: 2, ethernets: {eth0: {dhcp4: true}}}
157 USERDATA: {users: [{name: testuser, lock_passwd: false, shell: /bin/bash, ssh_authorized_keys: ["ssh-rsa xxxxxxxxxxxxxxxxxxxxx=="]}]}
158 METADATA: {local-hostname: my_host}
159 register: r__virt_volume__create_cidata_cdrom
160 '''
161
162 RETURN = r"""
163 type:
164 description: When I(command=list_volumes) returns the type of the volume based on the underlying type of the pool.
165 returned: success
166 type: str
167 sample: "file"
168 capacity:
169 description: When I(command=list_volumes) returns the total capacity of the volume in bytes.
170 returned: success
171 type: int
172 sample: "8589934592"
173 allocation:
174 description: When I(command=list_volumes) returns the current allocated size of the volume in bytes.
175 returned: success
176 type: int
177 sample: "2740523008"
178 """
179
180 from ansible_collections.community.libvirt.plugins.module_utils.constants import VOLUME_TYPE_INFO_MAP
181 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
182 import traceback
183
184 try:
185 import libvirt
186 LIBVIRT_IMPORT_ERR = None
187 except ImportError as libvirt_import_exception:
188 LIBVIRT_IMPORT_ERR = libvirt_import_exception
189
190 try:
191 from lxml import etree
192 LXML_IMPORT_ERR = None
193 except ImportError as lxml_import_exception:
194 LXML_IMPORT_ERR = lxml_import_exception
195
196
197 def _get_volume_size(capacity_elem):
198 """ Get volume size from xml definition
199
200 :param capacity_elem: lxml.etree._Element to parse for the capacity value
201 """
202 unit = capacity_elem.get("unit", "bytes").lower()
203
204 # Conversion factors to bytes
205 unit_factors = {
206 "bytes": 1, "b": 1, "k": 1024, "m": 1024**2, "g": 1024**3, "t": 1024**4}
207
208 # Convert size to bytes
209 try:
210 size_bytes = int(float(capacity_elem.text) * unit_factors.get(unit, 1))
211 except (ValueError, KeyError) as exc:
212 raise ValueError(
213 f"Unknown or invalid unit for capacity: {unit}") from exc
214 return size_bytes
215
216
217 class LibvirtConnection(object):
218 def __init__(self, uri, check_mode, pool):
219 conn = libvirt.open(uri)
220 if not conn:
221 raise Exception("hypervisor connection failure")
222 self.conn = conn
223
224 self.check_mode = check_mode
225
226 self.pool_ptr = self.conn.storagePoolLookupByName(pool) if pool is not None else None
227
228 def create(self, xml, clone_source=None, name=None, **kwargs):
229 """
230 Creates a new volume with the XML provided, with the name specified in the XML, optionally cloning the image from the clone_source
231 (https://libvirt.org/html/libvirt-libvirt-storage.html#virStorageVolCreateXMLFrom)
232 """
233 isChanged = False
234 xml_etree = etree.fromstring(xml)
235 xml_vol_name = xml_etree.xpath("/volume/name")[0].text
236
237 warnings_list = []
238 if name:
239 warnings_list.append("The 'name' parameter is ignored; the volume name is taken from the XML definition ('%s')." % xml_vol_name)
240
241 try:
242 createdStorageVolPtr = self.pool_ptr.storageVolLookupByName(xml_vol_name)
243 except libvirt.libvirtError as e:
244 if e.get_error_code() == libvirt.VIR_ERR_NO_STORAGE_VOL:
245 if clone_source:
246 # Ensure clone_source is valid
247 if not self.pool_ptr.storageVolLookupByName(clone_source):
248 raise libvirt.libvirtError("Clone source volume '%s' does not exist." % clone_source)
249 clone_source_vol_ptr = self.pool_ptr.storageVolLookupByName(clone_source)
250 createdStorageVolPtr = self.pool_ptr.createXMLFrom(xml, clone_source_vol_ptr, 0)
251 isChanged = True
252 else:
253 # If no clone_source is provided, just create an empty volume
254 createdStorageVolPtr = self.pool_ptr.createXML(xml)
255 isChanged = True
256 else:
257 raise e
258
259 if xml_etree.xpath("/volume/capacity"):
260 size_bytes = _get_volume_size(
261 xml_etree.xpath("/volume/capacity")[0])
262 # https://libvirt.org/html/libvirt-libvirt-storage.html#virStorageVolInfo
263 created_volume_size_bytes = createdStorageVolPtr.info()[1]
264 if created_volume_size_bytes != size_bytes:
265 createdStorageVolPtr.resize(size_bytes)
266 isChanged = True
267
268 result = {'changed': isChanged, 'res': {'XMLDesc': createdStorageVolPtr.XMLDesc(0),
269 'name': createdStorageVolPtr.name(),
270 'path': createdStorageVolPtr.path(),
271 'key': createdStorageVolPtr.key()}}
272 if warnings_list:
273 result['warnings'] = warnings_list
274
275 return result
276
277 def create_cidata_cdrom(self, name, cloudinit_config, **kwargs):
278 """ Create a properly formatted CD image containing cloud-init files, then upload it to the host """
279 import yaml
280
281 try:
282 import pycdlib
283 except ImportError as pycdlib_import_exception:
284 raise pycdlib_import_exception
285
286 # StringIO as BytesIO for python2/3 compatibility
287 try:
288 from cStringIO import StringIO as BytesIO
289 except ImportError:
290 from io import BytesIO
291
292 # Ensure we actually have some CIDATA before creating the CIDATA cdrom
293 if cloudinit_config and ('METADATA' in cloudinit_config or 'USERDATA' in cloudinit_config or 'NETWORK_CONFIG' in cloudinit_config):
294 iso = pycdlib.PyCdlib()
295 iso.new(interchange_level=3, joliet=True, sys_ident='LINUX', rock_ridge='1.09', vol_ident='cidata')
296
297 if 'NETWORK_CONFIG' in cloudinit_config:
298 cidata_network = yaml.safe_dump(cloudinit_config['NETWORK_CONFIG'], width=4096, encoding='utf-8')
299 iso.add_fp(BytesIO(cidata_network), len(cidata_network), '/NETWORK_CONFIG.;1', rr_name="network-config", joliet_path='/network-config')
300
301 if 'METADATA' in cloudinit_config:
302 cidata_metadata = yaml.safe_dump(cloudinit_config['METADATA'], width=4096, encoding='utf-8')
303 else:
304 cidata_metadata = "# Note: The user-data and meta-data must both be present for this to be considered a valid seed ISO.".encode('utf-8')
305
306 if 'USERDATA' in cloudinit_config:
307 cidata_userdata = "#cloud-config\n".encode('utf-8') + yaml.safe_dump(cloudinit_config['USERDATA'], width=4096, encoding='utf-8')
308 else:
309 cidata_metadata = "# Note: The user-data and meta-data must both be present for this to be considered a valid seed ISO.".encode('utf-8')
310
311 iso.add_fp(BytesIO(cidata_metadata), len(cidata_metadata), '/METADATA.;1', rr_name="meta-data", joliet_path='/meta-data')
312 iso.add_fp(BytesIO(cidata_userdata), len(cidata_userdata), '/USERDATA.;1', rr_name="user-data", joliet_path='/user-data')
313
314 outiso = BytesIO()
315 iso.write_fp(outiso)
316 outiso_len = outiso.getbuffer().nbytes
317
318 # Remote iso XML
319 vol_xml = """
320 <volume type='file'>
321 <name>{}</name>
322 <capacity unit='bytes'>{}</capacity>
323 <target><format type='iso'/></target>
324 </volume>""".format(name, outiso_len)
325
326 try:
327 createdStorageVolPtr = self.pool_ptr.storageVolLookupByName(name)
328 except libvirt.libvirtError as e:
329 if e.get_error_code() == libvirt.VIR_ERR_NO_STORAGE_VOL:
330 createdStorageVolPtr = self.pool_ptr.createXML(vol_xml)
331
332 virStreamPtr = self.conn.newStream(0)
333 createdStorageVolPtr.upload(virStreamPtr, 0, outiso_len, 0)
334 virStreamPtr.send(outiso.getvalue())
335
336 virStreamPtr.finish()
337 else:
338 raise e
339
340 iso.close()
341 return {'changed': True, 'res': {'XMLDesc': createdStorageVolPtr.XMLDesc(0),
342 'name': createdStorageVolPtr.name(),
343 'path': createdStorageVolPtr.path(),
344 'key': createdStorageVolPtr.key()}}
345 else:
346 return {'changed': False, 'res': {'Error': 'No CIDATA to create'}}
347
348 def delete(self, name, wipe=False, **kwargs):
349 """ Delete a storage volume (https://libvirt.org/html/libvirt-libvirt-storage.html#virStorageVolDelete) """
350 try:
351 if wipe:
352 self.pool_ptr.storageVolLookupByName(name).wipe(0)
353 self.pool_ptr.storageVolLookupByName(name).delete()
354 return {'changed': True, 'res': 'Deleted %s' % name}
355 except libvirt.libvirtError as e:
356 if e.get_error_code() == libvirt.VIR_ERR_NO_STORAGE_VOL:
357 return {'changed': False, 'res': e.get_error_message()}
358 else:
359 raise e
360
361 def wipe(self, name, **kwargs):
362 """ Wipe a storage volume (doesn't delete) (https://libvirt.org/html/libvirt-libvirt-storage.html#virStorageVolWipe)"""
363 try:
364 self.pool_ptr.storageVolLookupByName(name).wipe(0)
365 return {'changed': True, 'res': 'Wiped and deleted %s' % name}
366 except libvirt.libvirtError as e:
367 if e.get_error_code() == libvirt.VIR_ERR_NO_STORAGE_VOL:
368 return {'changed': False, 'res': e.get_error_message()}
369 else:
370 raise e
371
372 def get_xml(self, name, **kwargs):
373 """ Return the XMLDesc for a given storage volume (https://libvirt.org/html/libvirt-libvirt-storage.html#virStorageVolGetXMLDesc) """
374 try:
375 res_XMLDesc = self.pool_ptr.storageVolLookupByName(name).XMLDesc(0)
376 return {'changed': False, 'res': res_XMLDesc}
377 except libvirt.libvirtError as e:
378 if e.get_error_code() == libvirt.VIR_ERR_NO_STORAGE_VOL:
379 return {'changed': False, 'res': {'Error': 'libvirt.VIR_ERR_NO_STORAGE_VOL: %s' % (e.get_error_message())}}
380 else:
381 raise e
382
383 def list_volumes(self, **kwargs):
384 """ List all volumes in the storage pool (https://libvirt.org/html/libvirt-libvirt-storage.html#virStoragePoolListAllVolumes) """
385 results = []
386 for entry in self.pool_ptr.listAllVolumes():
387 results.append({'name': entry.name(),
388 'path': entry.path(),
389 'key': entry.key(),
390 'XMLDesc': entry.XMLDesc(0),
391 'capacity': entry.info()[1],
392 'allocation': entry.info()[2],
393 'type': VOLUME_TYPE_INFO_MAP.get(entry.info()[0], 'unknown'),
394 'info': entry.info()})
395 return {'changed': False, 'res': results}
396
397
398 def main():
399 module = AnsibleModule(
400 argument_spec=dict(
401 name=dict(aliases=['volume']),
402 pool=dict(required=True),
403 state=dict(choices=['present', 'absent']),
404 command=dict(choices=['create', 'delete', 'wipe', 'list_volumes', 'get_xml', 'create_cidata_cdrom']),
405 uri=dict(default='qemu:///system'),
406 xml=dict(),
407 clone_source=dict(type='str'),
408 cloudinit_config=dict(type='dict'),
409 wipe=dict(type='bool', default=False)
410 ),
411 mutually_exclusive=[['state', 'command']],
412 supports_check_mode=False
413 )
414
415 if LIBVIRT_IMPORT_ERR:
416 module.fail_json(msg=missing_required_lib("libvirt"), exception=LIBVIRT_IMPORT_ERR)
417
418 if LXML_IMPORT_ERR:
419 module.fail_json(msg=missing_required_lib("lxml"), exception=LXML_IMPORT_ERR)
420
421 state = module.params.get('state', None)
422 command = module.params.get('command', None)
423 uri = module.params.get('uri', None)
424
425 if not command and not state:
426 module.fail_json(msg="expected 'command' or 'state' parameter to be specified")
427
428 if state:
429 if state in ['present']:
430 command = 'create'
431 elif state in ['absent']:
432 command = 'delete'
433 else:
434 module.fail_json(msg="unexpected state, %s" % state)
435
436 if command:
437 v = LibvirtConnection(uri, module.check_mode, module.params.get('pool', None))
438 kwargs = {k: module.params.get(k) for k in module.argument_spec if module.params.get(k) is not None}
439
440 if hasattr(v, command):
441 try:
442 res = getattr(v, command)(**kwargs)
443 except Exception as e:
444 module.fail_json(msg=repr(e), exception=traceback.format_exc())
445 else:
446 if not isinstance(res, dict):
447 res = {command: res}
448
449 if 'res' in res:
450 res[command] = res.pop('res')
451
452 module.exit_json(**res)
453 else:
454 module.fail_json(msg="Command %s not recognized" % command)
455 else:
456 module.fail_json(msg="expected command parameter to be specified")
457
458
459 if __name__ == '__main__':
460 main()