Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_keyvaultcertificate.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
13 version_added: "3.4.0"
14 short_description: Managed keyvault certificate
15 description:
16 - Managed keyvault certificate.
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.
27 type: str
28 required: True
29 policy:
30 description:
31 - The management policy for the certificate.
32 - When generating a new certificate, if no policy is set, the default policy will be used.
33 type: dict
34 suboptions:
35 subject:
36 description:
37 - The subject name of the certificate. Should be a valid X509 distinguished name.
38 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
39 - This will be ignored when importing a certificate; the subject will be parsed from the imported certificate.
40 type: str
41 issuer_name:
42 description:
43 - Name of the referenced issuer object or reserved names. For example C(self) and C(unknown).
44 type: str
45 choices:
46 - self
47 - unknown
48 exportable:
49 description:
50 - Indicates if the private key can be exported. For valid values, see KeyType.
51 type: bool
52 key_type:
53 description:
54 - The type of key pair to be used for the certificate.
55 type: str
56 choices:
57 - EC
58 - EC-HSM
59 - RSA
60 - RSA-HSM
61 - oct
62 - oct-HSM
63 key_size:
64 description:
65 - The key size in bits. For example C(2048), C(3072), or C(4096) for RSA.
66 type: int
67 reuse_key:
68 description:
69 - Indicates if the same key pair will be used on certificate renewal.
70 type: bool
71 key_curve_name:
72 description:
73 - Elliptic curve name. For valid values, see KeyCurveName.
74 type: str
75 choices:
76 - P-256
77 - P-384
78 - P-521
79 - P-256K
80 enhanced_key_usage:
81 description:
82 - The extended ways the key of the certificate can be used.
83 type: list
84 elements: str
85 content_type:
86 description:
87 - he media type (MIME type) of the secret backing the certificate.
88 type: str
89 default: application/x-pkcs12
90 choices:
91 - application/x-pkcs12
92 - application/x-pem-file
93 key_usage:
94 description:
95 - The extended ways the key of the certificate can be used.
96 type: list
97 elements: str
98 choices:
99 - digitalSignature
100 - nonRepudiation
101 - keyEncipherment
102 - dataEncipherment
103 - keyAgreement
104 - keyCertSign
105 - cRLSign
106 - encipherOnly
107 - decipherOnly
108 validity_in_months:
109 description:
110 - The duration that the certificate is valid in months.
111 type: int
112 lifetime_actions:
113 description:
114 - Actions that will be performed by Key Vault over the lifetime of a certificate.
115 type: list
116 elements: dict
117 suboptions:
118 action:
119 description:
120 - The type of the action.
121 type: str
122 choices:
123 - EmailContacts
124 - AutoRenew
125 lifetime_percentage:
126 description:
127 - Percentage of lifetime at which to trigger. Value should be between 1 and 99.
128 type: int
129 days_before_expiry:
130 description:
131 - Days before expiry to attempt renewal.
132 - Value should be between 1 and `validity_in_months` multiplied by 27.
133 - If validity_in_months is 36, then value should be between 1 and 972 (36 * 27).
134 type: int
135 certificate_type:
136 description:
137 - Type of certificate to be requested from the issuer provider.
138 type: str
139 san_emails:
140 description:
141 - Subject alternative emails of the X509 object.
142 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
143 type: list
144 elements: str
145 certificate_transparency:
146 description:
147 - Indicates if the certificates generated under this policy should be published to certificate transparency logs.
148 type: bool
149 san_dns_names:
150 description:
151 - Subject alternative DNS names of the X509 object.
152 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
153 type: list
154 elements: str
155 san_user_principal_names:
156 description:
157 - Subject alternative user principal names of the X509 object.
158 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
159 type: list
160 elements: str
161 enabled:
162 description:
163 - Whether the certificate is enabled for use.
164 type: bool
165 password:
166 description:
167 - If the private key in the passed in certificate is encrypted, it is the password used for encryption.
168 type: str
169 cert_data:
170 description:
171 - Aan existing valid certificate, containing a private key, into Azure Key Vault.
172 type: str
173 state:
174 description:
175 - State of the keyvault certificate.
176 type: str
177 required: True
178 choices:
179 - generate
180 - import
181 - delete
182 - purge
183 - recover
184 - merge
185 - update
186
187 extends_documentation_fragment:
188 - azure.azcollection.azure
189 - azure.azcollection.azure_tags
190
191 author:
192 - xuzhang3 (@xuzhang3)
193 - Fred-sun (@Fred-sun)
194
195 '''
196
197 EXAMPLES = '''
198 - name: Import a keyvault certificate
199 azure_rm_keyvaultcertificate:
200 vault_uri: https://vault{{ rpfx }}.vault.azure.net
201 name: fredcerticate
202 enabled: true
203 password: Password@****
204 cert_data: "{{ lookup('file', 'cert.pem') }}"
205 state: import
206 tags:
207 key1: value1
208
209 - name: Generate a keyvault certificate
210 azure_rm_keyvaultcertificate:
211 vault_uri: https://vault{{ rpfx }}.vault.azure.net
212 name: fredcerticate
213 policy:
214 subject: 'CN=Anhui02'
215 issuer_name: self
216 exportable: true
217 key_type: RSA
218 key_size: 2048
219 san_emails:
220 - [email protected]
221 content_type: 'application/x-pkcs12'
222 validity_in_months: 36
223 lifetime_actions:
224 - action: EmailContacts
225 days_before_expiry: 10
226 enabled: true
227 state: generate
228
229 - name: Rotate Key Vault Certificate with a renewed PEM bundle
230 azure_rm_keyvaultcertificate:
231 vault_uri: https://vault{{ rpfx }}.vault.azure.net
232 name: fredcerticate
233 cert_data: "{{ lookup('file', 'new_cert.pem') }}" # PEM must include private key + cert
234 policy:
235 content_type: "application/x-pem-file"
236 state: import
237
238 - name: Rotate Key Vault Certificate with a renewed PFX bundle
239 azure_rm_keyvaultcertificate:
240 vault_uri: https://vault{{ rpfx }}.vault.azure.net
241 name: fredcerticate
242 cert_data: "{{ lookup('file', 'new_cert.pfx') | b64encode }}" # PFX must include private key + cert
243 password: Password@****
244 policy:
245 content_type: "application/x-pkcs12"
246 state: import
247
248 - name: Update the keyvault certificate
249 azure_rm_keyvaultcertificate:
250 vault_uri: https://vault{{ rpfx }}.vault.azure.net
251 name: fredcerticate
252 policy:
253 subject: 'CN=Anhui'
254 issuer_name: self
255 exportable: true
256 key_type: RSA
257 key_size: 2048
258 san_emails:
259 - [email protected]
260 content_type: 'application/x-pkcs12'
261 validity_in_months: 36
262 lifetime_actions:
263 - action: EmailContacts
264 days_before_expiry: 10
265 enabled: true
266 state: update
267
268 - name: Purge the keyvault certificate
269 azure_rm_keyvaultcertificate:
270 vault_uri: https://vault{{ rpfx }}.vault.azure.net
271 name: fredcerticate
272 state: purge
273
274 - name: Recover the keyvault certificate
275 azure_rm_keyvaultcertificate:
276 vault_uri: https://vault{{ rpfx }}.vault.azure.net
277 name: fredcerticate
278 state: recover
279
280 - name: Delete the keyvault certificate
281 azure_rm_keyvaultcertificate:
282 vault_uri: https://vault{{ rpfx }}.vault.azure.net
283 name: fredcerticate
284 state: absent
285 '''
286
287 RETURN = '''
288 certificates:
289 description:
290 - The facts of certificates in Azure Key Vault.
291 returned: always
292 type: complex
293 contains:
294 cert_data:
295 description:
296 - CER contents of the X509 certificate.
297 type: str
298 returned: always
299 sample: "MIID*****************0pRjXE"
300 name:
301 description:
302 - The name of the certificate.
303 type: str
304 returned: always
305 sample: testcert
306 deleted_on:
307 description:
308 - The time when the certificate was deleted, in UTC.
309 returned: always
310 type: str
311 sample: 2025-01-14T09"
312 recovery_id:
313 description:
314 - The url of the recovery object, used to identify and recover the deleted certificate.
315 type: str
316 returned: always
317 sample: "https://vaultrfred01.vault.azure.net/deletedcertificates/cert02"
318 scheduled_purge_date:
319 description:
320 - The time when the certificate is scheduled to be purged, in UTC.
321 returned: always
322 type: dict
323 sample: 2025-02-14T09"
324 policy:
325 description:
326 - The management policy of the deleted certificate.
327 returned: always
328 type: complex
329 contains:
330 attributes:
331 description:
332 - Certificate attributes.
333 type: complex
334 returned: always
335 contains:
336 created:
337 description:
338 - Creation datetime.
339 returned: always
340 type: str
341 sample: "2025-01-14T09:41:20+00:00"
342 not_before:
343 description:
344 - Not before datetime.
345 type: str
346 sample: None
347 expires:
348 description:
349 - Expiration datetime.
350 type: str
351 sample: None
352 updated:
353 description:
354 - Update datetime.
355 returned: always
356 type: str
357 sample: "2025-01-15T09:41:20+00:00"
358 enabled:
359 description:
360 - Indicate whether the certificate is enabled.
361 returned: always
362 type: str
363 sample: true
364 recovery_level:
365 description:
366 - Reflects the deletion recovery level currently in effect for certificates in the current vault.
367 - If it contains 'Purgeable' the certificate can be permanently deleted by a privileged user,
368 - Otherwise, only the system can purge the certificate, at the end of the retention interval.
369 returned: always
370 type: str
371 sample: None
372 recoverable_days:
373 description:
374 - Reflects the deletion recovery days.
375 type: int
376 returned: always
377 sample: None
378 issuer_name:
379 description:
380 - Name of the referenced issuer object or reserved names.
381 type: str
382 returned: always
383 sample: Self
384 subject:
385 description:
386 - The subject name of the certificate.
387 - Should be a valid X509 distinguished name.
388 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
389 - This will be ignored when importing a certificate; the subject will be parsed from the imported certificate.
390 type: str
391 returned: always
392 sample: CN=anhui.com
393 san_emails:
394 description:
395 - Subject alternative emails of the X509 object.
396 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
397 type: str
398 returned: always
399 sample: None
400 san_dns_names:
401 description:
402 - Subject alternative DNS names of the X509 object.
403 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
404 type: str
405 returned: always
406 sample: None
407 san_user_principal_names:
408 description:
409 - Subject alternative user principal names of the X509 object.
410 - Either subject or one of the subject alternative name parameters are required for creating a certificate.
411 type: str
412 returned: always
413 sample: None
414 exportable:
415 description:
416 - Indicates if the private key can be exported.
417 type: bool
418 returned: always
419 sample: true
420 key_type:
421 description:
422 - The type of key pair to be used for the certificate.
423 type: str
424 returned: always
425 sample: RSA
426 key_size:
427 description:
428 - The key size in bits.
429 type: int
430 returned: always
431 sample: 2048
432 reuse_key:
433 description:
434 - Indicates if the same key pair will be used on certificate renewal.
435 type: bool
436 returned: always
437 sample: false
438 key_curve_name:
439 description:
440 - Elliptic curve name. For valid values, see KeyCurveName.
441 type: str
442 returned: always
443 sample: None
444 enhanced_key_usage:
445 description:
446 - The extended ways the key of the certificate can be used.
447 type: list
448 returned: always
449 sample: ['1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2']
450 key_usage:
451 description:
452 - List of key usages.
453 type: list
454 returned: always
455 sample: ["digitalSignature", "keyEncipherment"]
456 content_type:
457 description:
458 - If not specified, the media type (MIME type) of the secret backing the certificate.
459 type: str
460 returned: always
461 sample: application/x-pkcs12
462 validity_in_months:
463 description:
464 - The duration that the certificate is valid in months.
465 type: int
466 returned: always
467 sample: 12
468 lifetime_actions:
469 description:
470 - Actions that will be performed by Key Vault over the lifetime of a certificate.
471 type: list
472 returned: always
473 sample: [{'action': 'AutoRenew', 'days_before_expiry': None, 'lifetime_percentage': 80}]
474 certificate_type:
475 description:
476 - Type of certificate to be requested from the issuer provider.
477 type: str
478 returned: str
479 sample: None
480 certificate_transparency:
481 description:
482 - Indicates if the certificates generated under this policy should be published to certificate transparency logs.
483 type: bool
484 returned: always
485 sample: None
486 properties:
487 description:
488 - The certificate's properties.
489 type: complex
490 returned: always
491 contains:
492 id:
493 description:
494 - Id of the certificate. If specified all other 'Id' arguments should be omitted.
495 type: str
496 returned: always
497 sample: "https://vaultrfred01.vault.azure.net/certificates/cert02/62409e6304c642f193209729b8360d2c"
498 vault_id:
499 description:
500 - ID of the Key Vault.
501 type: str
502 returned: always
503 sample: "https://vaultrfred01.vault.azure.net"
504 x509_thumbprint:
505 description:
506 - The X509 Thumbprint of the Key Vault Certificate represented as a hexadecimal string.
507 type: str
508 returned: always
509 sample: 1blAnHN9ddng0qh1pYoUDY2lp1E=
510 tags:
511 description:
512 - List of the certificate tags.
513 type: dict
514 returned: always
515 sample: {'key': 'value'}
516 attributes:
517 description:
518 - Certificate attributes.
519 type: complex
520 returned: always
521 contains:
522 created:
523 description:
524 - Creation datetime.
525 returned: always
526 type: str
527 sample: "2025-01-14T09"
528 not_before:
529 description:
530 - Not before datetime.
531 type: str
532 sample: "2025-02-14T09"
533 expires:
534 description:
535 - Expiration datetime.
536 type: str
537 sample: "2025-03-14T09"
538 updated:
539 description:
540 - Update datetime.
541 returned: always
542 type: str
543 sample: "2025-01-15T09"
544 enabled:
545 description:
546 - Indicate whether the certificate is enabled.
547 returned: always
548 type: str
549 sample: true
550 recovery_level:
551 description:
552 - Reflects the deletion recovery level currently in effect for certificates in the current vault.
553 - If it contains 'Purgeable' the certificate can be permanently deleted by a privileged user,
554 - Otherwise, only the system can purge the certificate, at the end of the retention interval.
555 returned: always
556 type: str
557 sample: Recoverable+Purgeable
558 '''
559
560 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
561
562 try:
563 from azure.keyvault.certificates import CertificateClient, CertificatePolicy, LifetimeAction
564 import base64
565 import hashlib
566 try:
567 from cryptography.hazmat.primitives import hashes
568 from cryptography.hazmat.primitives.serialization import pkcs12
569 except Exception:
570 hashes = None
571 pkcs12 = None
572 from azure.core.polling import LROPoller
573 except ImportError:
574 # This is handled in azure_rm_common
575 pass
576
577
578 def certificatebundle_to_dict(certificate):
579 response = dict(policy=dict(), properties=dict(), cert_data=None)
580 if certificate.cer is not None:
581 response['cert_data'] = base64.b64encode(certificate.cer).decode('utf-8')
582 response['name'] = certificate.name
583 if certificate.policy is not None:
584 response['policy']['issuer_name'] = certificate.policy._issuer_name
585 response['policy']['subject'] = certificate.policy._subject
586 response['policy']['exportable'] = certificate.policy._exportable
587 response['policy']['key_type'] = certificate.policy._key_type
588 response['policy']['key_size'] = certificate.policy._key_size
589 response['policy']['reuse_key'] = certificate.policy._reuse_key
590 response['policy']['key_curve_name'] = certificate.policy._key_curve_name
591 response['policy']['enhanced_key_usage'] = certificate.policy._enhanced_key_usage
592 response['policy']['key_usage'] = certificate.policy._key_usage
593 response['policy']['content_type'] = certificate.policy._content_type
594 response['policy']['validity_in_months'] = certificate.policy._validity_in_months
595 response['policy']['certificate_type'] = certificate.policy._certificate_type
596 response['policy']['certificate_transparency'] = certificate.policy._certificate_transparency
597 response['policy']['san_emails'] = certificate.policy._san_emails
598 response['policy']['san_dns_names'] = certificate.policy._san_dns_names
599 response['policy']['san_user_principal_names'] = certificate.policy._san_user_principal_names
600 response['policy']['attributes'] = dict()
601 if certificate.policy._attributes is not None:
602 response['policy']['attributes']['enabled'] = certificate.policy._attributes.enabled
603 response['policy']['attributes']['not_before'] = certificate.policy._attributes.not_before
604 response['policy']['attributes']['expires'] = certificate.policy._attributes.expires
605 response['policy']['attributes']['created'] = certificate.policy._attributes.created
606 response['policy']['attributes']['updated'] = certificate.policy._attributes.updated
607 response['policy']['attributes']['recoverable_days'] = certificate.policy._attributes.recoverable_days
608 response['policy']['attributes']['recovery_level'] = certificate.policy._attributes.recovery_level
609 else:
610 response['policy']['attributes'] = None
611 if certificate.policy._lifetime_actions is not None:
612 response['policy']['lifetime_actions'] = []
613 for item in certificate.policy._lifetime_actions:
614 response['policy']['lifetime_actions'].append(dict(action=item.action,
615 lifetime_percentage=item.lifetime_percentage,
616 days_before_expiry=item.days_before_expiry))
617 else:
618 response['policy']['lifetime_actions'] = None
619 else:
620 response['policy'] = None
621
622 if certificate.properties is not None:
623 response['properties']['attributes'] = dict(enabled=certificate.properties._attributes.enabled,
624 not_before=certificate.properties._attributes.not_before,
625 expires=certificate.properties._attributes.expires,
626 created=certificate.properties._attributes.created,
627 updated=certificate.properties._attributes.updated,
628 recovery_level=certificate.properties._attributes.recovery_level)
629 response['properties']['id'] = certificate.properties._id
630 response['properties']['vault_id'] = certificate.properties._vault_id.vault_url if certificate.properties._vault_id is not None else None
631 response['properties']['x509_thumbprint'] = base64.b64encode(certificate.properties._x509_thumbprint).decode('utf-8')
632 response['properties']['tags'] = certificate.properties._tags
633 else:
634 response['properties'] = None
635
636 return response
637
638
639 def policy_bundle_to_dict(policy):
640 result = dict()
641 if policy is not None:
642 result['issuer_name'] = policy._issuer_name
643 result['subject'] = policy._subject
644 result['exportable'] = policy._exportable
645 result['key_type'] = policy._key_type
646 result['key_size'] = policy._key_size
647 result['reuse_key'] = policy._reuse_key
648 result['key_curve_name'] = policy._key_curve_name
649 result['enhanced_key_usage'] = policy._enhanced_key_usage
650 result['key_usage'] = policy._key_usage
651 result['content_type'] = policy._content_type
652 result['validity_in_months'] = policy._validity_in_months
653 result['certificate_type'] = policy._certificate_type
654 result['certificate_transparency'] = policy._certificate_transparency
655 result['san_emails'] = policy._san_emails
656 result['san_dns_names'] = policy._san_dns_names
657 result['san_user_principal_names'] = policy._san_user_principal_names
658 result['attributes'] = dict()
659 if policy._attributes is not None:
660 result['attributes']['enabled'] = policy._attributes.enabled
661 result['attributes']['not_before'] = policy._attributes.not_before
662 result['attributes']['expires'] = policy._attributes.expires
663 result['attributes']['created'] = policy._attributes.created
664 result['attributes']['updated'] = policy._attributes.updated
665 result['attributes']['recoverable_days'] = policy._attributes.recoverable_days
666 result['attributes']['recovery_level'] = policy._attributes.recovery_level
667 else:
668 result['attributes'] = None
669 if policy._lifetime_actions is not None:
670 result['lifetime_actions'] = []
671 for item in policy._lifetime_actions:
672 result['lifetime_actions'].append(dict(action=item.action,
673 lifetime_percentage=item.lifetime_percentage,
674 days_before_expiry=item.days_before_expiry))
675 else:
676 result['lifetime_actions'] = None
677 else:
678 result = None
679
680 return result
681
682
683 def deleted_certificatebundle_to_dict(certificate):
684 response = dict(policy=dict(), properties=dict(), cert_data=None)
685 if certificate.cer is not None:
686 response['cert_data'] = str(certificate.cer)
687 response['name'] = certificate.name
688 response['recovery_id'] = certificate._recovery_id
689 response['scheduled_purge_date'] = certificate._scheduled_purge_date
690 response['deleted_on'] = certificate._deleted_on
691 if certificate.cer is not None:
692 response['cert_data'] = str(certificate.cer)
693 if certificate.policy is not None:
694 response['policy']['issuer_name'] = certificate.policy._issuer_name
695 response['policy']['subject'] = certificate.policy._subject
696 response['policy']['exportable'] = certificate.policy._exportable
697 response['policy']['key_type'] = certificate.policy._key_type
698 response['policy']['key_size'] = certificate.policy._key_size
699 response['policy']['reuse_key'] = certificate.policy._reuse_key
700 response['policy']['key_curve_name'] = certificate.policy._key_curve_name
701 response['policy']['enhanced_key_usage'] = certificate.policy._enhanced_key_usage
702 response['policy']['key_usage'] = certificate.policy._key_usage
703 response['policy']['content_type'] = certificate.policy._content_type
704 response['policy']['validity_in_months'] = certificate.policy._validity_in_months
705 response['policy']['certificate_type'] = certificate.policy._certificate_type
706 response['policy']['certificate_transparency'] = certificate.policy._certificate_transparency
707 response['policy']['san_emails'] = certificate.policy._san_emails
708 response['policy']['san_dns_names'] = certificate.policy._san_dns_names
709 response['policy']['san_user_principal_names'] = certificate.policy._san_user_principal_names
710 response['policy']['attributes'] = dict()
711 if certificate.policy._attributes is not None:
712 response['policy']['attributes']['enabled'] = certificate.policy._attributes.enabled
713 response['policy']['attributes']['not_before'] = certificate.policy._attributes.not_before
714 response['policy']['attributes']['expires'] = certificate.policy._attributes.expires
715 response['policy']['attributes']['created'] = certificate.policy._attributes.created
716 response['policy']['attributes']['updated'] = certificate.policy._attributes.updated
717 response['policy']['attributes']['recoverable_days'] = certificate.policy._attributes.recoverable_days
718 response['policy']['attributes']['recovery_level'] = certificate.policy._attributes.recovery_level
719 else:
720 response['policy']['attributes'] = None
721 if certificate.policy._lifetime_actions is not None:
722 response['policy']['lifetime_actions'] = []
723 for item in certificate.policy._lifetime_actions:
724 response['policy']['lifetime_actions'].append(dict(action=item.action,
725 lifetime_percentage=item.lifetime_percentage,
726 days_before_expiry=item.days_before_expiry))
727 else:
728 response['policy']['lifetime_actions'] = None
729 else:
730 response['policy'] = None
731
732 if certificate.properties is not None:
733 response['properties']['attributes'] = dict(enabled=certificate.properties._attributes.enabled,
734 not_before=certificate.properties._attributes.not_before,
735 expires=certificate.properties._attributes.expires,
736 created=certificate.properties._attributes.created,
737 updated=certificate.properties._attributes.updated,
738 recovery_level=certificate.properties._attributes.recovery_level)
739 response['properties']['id'] = certificate.properties._id
740 response['properties']['vault_id'] = certificate.properties._vault_id.vault_url if certificate.properties._vault_id is not None else None
741 response['properties']['x509_thumbprint'] = base64.b64encode(certificate.properties._x509_thumbprint).decode('utf-8')
742 response['properties']['tags'] = certificate.properties._tags
743 else:
744 response['properties'] = None
745 return response
746
747
748 def _cert_data_thumbprint_sha1(cert_data_str, content_type=None, password=None):
749 """
750 Returns SHA-1 thumbprint (bytes) of the leaf certificate contained in cert_data_str.
751 Supports PEM ('-----BEGIN CERTIFICATE-----') and PKCS12 (application/x-pkcs12) if cryptography is available.
752 Returns None when parsing fails (caller should decide fallback behavior).
753 """
754 try:
755 # PEM: extract first CERT block and hash its DER
756 if "-----BEGIN CERTIFICATE-----" in cert_data_str:
757 lines = cert_data_str.strip().splitlines()
758 collecting = False
759 b64 = []
760 for ln in lines:
761 if ln.startswith("-----BEGIN CERTIFICATE-----"):
762 collecting = True
763 b64 = []
764 continue
765 if ln.startswith("-----END CERTIFICATE-----"):
766 collecting = False
767 der = base64.b64decode("".join(b64))
768 return hashlib.sha1(der).digest()
769 if collecting:
770 b64.append(ln.strip())
771
772 # PKCS#12 (PFX): parse via cryptography if available
773 if content_type and content_type.lower() in ("application/x-pkcs12", "application/x-pfx"):
774 if pkcs12 and hashes:
775 try:
776 raw = base64.b64decode(cert_data_str)
777 except Exception:
778 raw = cert_data_str.encode("utf-8", "ignore")
779 pk = pkcs12.load_key_and_certificates(raw, None if password in (None, "") else password.encode("utf-8"))
780 if pk and pk[1]:
781 return pk[1].fingerprint(hashes.SHA1())
782 return None
783
784 # Fallback: attempt base64->DER->SHA1
785 try:
786 der = base64.b64decode(cert_data_str)
787 return hashlib.sha1(der).digest()
788 except Exception:
789 return None
790 except Exception:
791 return None
792
793
794 policy_spec = dict(
795 issuer_name=dict(type='str', choices=['self', 'unknown']),
796 subject=dict(type='str'),
797 exportable=dict(type='bool',),
798 key_type=dict(type='str', choices=['EC', 'EC-HSM', 'RSA', 'RSA-HSM', 'oct', 'oct-HSM']),
799 key_size=dict(type='int'),
800 reuse_key=dict(type='bool',),
801 key_curve_name=dict(type='str', choices=['P-256', 'P-384', 'P-521', 'P-256K']),
802 enhanced_key_usage=dict(type='list', elements='str'),
803 key_usage=dict(
804 type='list',
805 elements='str',
806 choices=['digitalSignature', 'nonRepudiation', 'keyEncipherment', 'dataEncipherment',
807 'keyAgreement', 'keyCertSign', 'cRLSign', 'encipherOnly', 'decipherOnly']
808 ),
809 content_type=dict(type='str', default='application/x-pkcs12', choices=['application/x-pkcs12', 'application/x-pem-file']),
810 validity_in_months=dict(type='int',),
811 certificate_type=dict(type='str'),
812 certificate_transparency=dict(type='bool'),
813 san_emails=dict(type='list', elements='str'),
814 san_dns_names=dict(type='list', elements='str'),
815 san_user_principal_names=dict(type='list', elements='str'),
816 lifetime_actions=dict(
817 type='list',
818 elements='dict',
819 options=dict(
820 action=dict(type='str', choices=['EmailContacts', 'AutoRenew']),
821 lifetime_percentage=dict(type='int'),
822 days_before_expiry=dict(type='int')
823 )
824 ),
825 )
826
827
828 class AzureRMKeyVaultCertificate(AzureRMModuleBaseExt):
829 def __init__(self):
830 self.module_arg_spec = dict(name=dict(type='str', required=True),
831 vault_uri=dict(type='str', required=True),
832 policy=dict(type='dict', options=policy_spec),
833 enabled=dict(type='bool'),
834 password=dict(type='str', no_log=True),
835 cert_data=dict(type='str', no_log=True),
836 state=dict(
837 type='str',
838 required=True,
839 choices=['generate', 'import', 'delete', 'purge', 'update', 'recover', 'merge']))
840 self.vault_uri = None
841 self.name = None
842 self.policy = None
843 self.enabled = None
844 self.cert_data = None
845 self.password = None
846 self.state = None
847 self.tags = None
848
849 self.results = dict(changed=False)
850 self._client = None
851 required_if = [('state', 'import', ['cert_data'])]
852
853 super(AzureRMKeyVaultCertificate,
854 self).__init__(derived_arg_spec=self.module_arg_spec,
855 supports_check_mode=True,
856 supports_tags=True,
857 required_if=required_if,
858 facts_module=False)
859
860 def exec_module(self, **kwargs):
861 """Main module execution method"""
862
863 for key in list(self.module_arg_spec.keys()) + ['tags']:
864 if hasattr(self, key):
865 setattr(self, key, kwargs[key])
866 else:
867 setattr(self, key, None)
868
869 self._client = self.get_keyvault_client()
870 changed = False
871 response = None
872
873 del_response = self.get_deleted_certificate()
874 response = self.get_certificate()
875
876 if self.state == 'import' and del_response is not None and response is None:
877 self.fail("The certificate {0} is soft-deleted and recoverable; recover or purge before importing".format(self.name))
878
879 if self.state == 'delete':
880 if response is not None:
881 changed = True
882 if not self.check_mode:
883 response = self.delete_certificate()
884 elif self.state == 'purge':
885 if del_response is not None:
886 changed = True
887 if not self.check_mode:
888 response = self.purge_certificate()
889 elif self.state == 'merge':
890 if response is not None:
891 changed = True
892 if not self.check_mode:
893 response = self.merge_certificate()
894 else:
895 self.fail("The certificate not exist {0}".format(self.name))
896 elif self.state == 'recover':
897 if del_response is not None:
898 changed = True
899 if not self.check_mode:
900 response = self.recover_certificate()
901 else:
902 self.log("The certificate {0} exist or purged".format(self.name))
903 else:
904 if response is not None:
905 a = {}
906 b = dict(compare=[])
907
908 # if not self.default_compare({}, self.policy, response['policy'], '', dict(compare=[])):
909 if not self.default_compare(a, self.policy, response['policy'], '', b):
910 changed = True
911 if not self.check_mode:
912 response['policy'] = self.update_certificate_policy()
913
914 update_tags, self.tags = self.update_tags(response['properties']['tags'])
915 if update_tags or (self.enabled is not None and bool(self.enabled) != bool(response['properties']['attributes']['enabled'])):
916 changed = True
917 if not self.check_mode:
918 response = self.update_certificate_properties()
919
920 if self.state == 'import' and self.cert_data:
921 existing_thumb_b64 = response['properties'].get('x509_thumbprint')
922 existing_thumb = None
923 if existing_thumb_b64:
924 try:
925 existing_thumb = base64.b64decode(existing_thumb_b64)
926 except Exception:
927 existing_thumb = None
928
929 new_thumb = _cert_data_thumbprint_sha1(self.cert_data, (self.policy or {}).get('content_type'), password=self.password)
930
931 should_import = False
932 if new_thumb is None or existing_thumb is None:
933 should_import = True
934 else:
935 should_import = (new_thumb != existing_thumb)
936
937 if should_import:
938 changed = True
939 if not self.check_mode:
940 response = self.import_certificate()
941 else:
942 changed = True
943 if self.state == 'import':
944 if not self.check_mode:
945 response = self.import_certificate()
946 else:
947 if not self.check_mode:
948 response = self.create_certificate()
949
950 self.results['changed'] = changed
951 self.results['certificate'] = response
952
953 return self.results
954
955 def get_keyvault_client(self):
956
957 return CertificateClient(vault_url=self.vault_uri, credential=self.azure_auth.azure_credential_track2)
958
959 def get_certificate(self):
960 '''
961 Gets the certificate fact of the specified in key vault.
962
963 :return: deserialized certificate state dictionary
964 '''
965 self.log("Get the certificate {0}".format(self.name))
966
967 try:
968 return certificatebundle_to_dict(self._client.get_certificate(certificate_name=self.name))
969
970 except Exception as ec:
971 self.log("Did not find the key vault certificate {0}: {1}".format(self.name, str(ec)))
972
973 def create_certificate(self):
974 '''
975 Create the certificate in key vault.
976
977 :return: deserialized certificate state dictionary
978 '''
979 self.log("Create the certificate {0}".format(self.name))
980
981 lifetime_actions = []
982 for item in (self.policy.get('lifetime_actions') or []):
983 lifetime_actions.append(LifetimeAction(**item))
984
985 try:
986 if self.policy is None:
987 policy = CertificatePolicy.get_default()
988 else:
989 policy = CertificatePolicy(subject=self.policy.get('subject'),
990 issuer_name=self.policy.get('issuer_name'),
991 exportable=self.policy.get('exportable'),
992 key_type=self.policy.get('key_type'),
993 key_size=self.policy.get('key_size'),
994 san_emails=self.policy.get('san_emails'),
995 content_type=self.policy.get('content_type'),
996 validity_in_months=self.policy.get('validity_in_months'),
997 reuse_key=self.policy.get('reuse_key'),
998 key_curve_name=self.policy.get('key_curve_name'),
999 enhanced_key_usage=self.policy.get('enhanced_key_usage'),
1000 key_usage=self.policy.get('key_usage'),
1001 certificate_type=self.policy.get('certificate_type'),
1002 certificate_transparency=self.policy.get('certificate_transparency'),
1003 san_dns_names=self.policy.get('san_dns_names'),
1004 lifetime_actions=lifetime_actions,
1005 san_user_principal_names=self.policy.get('san_user_principal_names'))
1006 response = self._client.begin_create_certificate(certificate_name=self.name,
1007 policy=policy,
1008 enabled=self.enabled,
1009 tags=self.tags)
1010 if isinstance(response, LROPoller):
1011 return certificatebundle_to_dict(self.get_poller_result(response))
1012
1013 except Exception as ec:
1014 self.fail("Did not create the key vault certificate {0}: {1}".format(self.name, str(ec)))
1015
1016 def import_certificate(self):
1017 '''
1018 Import the certificate in key vault.
1019
1020 :return: deserialized certificate state dictionary
1021 '''
1022 self.log("Import the certificate {0}".format(self.name))
1023
1024 try:
1025 raw_bytes = None
1026 ct = (self.policy or {}).get('content_type')
1027 if ct and ct.lower() in ("application/x-pkcs12", "application/x-pfx"):
1028 # Expect cert_data to be Base64 text of the PFX; decode to raw bytes
1029 try:
1030 raw_bytes = base64.b64decode(self.cert_data)
1031 except Exception:
1032 # raw binary encoded as latin-1-safe text; avoid utf-8
1033 raw_bytes = self.cert_data.encode("latin-1")
1034 else:
1035 # PEM or unknown: treat as text content; SDK accepts PEM bytes
1036 raw_bytes = self.cert_data.encode('utf-8')
1037
1038 response = self._client.import_certificate(certificate_name=self.name,
1039 certificate_bytes=raw_bytes,
1040 enabled=self.enabled,
1041 password=self.password,
1042 tags=self.tags)
1043
1044 if response:
1045 response = certificatebundle_to_dict(response)
1046 return response
1047
1048 except Exception as ec:
1049 self.fail("Did not import the key vault certificate {0}: {1}".format(self.name, str(ec)))
1050
1051 def delete_certificate(self):
1052 '''
1053 Delete the certificate in key vault.
1054
1055 :return: deserialized certificate state dictionary
1056 '''
1057 self.log("Delete the certificate {0}".format(self.name))
1058
1059 try:
1060 response = self._client.begin_delete_certificate(certificate_name=self.name)
1061 if isinstance(response, LROPoller):
1062 return deleted_certificatebundle_to_dict(self.get_poller_result(response))
1063 self.log("Delete the certificate")
1064 except Exception as ec:
1065 self.fail("Did not delete the key vault certificate {0}: {1}".format(self.name, str(ec)))
1066
1067 def get_deleted_certificate(self):
1068 '''
1069 Gets the deleted certificate facts in key vault.
1070
1071 :return: deserialized certificate state dictionary
1072 '''
1073 self.log("Get the certificate {0}".format(self.name))
1074
1075 try:
1076 return deleted_certificatebundle_to_dict(self._client.get_deleted_certificate(certificate_name=self.name))
1077 except Exception as ec:
1078 self.log("Find the key vault certificate got exception, exception as {0}".format(str(ec)))
1079
1080 def recover_certificate(self):
1081 '''
1082 Recover the certificate in key vault.
1083
1084 :return: deserialized certificate state dictionary
1085 '''
1086 self.log("Recover the certificate {0}".format(self.name))
1087
1088 try:
1089 response = self._client.begin_recover_deleted_certificate(certificate_name=self.name)
1090 if isinstance(response, LROPoller):
1091 return certificatebundle_to_dict(self.get_poller_result(response))
1092
1093 except Exception as ec:
1094 self.fail("Did not recover the key vault certificate {0}: {1}".format(self.name, str(ec)))
1095
1096 def update_certificate_properties(self):
1097 '''
1098 Update the certificate properties in key vault.
1099
1100 :return: deserialized certificate state dictionary
1101 '''
1102 self.log("Merge the certificate {0}".format(self.name))
1103
1104 try:
1105 response = self._client.update_certificate_properties(certificate_name=self.name,
1106 version=None,
1107 enabled=self.enabled,
1108 tags=self.tags)
1109 if response is not None:
1110 return certificatebundle_to_dict(response)
1111 except Exception as ec:
1112 self.fail("Did not update the key vault certificate {0}: {1}".format(self.name, str(ec)))
1113
1114 def update_certificate_policy(self):
1115 '''
1116 Update the certificate policy in key vault.
1117
1118 :return: deserialized certificate state dictionary
1119 '''
1120 self.log("Update the certificate policy {0}".format(self.name))
1121
1122 lifetime_actions = []
1123 for item in (self.policy.get('lifetime_actions') or []):
1124 lifetime_actions.append(LifetimeAction(**item))
1125
1126 policy = CertificatePolicy(subject=self.policy.get('subject'),
1127 issuer_name=self.policy.get('issuer_name'),
1128 exportable=self.policy.get('exportable'),
1129 key_type=self.policy.get('key_type'),
1130 key_size=self.policy.get('key_size'),
1131 san_emails=self.policy.get('san_emails'),
1132 content_type=self.policy.get('content_type'),
1133 validity_in_months=self.policy.get('validity_in_months'),
1134 reuse_key=self.policy.get('reuse_key'),
1135 key_curve_name=self.policy.get('key_curve_name'),
1136 enhanced_key_usage=self.policy.get('enhanced_key_usage'),
1137 key_usage=self.policy.get('key_usage'),
1138 certificate_type=self.policy.get('certificate_type'),
1139 certificate_transparency=self.policy.get('certificate_transparency'),
1140 san_dns_names=self.policy.get('san_dns_names'),
1141 lifetime_actions=lifetime_actions,
1142 san_user_principal_names=self.policy.get('san_user_principal_names'))
1143 try:
1144 response = self._client.update_certificate_policy(certificate_name=self.name,
1145 policy=policy)
1146 if response is not None:
1147 return policy_bundle_to_dict(response)
1148
1149 except Exception as ec:
1150 self.fail("Did not update policy in the key vault certificate {0}: {1}".format(self.name, str(ec)))
1151
1152 def purge_certificate(self):
1153 '''
1154 Permanently deletes a deleted certificate.
1155 '''
1156 self.log("Permanently deletes the certificate {0}".format(self.name))
1157
1158 try:
1159 self._client.purge_deleted_certificate(certificate_name=self.name)
1160
1161 except Exception as ec:
1162 self.fail("Did not permanently delete the key vault certificate {0}: {1}".format(self.name, str(ec)))
1163
1164
1165 def main():
1166 """Main execution"""
1167 AzureRMKeyVaultCertificate()
1168
1169
1170 if __name__ == '__main__':
1171 main()