Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_keyvaultcertificate_info.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2025 xuzhang3 (@xuzhang3), Fred-sun (@Fred-sun)
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 ---
12 module: azure_rm_keyvaultcertificate_info
13 version_added: "3.1.0"
14 short_description: Get Azure Key Vault certificate facts
15 description:
16 - Get or list facts of Azure Key Vault certificate(deleted).
17
18 options:
19 vault_uri:
20 description:
21 - Vault uri where the certificate stored in.
22 required: True
23 type: str
24 name:
25 description:
26 - Certificate name. If not set, will list all certificates in vault_uri.
27 type: str
28 version:
29 description:
30 - The version of the certificate.
31 type: str
32 show_deleted_certificate:
33 description:
34 - Set to I(show_delete_certificate=true) to show deleted certificates. Set to I(show_deleted_certificate=false) to show not deleted certificates.
35 type: bool
36 default: false
37 tags:
38 description:
39 - Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
40 type: list
41 elements: str
42
43 extends_documentation_fragment:
44 - azure.azcollection.azure
45
46 author:
47 - xuzhang3 (@xuzhang3)
48 - Fred-sun (@Fred-sun)
49
50 '''
51
52 EXAMPLES = '''
53 - name: Get certificate facts
54 azure_rm_keyvaultcertificate_info:
55 vault_uri: "https://myVault.vault.azure.net"
56 name: myCertificate
57
58 - name: Get specific versions of certificate
59 azure_rm_keyvaultcertificate_info:
60 vault_uri: "https://myVault.vault.azure.net"
61 name: mySecret
62 version: 2809225bcb674ff380f330471b3c3eb0
63
64 - name: Get deleted certificate
65 azure_rm_keyvaultcertificate_info:
66 vault_uri: "https://myVault.vault.azure.net"
67 name: mySecret
68 show_deleted_certificate: true
69
70 - name: List deleted certificate
71 azure_rm_keyvaultcertificate_info:
72 vault_uri: "https://myVault.vault.azure.net"
73 show_deleted_certificate: true
74 '''
75
76 RETURN = '''
77 certificates:
78 description:
79 - The facts of certificates in Azure Key Vault.
80 returned: always
81 type: complex
82 contains:
83 cert_data:
84 description:
85 - CER contents of the X509 certificate.
86 type: str
87 returned: always
88 sample: "MIID*****************0pRjXE"
89 name:
90 description:
91 - The name of the certificate.
92 type: str
93 returned: always
94 sample: testcert
95 deleted_on:
96 description:
97 - The time when the certificate was deleted, in UTC.
98 returned: always
99 type: str
100 sample: 2025-01-14T09
101 recovery_id:
102 description:
103 - The url of the recovery object, used to identify and recover the deleted certificate.
104 type: str
105 returned: always
106 sample: "https://vaultrfred01.vault.azure.net/deletedcertificates/cert02"
107 scheduled_purge_date:
108 description:
109 - The time when the certificate is scheduled to be purged, in UTC.
110 returned: always
111 type: dict
112 sample: 2025-02-14T09
113 policy:
114 description:
115 - The management policy of the deleted certificate.
116 returned: always
117 type: complex
118 contains:
119 attributes:
120 description:
121 - Certificate attributes.
122 type: complex
123 returned: always
124 contains:
125 created:
126 description:
127 - Creation datetime.
128 returned: always
129 type: str
130 sample: "2025-01-14T09:41:20+00:00"
131 not_before:
132 description:
133 - Not before datetime.
134 type: str
135 sample: None
136 expires:
137 description:
138 - Expiration datetime.
139 type: str
140 sample: None
141 updated:
142 description:
143 - Update datetime.
144 returned: always
145 type: str
146 sample: "2025-01-15T09:41:20+00:00"
147 enabled:
148 description:
149 - Indicate whether the certificate is enabled.
150 returned: always
151 type: str
152 sample: true
153 recovery_level:
154 description:
155 - Reflects the deletion recovery level currently in effect for certificates in the current vault.
156 - If it contains 'Purgeable' the certificate can be permanently deleted by a privileged user,
157 - Otherwise, only the system can purge the certificate, at the end of the retention interval.
158 returned: always
159 type: str
160 sample: None
161 recoverable_days:
162 description:
163 - Reflects the deletion recovery days.
164 type: int
165 returned: always
166 sample: None
167 issuer_name:
168 description:
169 - Name of the referenced issuer object or reserved names.
170 type: str
171 returned: always
172 sample: Self
173 subject:
174 description:
175 - The subject name of the certificate.
176 - Should be a valid X509 distinguished name.
177 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
178 - This will be ignored when importing a certificate; the subject will be parsed from the imported certificate.
179 type: str
180 returned: always
181 sample: CN=anhui.com
182 san_emails:
183 description:
184 - Subject alternative emails of the X509 object.
185 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
186 type: str
187 returned: always
188 sample: None
189 san_dns_names:
190 description:
191 - Subject alternative DNS names of the X509 object.
192 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
193 type: str
194 returned: always
195 sample: None
196 san_user_principal_names:
197 description:
198 - Subject alternative user principal names of the X509 object.
199 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
200 type: str
201 returned: always
202 sample: None
203 exportable:
204 description:
205 - Indicates if the private key can be exported.
206 type: bool
207 returned: always
208 sample: true
209 key_type:
210 description:
211 - The type of key pair to be used for the certificate.
212 type: str
213 returned: always
214 sample: RSA
215 key_size:
216 description:
217 - The key size in bits.
218 type: int
219 returned: always
220 sample: 2048
221 reuse_key:
222 description:
223 - Indicates if the same key pair will be used on certificate renewal.
224 type: bool
225 returned: always
226 sample: false
227 key_curve_name:
228 description:
229 - Elliptic curve name. For valid values, see KeyCurveName.
230 type: str
231 returned: always
232 sample: None
233 enhanced_key_usage:
234 description:
235 - The extended ways the key of the certificate can be used.
236 type: list
237 returned: always
238 sample: ['1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2']
239 key_usage:
240 description:
241 - List of key usages.
242 type: list
243 returned: always
244 sample: ["digitalSignature", "keyEncipherment"]
245 content_type:
246 description:
247 - If not specified, the media type (MIME type) of the secret backing the certificate.
248 type: str
249 returned: always
250 sample: application/x-pkcs12
251 validity_in_months:
252 description:
253 - The duration that the certificate is valid in months.
254 type: int
255 returned: always
256 sample: 12
257 lifetime_actions:
258 description:
259 - Actions that will be performed by Key Vault over the lifetime of a certificate.
260 type: list
261 returned: always
262 sample: [{'action': 'AutoRenew', 'days_before_expiry': None, 'lifetime_percentage': 80}]
263 certificate_type:
264 description:
265 - Type of certificate to be requested from the issuer provider.
266 type: str
267 returned: str
268 sample: None
269 certificate_transparency:
270 description:
271 - Indicates if the certificates generated under this policy should be published to certificate transparency logs.
272 type: bool
273 returned: always
274 sample: None
275 properties:
276 description:
277 - The certificate's properties.
278 type: complex
279 returned: always
280 contains:
281 id:
282 description:
283 - Id of the certificate. If specified all other 'Id' arguments should be omitted.
284 type: str
285 returned: always
286 sample: "https://vaultrfred01.vault.azure.net/certificates/cert02/62409e6304c642f193209729b8360d2c"
287 vault_id:
288 description:
289 - ID of the Key Vault.
290 type: str
291 returned: always
292 sample: "https://vaultrfred01.vault.azure.net"
293 x509_thumbprint:
294 description:
295 - The X509 Thumbprint of the Key Vault Certificate represented as a hexadecimal string.
296 type: str
297 returned: always
298 sample: 1blAnHN9ddng0qh1pYoUDY2lp1E=
299 tags:
300 description:
301 - List of the certificate tags.
302 type: dict
303 returned: always
304 sample: {'key': 'value'}
305 attributes:
306 description:
307 - Certificate attributes.
308 type: complex
309 returned: always
310 contains:
311 created:
312 description:
313 - Creation datetime.
314 returned: always
315 type: str
316 sample: "2025-01-14T09"
317 not_before:
318 description:
319 - Not before datetime.
320 type: str
321 sample: "2025-02-14T09"
322 expires:
323 description:
324 - Expiration datetime.
325 type: str
326 sample: "2025-03-14T09"
327 updated:
328 description:
329 - Update datetime.
330 returned: always
331 type: str
332 sample: "2025-01-15T09"
333 enabled:
334 description:
335 - Indicate whether the certificate is enabled.
336 returned: always
337 type: str
338 sample: true
339 recovery_level:
340 description:
341 - Reflects the deletion recovery level currently in effect for certificates in the current vault.
342 - If it contains 'Purgeable' the certificate can be permanently deleted by a privileged user,
343 - Otherwise, only the system can purge the certificate, at the end of the retention interval.
344 returned: always
345 type: str
346 sample: Recoverable+Purgeable
347 '''
348
349 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common import AzureRMModuleBase
350
351 try:
352 from azure.keyvault.certificates import CertificateClient
353 from azure.core.exceptions import ResourceNotFoundError
354 import base64
355 except ImportError:
356 # This is handled in azure_rm_common
357 pass
358
359
360 def certificatebundle_to_dict(certificate):
361 response = dict(policy=dict(), properties=dict(), cert_data=None)
362 if certificate.cer is not None:
363 response['cert_data'] = base64.b64encode(certificate.cer).decode('utf-8')
364 response['name'] = certificate.name
365 if certificate.policy is not None:
366 response['policy']['issuer_name'] = certificate.policy._issuer_name
367 response['policy']['subject'] = certificate.policy._subject
368 response['policy']['exportable'] = certificate.policy._exportable
369 response['policy']['key_type'] = certificate.policy._key_type
370 response['policy']['reuse_key'] = certificate.policy._reuse_key
371 response['policy']['key_size'] = certificate.policy._key_size
372 response['policy']['key_curve_name'] = certificate.policy._key_curve_name
373 response['policy']['enhanced_key_usage'] = certificate.policy._enhanced_key_usage
374 response['policy']['key_usage'] = certificate.policy._key_usage
375 response['policy']['content_type'] = certificate.policy._content_type
376 response['policy']['validity_in_months'] = certificate.policy._validity_in_months
377 response['policy']['certificate_type'] = certificate.policy._certificate_type
378 response['policy']['certificate_transparency'] = certificate.policy._certificate_transparency
379 response['policy']['san_emails'] = certificate.policy._san_emails
380 response['policy']['san_dns_names'] = certificate.policy._san_dns_names
381 response['policy']['san_user_principal_names'] = certificate.policy._san_user_principal_names
382 response['policy']['attributes'] = dict()
383 if certificate.policy._attributes is not None:
384 response['policy']['attributes']['enabled'] = certificate.policy._attributes.enabled
385 response['policy']['attributes']['not_before'] = certificate.policy._attributes.not_before
386 response['policy']['attributes']['expires'] = certificate.policy._attributes.expires
387 response['policy']['attributes']['created'] = certificate.policy._attributes.created
388 response['policy']['attributes']['updated'] = certificate.policy._attributes.updated
389 response['policy']['attributes']['recoverable_days'] = certificate.policy._attributes.recoverable_days
390 response['policy']['attributes']['recovery_level'] = certificate.policy._attributes.recovery_level
391 else:
392 response['policy']['attributes'] = None
393 if certificate.policy._lifetime_actions is not None:
394 response['policy']['lifetime_actions'] = []
395 for item in certificate.policy._lifetime_actions:
396 response['policy']['lifetime_actions'].append(dict(action=item.action,
397 lifetime_percentage=item.lifetime_percentage,
398 days_before_expiry=item.days_before_expiry))
399 else:
400 response['policy']['lifetime_actions'] = None
401 else:
402 response['policy'] = None
403
404 if certificate.properties is not None:
405 response['properties']['attributes'] = dict(enabled=certificate.properties._attributes.enabled,
406 not_before=certificate.properties._attributes.not_before,
407 expires=certificate.properties._attributes.expires,
408 created=certificate.properties._attributes.created,
409 updated=certificate.properties._attributes.updated,
410 recovery_level=certificate.properties._attributes.recovery_level)
411 response['properties']['id'] = certificate.properties._id
412 response['properties']['vault_id'] = certificate.properties._vault_id.vault_url if certificate.properties._vault_id is not None else None
413 response['properties']['x509_thumbprint'] = base64.b64encode(certificate.properties._x509_thumbprint).decode('utf-8')
414 response['properties']['tags'] = certificate.properties._tags
415 else:
416 response['properties'] = None
417
418 return response
419
420
421 def deleted_certificatebundle_to_dict(certificate):
422 response = dict(policy=dict(), properties=dict(), cert_data=None)
423 if certificate.cer is not None:
424 response['cert_data'] = str(certificate.cer)
425 response['name'] = certificate.name
426 response['recovery_id'] = certificate._recovery_id
427 response['scheduled_purge_date'] = certificate._scheduled_purge_date
428 response['deleted_on'] = certificate._deleted_on
429 if certificate.policy is not None:
430 response['policy']['issuer_name'] = certificate.policy._issuer_name
431 response['policy']['subject'] = certificate.policy._subject
432 response['policy']['exportable'] = certificate.policy._exportable
433 response['policy']['key_type'] = certificate.policy._key_type
434 response['policy']['key_size'] = certificate.policy._key_size
435 response['policy']['reuse_key'] = certificate.policy._reuse_key
436 response['policy']['key_curve_name'] = certificate.policy._key_curve_name
437 response['policy']['enhanced_key_usage'] = certificate.policy._enhanced_key_usage
438 response['policy']['key_usage'] = certificate.policy._key_usage
439 response['policy']['content_type'] = certificate.policy._content_type
440 response['policy']['validity_in_months'] = certificate.policy._validity_in_months
441 response['policy']['certificate_type'] = certificate.policy._certificate_type
442 response['policy']['certificate_transparency'] = certificate.policy._certificate_transparency
443 response['policy']['san_emails'] = certificate.policy._san_emails
444 response['policy']['san_dns_names'] = certificate.policy._san_dns_names
445 response['policy']['san_user_principal_names'] = certificate.policy._san_user_principal_names
446 response['policy']['attributes'] = dict()
447 if certificate.policy._attributes is not None:
448 response['policy']['attributes']['enabled'] = certificate.policy._attributes.enabled
449 response['policy']['attributes']['not_before'] = certificate.policy._attributes.not_before
450 response['policy']['attributes']['expires'] = certificate.policy._attributes.expires
451 response['policy']['attributes']['created'] = certificate.policy._attributes.created
452 response['policy']['attributes']['updated'] = certificate.policy._attributes.updated
453 response['policy']['attributes']['recoverable_days'] = certificate.policy._attributes.recoverable_days
454 response['policy']['attributes']['recovery_level'] = certificate.policy._attributes.recovery_level
455 else:
456 response['policy']['attributes'] = None
457 if certificate.policy._lifetime_actions is not None:
458 response['policy']['lifetime_actions'] = []
459 for item in certificate.policy._lifetime_actions:
460 response['policy']['lifetime_actions'].append(dict(action=item.action,
461 lifetime_percentage=item.lifetime_percentage,
462 days_before_expiry=item.days_before_expiry))
463 else:
464 response['policy']['lifetime_actions'] = None
465 else:
466 response['policy'] = None
467
468 if certificate.properties is not None:
469 response['properties']['attributes'] = dict(enabled=certificate.properties._attributes.enabled,
470 not_before=certificate.properties._attributes.not_before,
471 expires=certificate.properties._attributes.expires,
472 created=certificate.properties._attributes.created,
473 updated=certificate.properties._attributes.updated,
474 recovery_level=certificate.properties._attributes.recovery_level)
475 response['properties']['id'] = certificate.properties._id
476 response['properties']['vault_id'] = certificate.properties._vault_id.vault_url if certificate.properties._vault_id is not None else None
477 response['properties']['x509_thumbprint'] = base64.b64encode(certificate.properties._x509_thumbprint).decode('utf-8')
478 response['properties']['tags'] = certificate.properties._tags
479 else:
480 response['properties'] = None
481 return response
482
483
484 class AzureRMKeyVaultCertificateInfo(AzureRMModuleBase):
485 def __init__(self):
486 self.module_arg_spec = dict(version=dict(type='str'),
487 name=dict(type='str'),
488 vault_uri=dict(type='str', required=True),
489 show_deleted_certificate=dict(type='bool', default=False),
490 tags=dict(type='list', elements='str'))
491
492 self.vault_uri = None
493 self.name = None
494 self.version = None
495 self.show_deleted_certificate = False
496 self.tags = None
497
498 self.results = dict(changed=False)
499 self._client = None
500
501 super(AzureRMKeyVaultCertificateInfo,
502 self).__init__(derived_arg_spec=self.module_arg_spec,
503 supports_check_mode=True,
504 supports_tags=False,
505 facts_module=True)
506
507 def exec_module(self, **kwargs):
508 """Main module execution method"""
509
510 for certificate in list(self.module_arg_spec.keys()):
511 if hasattr(self, certificate):
512 setattr(self, certificate, kwargs[certificate])
513
514 self._client = self.get_keyvault_client()
515
516 if self.name:
517 if self.show_deleted_certificate:
518 self.results['certificates'] = self.get_deleted_certificate()
519 else:
520 if self.version is not None:
521 self.results['certificates'] = self.get_certificate_version()
522 else:
523 self.results['certificates'] = self.get_certificate()
524 else:
525 if self.show_deleted_certificate:
526 self.results['certificates'] = self.list_deleted_certificates()
527
528 return self.results
529
530 def get_keyvault_client(self):
531
532 return CertificateClient(vault_url=self.vault_uri, credential=self.azure_auth.azure_credential_track2)
533
534 def get_certificate(self):
535 '''
536 Gets the certificate fact of the specified certificate in key vault.
537
538 :return: deserialized certificate state dictionary
539 '''
540 self.log("Get the certificate {0}".format(self.name))
541
542 results = []
543 try:
544 response = self._client.get_certificate(certificate_name=self.name)
545
546 if response:
547 response = certificatebundle_to_dict(response)
548 if self.has_tags(response['properties']['tags'], self.tags):
549 self.log("Response : {0}".format(response))
550 results.append(response)
551
552 except ResourceNotFoundError as ec:
553 self.log("Did not find the key vault certificate {0}: {1}".format(
554 self.name, str(ec)))
555 except Exception as ec2:
556 self.fail("Find the key vault certificate got exception, exception as {0}".format(str(ec2)))
557 return results
558
559 def get_deleted_certificate(self):
560 '''
561 Gets the deleted certificate facts in key vault.
562
563 :return: deserialized certificate state dictionary
564 '''
565 self.log("Get the certificate {0}".format(self.name))
566
567 results = []
568 try:
569 response = self._client.get_deleted_certificate(certificate_name=self.name)
570 if response:
571 response = deleted_certificatebundle_to_dict(response)
572 if self.has_tags(response['properties'].get('tags'), self.tags):
573 self.log("Response : {0}".format(response))
574 results.append(response)
575
576 except ResourceNotFoundError as ec:
577 self.log("Did not find the key vault certificate {0}: {1}".format(self.name, str(ec)))
578 except Exception as ec2:
579 self.fail("Find the key vault certificate got exception, exception as {0}".format(str(ec2)))
580 return results
581
582 def get_certificate_version(self):
583 '''
584 Lists certificates versions.
585
586 :return: deserialized versions of certificate, includes certificate identifier, attributes and tags
587 '''
588 self.log("Get the certificate versions {0}".format(self.name))
589
590 try:
591 response = self._client.get_certificate_version(certificate_name=self.name, version=self.version)
592 self.log("Response : {0}".format(response))
593
594 if response:
595 res = certificatebundle_to_dict(response)
596 if self.has_tags(res['properties'].get('tags'), self.tags):
597 return res
598 except Exception as e:
599 self.fail("Did not find certificate versions {0} : {1}.".format(
600 self.name, str(e)))
601
602 def list_deleted_certificates(self):
603 '''
604 Lists deleted certificates in specific key vault.
605
606 :return: deserialized certificates, includes certificate identifier, attributes and tags.
607 '''
608 self.log("Get the key vaults in current subscription")
609
610 results = []
611 try:
612 response = self._client.list_deleted_certificates()
613 self.log("Response : {0}".format(response))
614
615 if response:
616 for item in response:
617 item = deleted_certificatebundle_to_dict(item)
618 if self.has_tags(item['properties'].get('tags'), self.tags):
619 results.append(item)
620 except Exception as e:
621 self.fail("Did not find certificate in current key vault {0}.".format(str(e)))
622 return results
623
624
625 def main():
626 """Main execution"""
627 AzureRMKeyVaultCertificateInfo()
628
629
630 if __name__ == '__main__':
631 main()