Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2025, Denys Mishchenko <[email protected]>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7
8 from __future__ import (absolute_import, division, print_function)
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r'''
13 ---
14 module: virt_secret
15 version_added: '2.1.0'
16 author:
17 - Denys Mishchenko (@arddennis)
18
19 short_description: Manage libvirt secrets and their values
20 description:
21 - Manage I(libvirt) secrets. Can add, remove or update secrets in libvirt.
22 - Can be used to set secrets value.
23 options:
24 uuid:
25 description:
26 - Secret UUID. The value is unique across all secret types.
27 - If UUID value is also defined in the O(xml) this option is ignored.
28 type: str
29 secret:
30 type: dict
31 description:
32 - Defines a secret as a set of fields instead of raw XML.
33 - This property is mutually exclusive with O(xml).
34 - If O(uuid) is not defined, O(secret.usage) and O(secret.usage_id) must be defined.
35 suboptions:
36 ephemeral:
37 description:
38 - If V(True), secret will only be kept in memory.
39 - Default value is V(False).
40 type: bool
41 default: False
42 private:
43 description:
44 - If V(True), value will not be retrivable from libvirt.
45 - Default value is V(False).
46 type: bool
47 default: True
48 usage:
49 type: str
50 description:
51 - Specifies what this secret is used for.
52 - Possible values are V(none), V(volume), V(ceph), V(iscsi), V(tls), V(vtpm).
53 choices:
54 - none
55 - volume
56 - ceph
57 - iscsi
58 - tls
59 - vtpm
60 usage_id:
61 description:
62 - Defines unique secret_ID. Unique for each O(secret.usage).
63 type: str
64 description:
65 type: str
66 description:
67 - Defines secret description.
68 password:
69 description:
70 - A value of the secret which will be stored in the libvirt secret.
71 - |
72 As in majority cases secrets are private, password is defined only
73 during secret creation or when O(command=set_value) is executed. If the
74 secret already exist and the O(password) is defined, it will not try to
75 set it once again. Even if different password is provided.
76 type: str
77 state:
78 description:
79 - Alternative for the O(command) option.
80 - If V(present), creates a volume described by either O(xml) or O(secret).
81 - Can be used to update existing secrets properties.
82 - If V(absent), removes secret defined by either O(uuid), O(state) or O(xml).
83 - |
84 If V(present) and UUID is not specified in either O(uuid) or O(xml), it
85 will try to find existing secret using O(secret.usage) and
86 O(secret.usage_id)
87 - Mutually exclusive with O(command).
88 type: str
89 choices: [present, absent]
90 command:
91 choices:
92 - create
93 - delete
94 - list_secrets
95 - get_xml
96 - set_value
97 description:
98 - Executes commands to manage secret.
99 - |
100 If defined V(create), creates secret described by either O(xml)
101 or(secret). It is analagous to O(state=present).
102 - |
103 If defined V(delete), removes secret defined by either O(uuid),
104 O(state), O(xml). It is analagous to O(state=absent).
105 - |
106 If defined V(list_secrets) it will return RV(list_secrets) with all
107 existing secrets in XML format.
108 - |
109 If defined V(get_xml) module will try to get secret definition from
110 libvirt. If existing secret found, returns RV(secret_xml). Otherwise it
111 will return None.
112 - |
113 If defined V(set_value) module will define a secret value. This command
114 is not idempotent and will always show changed. Requires O(password) to
115 be defined.
116 type: str
117 extends_documentation_fragment:
118 - community.libvirt.virt.options_uri
119 - community.libvirt.virt.options_xml
120 requirements:
121 - "libvirt"
122 - "lxml"
123 - "PyYAML"
124 attributes:
125 check_mode:
126 description: Check mode is fully supported.
127 support: full
128 details:
129 - In check mode, secrets are not actually created, updated or deleted.
130 - |
131 Module compares existing state of the secret in libvirt and check if
132 change is required.
133 - Will always produce changed with O(command=set_value).
134 diff_mode:
135 description: Module provides state change as a dict.
136 support: full
137 details:
138 - |
139 For all made changes except O(command=set_value) module will return
140 diff in a dict form to illustrate was was changed.
141 - |
142 In check_mode diff will contain the same output as if it was executed
143 normally.
144 idempotent:
145 description: In most cases, this module is idempotent.
146 support: partial
147 details:
148 - |
149 If O(command=set_value) the module is not idempotent as it don't try to
150 get secrets from libvirt and always return changed.
151 - In most of the cases secrets are private and their value is not
152 obtainable from the libvirt.
153 '''
154
155
156 RETURN = r'''
157 secret_xml:
158 type: str
159 description: When I(command=get_xml) returns XML definition of the secret.
160 returned: success
161 sample: |
162 <secret ephemeral="no" private="yes">
163 <uuid>e4b5978c-ba37-5605-97c1-4a20413d0fc9</uuid>
164 <description>test_secret pool secret</description>
165 <usage type="ceph">
166 <name>test_secret</name>
167 </usage>
168 </secret>"
169 list_secrets:
170 type: list
171 elements: str
172 returned: success
173 description: When (command=list_secrets) returns a list of secrets in XML format.
174 sample:
175 - |
176 <secret ephemeral='no' private='yes'>
177 <uuid>fce0c61a-f0fc-5727-90b2-56c92534070f</uuid>
178 <description>sample vTPM secret</description>
179 <usage type='vtpm'><name>VTPM_example</name></usage></secret>
180 - |
181 <secret ephemeral='no' private='yes'>
182 <uuid>e4b5978c-ba37-5605-97c1-4a20413d0fc9</uuid>
183 <description>changed_test pool secret</description>
184 <usage type='ceph'><name>test_secret</name></usage>
185 </secret>
186 - |
187 <secret ephemeral='no' private='yes'>
188 <uuid>edfa6124-eb0e-4449-a680-66f5fa7aedeb</uuid>
189 <description>Secret puppy name</description>
190 <usage type='volume'><volume>/var/lib/libvirt/images/puppyname.img</volume></usage>
191 </secret>
192 '''
193
194
195 EXAMPLES = r'''
196 ---
197 - name: Create new secret using xml option and command
198 community.libvirt.virt_secret:
199 command: create
200 xml: |
201 <secret ephemeral='no' private='yes'>
202 <uuid>e4b5978c-ba37-5605-97c1-4a20413d0fc9</uuid>
203 <description>test ceph pool secret</description>
204 <usage type='ceph'>
205 <name>test_secret</name>
206 </usage>
207 </secret>
208
209 - name: Get secret XML by uuid
210 community.libvirt.virt_secret:
211 uuid: e4b5978c-ba37-5605-97c1-4a20413d0fc9
212 command: get_xml
213 register: result
214
215 - name: Get XML by secret usage and usage_id
216 community.libvirt.virt_secret:
217 secret:
218 usage: ceph
219 usage_id: test_secret
220 command: get_xml
221 register: result
222
223 - name: Print found XML
224 ansible.builtin.debug:
225 var: result.secret_xml
226
227 - name: Define secret using options secret and uuid
228 community.libvirt.virt_secret:
229 uuid: e4b5978c-ba37-5605-97c1-4a20413d0fc9
230 secret:
231 usage: tls
232 usage_id: test_secret
233 description: Test TLS secret
234 state: present
235
236 - name: List all currently defined secrets
237 community.libvirt.virt_secret:
238 command: list_secrets
239 register: result
240
241 - name: Print found secrets list
242 ansible.builtin.debug:
243 var: result.secrets_list
244
245 - name: Set value of the secret
246 community.libvirt.virt_secret:
247 uuid: e4b5978c-ba37-5605-97c1-4a20413d0fc9
248 command: set_value
249 password: somesecureandrandomsecret1234
250
251 - name: Remove secret
252 community.libvirt.virt_secret:
253 uuid: 57ea8fd0-9b82-4e54-9d16-df7d2765844d
254 state: absent
255 '''
256
257
258 # ansible module_utils uses own path structure and must be imported first
259 # pylint: disable-next=no-name-in-module,import-error,wrong-import-order
260 from ansible_collections.community.libvirt.plugins.module_utils.common import (
261 VirtModule, libvirt_error_to_none)
262 from dataclasses import dataclass, asdict
263 from typing import Union
264
265 try:
266 from lxml import etree
267 except ImportError:
268 import xml.etree.ElementTree as etree
269
270
271 COMMAND_CHOICES = [
272 'create',
273 'delete',
274 'list_secrets',
275 'get_xml',
276 'set_value'
277 ]
278
279
280 # https://libvirt.org/formatsecret.html
281 USAGE_TYPES_TAGS = {
282 'none': 'name',
283 'volume': 'volume',
284 'ceph': 'name',
285 'iscsi': 'target',
286 'tls': 'name',
287 'vtpm': 'name'
288 }
289
290
291 # https://libvirt.org/html/libvirt-libvirt-secret.html#virSecretUsageType
292 VIR_SECRET_USAGE_TYPE = {
293 0: 'none',
294 1: 'volume',
295 2: 'ceph',
296 3: 'iscsi',
297 4: 'tls',
298 5: 'vtpm'
299 }
300
301
302 VIR_SECRET_USAGE_ID = {
303 'none': 0,
304 'volume': 1,
305 'ceph': 2,
306 'iscsi': 3,
307 'tls': 4,
308 'vtpm': 5
309 }
310
311
312 bool_map = {
313 'yes': True,
314 'no': False
315 }
316
317
318 @dataclass
319 class SecretUsage():
320 """ libvirt secret usage type """
321 type: str
322 values: list
323
324 def to_xml(self) -> etree.Element:
325 """ Form usage element of the secret element """
326 element = etree.Element('usage', type=self.type)
327 for sub in self.values:
328 subelement = etree.Element('name')
329 subelement.text = sub
330 element.append(subelement)
331 return element
332
333
334 @dataclass
335 class SecretElement():
336 """ Libvirt secret record """
337 uuid: Union[str, None] # We might not have uuid defined in the module
338 usage: str
339 usageid: str
340 ephemeral: bool = False
341 private: bool = True
342 description: Union[str, None] = ''
343
344 def to_xmlstr(self) -> str:
345 """ form xml secret suitable for libvirt """
346 is_efemeral = 'yes' if self.ephemeral else 'no'
347 is_private = 'yes' if self.private else 'no'
348 the_element = etree.Element(
349 'secret', ephemeral=is_efemeral, private=is_private)
350 if self.uuid:
351 the_element.append(self._uuid_element)
352 the_element.append(self._description_element)
353 the_element.append(self._usage_element)
354 return etree.tostring(the_element, encoding='unicode')
355
356 @property
357 def _usage_element(self):
358 """ Forms usage element """
359 usage = etree.Element('usage', type=self.usage)
360 usage_id = etree.Element(USAGE_TYPES_TAGS[self.usage])
361 usage_id.text = self.usageid
362 usage.append(usage_id)
363 return usage
364
365 @property
366 def _uuid_element(self):
367 """ Forms uuid element """
368 uuid = etree.Element('uuid')
369 uuid.text = self.uuid
370 return uuid
371
372 @property
373 def _description_element(self):
374 """ Forms description element """
375 description = etree.Element('description')
376 if self.description:
377 description.text = self.description
378 else:
379 description.text = ""
380 return description
381
382
383 class LibvirtSecretModule(VirtModule):
384 """ Libvirt secrets manipulation module """
385
386 def logic(self):
387 """ Module logic not covered by direct function calls
388
389 As state and command are mutual params and one of them is required
390 we could get here only if state is already defined and of a correct
391 value """
392
393 state = self.ansible.params.get('state')
394 if state == 'present':
395 self.create()
396 elif state == 'absent':
397 self.delete()
398
399 def create(self):
400 """ Secret create function
401
402 If secret with defined UUID already exist, it will compare its
403 attributes to a defined ones. If a difference is found, it will replace
404 the secret attributes with the defined ones.
405 If we do not have UUID defined it will try to find the secret using its
406 usage and usageID which must be unique set. If found UUID of existing
407 secret will be assumed as a defined one for the attributes comparsion.
408 In case existing secret was not found, a new one will be created.
409 """
410 self._check_duplicated_uuid() # A warning for UUID defined twice
411 defined_element = self.defined_element
412 password = self.ansible.params.get('password')
413
414 existing_virtsecret = self.get_virsecret()
415 existing_element = self._form_element_from_virtsecret(
416 existing_virtsecret)
417
418 # We might have created secret without uuid supplied, but want to
419 # compare objects defined vs existing
420 if defined_element.uuid is None and existing_element:
421 defined_element.uuid = existing_element.uuid
422
423 if defined_element != existing_element:
424 self.mod_status.changed = True
425 if existing_element is not None:
426 self.mod_status.before = asdict(existing_element)
427 else:
428 self.mod_status.before = {}
429 self.mod_status.after = asdict(defined_element)
430 if not self.check:
431 self.conn.secretDefineXML(defined_element.to_xmlstr())
432 created_secret = self.get_virsecret()
433 if created_secret is None:
434 self.mod_status.failed = True
435 self.mod_status.msg = "Failed to create a secret."
436 self.exit()
437 if password is not None:
438 created_secret.setValue(password)
439 self.exit()
440
441 @libvirt_error_to_none
442 def get_virsecret(self):
443 """ Lookup of the secret by its uuid or usage
444
445 Ansible module will make sure that uuid, secret or xml is defined.
446
447 :return: libvirt.virSecret object or None if it wasn't found
448 """
449 if self.defined_uuid:
450 return self.conn.secretLookupByUUIDString(self.defined_uuid)
451 secret = self.defined_element
452 if secret is None:
453 return None
454 if secret.usage is None or secret.usageid is None:
455 self.mod_status.failed = True
456 self.mod_status.msg = \
457 "Usage and usage_id must be defined if uuid is missing"
458 self.exit()
459 int_usage = VIR_SECRET_USAGE_ID[secret.usage]
460 return self.conn.secretLookupByUsage(int_usage, secret.usageid)
461
462 def _form_element_from_virtsecret(self, element) -> Union[
463 SecretElement, None]:
464 """ Convert libvirt.virSecret to SecretElement
465
466 :param element: libvirt.virSecret object
467 :return: SecretElement class secret
468 """
469 if element is None:
470 return None
471
472 an_xml = etree.fromstring(element.XMLDesc())
473 return SecretElement(
474 uuid=element.UUIDString(),
475 usage=VIR_SECRET_USAGE_TYPE[element.usageType()],
476 usageid=element.usageID(),
477 ephemeral=bool_map[an_xml.get('ephemeral', 'no')],
478 private=bool_map[an_xml.get('private', 'yes')],
479 description=an_xml.findtext('description'))
480
481 @property
482 def defined_xml(self) -> Union[str, None]:
483 """ Forms defined XML
484
485 It looks like this function has chicken and the egg problem, but if
486 xml option is defined, defined_element will be calculated first based
487 on its values. If it is not, we expect secret to be defined and will
488 use it instead.
489 """
490 defined_xml = self.ansible.params.get('xml')
491 if defined_xml is not None:
492 return defined_xml
493 # To break possible infinity recursion we'll check for secret here as
494 # we already know that xml is not defined
495 if self.ansible.params.get('secret') is not None:
496 element = self.defined_element
497 if element is not None:
498 return element.to_xmlstr()
499 return None
500
501 @property
502 def defined_element(self) -> Union[SecretElement, None]:
503 """ generate defined secret element """
504 secret = self.ansible.params.get('secret')
505 if secret is not None:
506 return self._parse_secret_param()
507 if self.defined_xml is not None:
508 return self._parse_xml_secret(self.defined_xml)
509 return None
510
511 def _check_duplicated_uuid(self) -> None:
512 """ Get UUID provided in the module params
513
514 We need to inform user if uuid was provided multiple times
515 UUID from XML takes precedance over uuid param. Function is dedicated
516 for exactly this purpose to not produce multiple warnings.
517 """
518
519 param_uuid = self.ansible.params.get('uuid')
520 if self.defined_xml_uuid is not None and param_uuid is not None:
521 self.ansible.warn(
522 'UUID provided multiple times, using the one defined in XML!')
523 return
524
525 @property
526 def defined_xml_uuid(self) -> Union[str, None]:
527 """ Finds if we have defined UUID in the XML param """
528 xml = self.ansible.params.get('xml')
529 if xml is None:
530 return None
531 secret_element = etree.fromstring(xml)
532 return secret_element.findtext('uuid')
533
534 @property
535 def defined_uuid(self) -> Union[str, None]:
536 """ Defined UUID either in XML or as a separate param """
537 xml_uuid = self.defined_xml_uuid
538 param_uuid = self.ansible.params.get('uuid')
539 return xml_uuid if xml_uuid is not None else param_uuid
540
541 def _parse_secret_param(self) -> SecretElement:
542 """ Form SecretElement from secret module params """
543 secret_param = self.ansible.params.get('secret')
544 usage_id = secret_param.get('usage_id')
545 if usage_id is None:
546 self.mod_status.failed = True
547 self.mod_status.msg = "usageid is requrired to create a secret"
548 self.exit()
549 element = SecretElement(
550 uuid=self.ansible.params.get('uuid'),
551 usage=secret_param.get('usage', 'none'),
552 usageid=usage_id,
553 ephemeral=secret_param.get('ephemeral', False),
554 private=secret_param.get('private', True),
555 description=secret_param.get('description', '')
556 )
557 return element
558
559 def _parse_xml_secret(self, xml: str) -> Union[SecretElement, None]:
560 """ Parse xml string and return it as SecretElement object
561
562 :param xml: string containing XML of the secret. Param left for future
563 reuse of the function.
564 """
565 an_xml = etree.fromstring(xml)
566 # Usage element must be present along with its usageid
567 usage_element = an_xml.find('usage')
568 if usage_element is not None:
569 usage = usage_element.get('type', 'none')
570 childrens = usage_element.getchildren()
571 if childrens:
572 if len(childrens) > 0:
573 usage_id = childrens[0].text
574 else:
575 self.mod_status.failed = True
576 self.mod_status.mgs = 'Unable to find usageid in the xml'
577 self.exit()
578 usage_id = 'error'
579 else:
580 self.mod_status.failed = True
581 self.mod_status.mgs = 'Unable to find usageid in the xml'
582 self.exit()
583 return None # never reached, but better than linter asertion
584 else:
585 self.mod_status.failed = True
586 self.mod_status.mgs = 'Unable to find usage element in the xml'
587 self.exit()
588 return None # never reached, but better than linter asertion
589
590 uuid_element = an_xml.find('uuid')
591 if uuid_element is not None:
592 a_uuid = uuid_element.text
593 else:
594 a_uuid = self.ansible.params.get('uuid')
595
596 element = SecretElement(
597 uuid=a_uuid,
598 usage=usage,
599 usageid=usage_id,
600 ephemeral=bool_map[an_xml.get('ephemeral', 'no')],
601 private=bool_map[an_xml.get('private', 'yes')],
602 description=an_xml.findtext('description'))
603
604 return element
605
606 def delete(self):
607 """ Delete defined secret """
608
609 virsecret = self.get_virsecret()
610 before = self._form_element_from_virtsecret(virsecret)
611 if before is not None:
612 self.mod_status.before = asdict(before)
613 else:
614 self.mod_status.msg = "Requested secret not found"
615 self.exit()
616
617 if not self.check:
618 virsecret.undefine() # type: ignore
619 self.mod_status.changed = True
620 self.mod_status.after = {}
621 self.exit()
622
623 def list_secrets(self):
624 """ Get list of defined secrets and return them as list of XMLs """
625
626 current_secrets = [
627 secret.XMLDesc()
628 for secret in self.conn.listAllSecrets()]
629 if len(current_secrets) > 0:
630 self.mod_status.msg = "Found defined secrets"
631 else:
632 self.mod_status.msg = "No secrets currently defined"
633 self.mod_status.data = {
634 'secrets_list': current_secrets}
635 self.exit()
636
637 def set_value(self):
638 """ Set secret value to a defined password """
639 password = self.ansible.params.get('password')
640 virsecret = self.get_virsecret()
641 if virsecret is None:
642 self.mod_status.failed = True
643 self.mod_status.msg = "Unable to find a secret to set a value"
644 self.exit()
645 if not self.check:
646 result = virsecret.setValue(password)
647 if result != 0:
648 self.mod_status.failed = True
649 self.mod_status.msg = "Failed to set the value"
650 self.mod_status.msg = "The value for the secret was successfully set"
651 self.mod_status.changed = True
652 self.exit()
653
654 def get_xml(self):
655 """ Get defined secret XML
656
657 There are two options to get the secret: using uuid and by its usage
658 """
659 virsecret = self.get_virsecret()
660 secret_object = self._form_element_from_virtsecret(virsecret)
661 if secret_object:
662 result = secret_object.to_xmlstr()
663 self.mod_status.msg = "Found secret"
664 else:
665 self.mod_status.msg = "Secret not found"
666 result = None
667 self.mod_status.data = {'secret_xml': result}
668 self.exit()
669
670 def secret_undefine(self):
671 """ Undefine secret if it exist """
672
673
674 def main():
675 """ Module execution """
676 argument_spec = {
677 'uuid': {'type': 'str'},
678 'secret': {
679 'type': 'dict',
680 'no_log': False,
681 "options": {
682 'ephemeral': {'type': 'bool', 'default': False},
683 'private': {'type': 'bool', 'default': True},
684 'usage': {'type': 'str',
685 'choices': [
686 'none',
687 'volume',
688 'ceph',
689 'iscsi',
690 'tls',
691 'vtpm']},
692 'usage_id': {'type': 'str'},
693 'description': {'type': 'str'}}},
694 'password': {'type': 'str', 'no_log': True},
695 'uri': {'type': 'str', 'default': 'qemu:///system'},
696 'state': {'type': 'str', 'choices': ['present', 'absent']},
697 'command': {'type': 'str', 'choices': COMMAND_CHOICES},
698 'xml': {'type': 'str'}}
699 required_if = [
700 ('state', 'present', ['xml', 'secret'], True),
701 ('state', 'absent', ['uuid', 'secret', 'xml'], True),
702 ('command', 'create', ['xml', 'secret'], True),
703 ('command', 'delete', ['uuid', 'xml', 'secret'], True),
704 ('command', 'set_value', ['password'], False),
705 ('command', 'get_xml', ['uuid', 'secret'], True)]
706 mutually_exclusive = [['state', 'command'], ['xml', 'secret']]
707 required_one_of = [('state', 'command')]
708
709 module = LibvirtSecretModule(argument_spec=argument_spec,
710 required_if=required_if,
711 mutually_exclusive=mutually_exclusive,
712 required_one_of=required_one_of,
713 supports_check_mode=True)
714 module.run()
715
716
717 if __name__ == '__main__':
718 main()