Debian Codegraph @

ansible_collections/purestorage/flashblade/plugins/modules/purefb_certs.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2024, Simon Dodsley ([email protected])
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
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["preview"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 ---
19 module: purefb_certs
20 version_added: '1.4.0'
21 short_description: Manage FlashBlade SSL Certificates
22 description:
23 - Create, delete, import and export FlashBlade SSL Certificates
24 author:
25 - Pure Storage Ansible Team (@sdodsley) <[email protected]>
26 options:
27 name:
28 description:
29 - Name of the SSL Certificate
30 type: str
31 default: management
32 state:
33 description:
34 - Action for the module to perform
35 - I(present) will create or re-create an SSL certificate
36 - I(absent) will delete an existing SSL certificate
37 - I(sign) will construct a Certificate Signing request (CSR)
38 - I(export) will export the exisitng SSL certificate
39 - I(import) will import a CA provided certificate.
40 default: present
41 choices: [ absent, present, import, export, sign ]
42 type: str
43 country:
44 type: str
45 description:
46 - The two-letter ISO code for the country where your organization is located
47 province:
48 type: str
49 description:
50 - The full name of the state or province where your organization is located
51 locality:
52 type: str
53 description:
54 - The full name of the city where your organization is located
55 organization:
56 type: str
57 description:
58 - The full and exact legal name of your organization.
59 - The organization name should not be abbreviated and should
60 include suffixes such as Inc, Corp, or LLC.
61 org_unit:
62 type: str
63 description:
64 - The department within your organization that is managing the certificate
65 common_name:
66 type: str
67 description:
68 - The fully qualified domain name (FQDN) of the current system
69 - For example, the common name for https://pureblade.example.com is
70 pureblade.example.com, or *.example.com for a wildcard certificate
71 - This can also be the management IP address of the system or the
72 shortname of the current system.
73 - Maximum of 64 characters
74 - If not provided this will default to the shortname of the system
75 email:
76 type: str
77 description:
78 - The email address used to contact your organization
79 key_size:
80 type: int
81 description:
82 - The key size in bits if you generate a new private key
83 default: 2048
84 choices: [ 1024, 2048, 4096 ]
85 days:
86 default: 3650
87 type: int
88 description:
89 - The number of valid days for the self-signed certificate being generated
90 - If not specified, the self-signed certificate expires after 3650 days.
91 generate:
92 default: false
93 type: bool
94 description:
95 - Generate a new private key.
96 - If not selected, the certificate will use the existing key
97 certificate:
98 aliases: [ contents ]
99 type: str
100 description:
101 - Required for I(import)
102 - A valid signed certicate in PEM format (Base64 encoded)
103 - Includes the "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" lines
104 - Does not exceed 3000 characters in length
105 intermediate_cert:
106 aliases: [ intermeadiate_cert ]
107 type: str
108 description:
109 - Intermeadiate certificate provided by the CA
110 key:
111 aliases: [ private_key ]
112 type: str
113 description:
114 - If the Certificate Signed Request (CSR) was not constructed on the system
115 or the private key has changed since construction the CSR, provide
116 a new private key here
117 passphrase:
118 type: str
119 description:
120 - Passphrase if the private key is encrypted
121 export_file:
122 type: str
123 description:
124 - Name of file to contain Certificate Signing Request when `status sign`
125 - Name of file to export the current SSL Certificate when `status export`
126 - File will be overwritten if it already exists
127 key_algorithm:
128 type: str
129 description:
130 - The key algorithm used to generate the certificate.
131 - This field can only be specified when creating a new self-signed certificate
132 choices: [ rsa, ec, ed448, ed25519 ]
133 version_added: "1.22.0"
134 extends_documentation_fragment:
135 - purestorage.flashblade.purestorage.fb
136 """
137
138 EXAMPLES = r"""
139 - name: Create SSL certifcate foo
140 purestorage.flashblade.purefb_certs:
141 name: foo
142 key_size: 4096
143 country: US
144 province: FL
145 locality: Miami
146 organization: "Acme Inc"
147 org_unit: "DevOps"
148 fb_url: 10.10.10.2
149 api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641
150
151 - name: Delete SSL certificate foo
152 purestorage.flashblade.purefb_certs:
153 name: foo
154 state: absent
155 fb_url: 10.10.10.2
156 api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641
157
158 - name: Request CSR
159 purestorage.flashblade.purefb_certs:
160 state: sign
161 fb_url: 10.10.10.2
162 api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641
163
164 - name: Request CSR with updated fields
165 purestorage.flashblade.purefb_certs:
166 state: sign
167 org_unit: Development
168 fb_url: 10.10.10.2
169 api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641
170
171 - name: Regenerate key for SSL foo
172 purestorage.flashblade.purefb_certs:
173 generate: true
174 name: foo
175 fb_url: 10.10.10.2
176 api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641
177
178 - name: Import SSL Cert foo and Private Key
179 purestorage.flashblade.purefb_certs:
180 state: import
181 name: foo
182 certificate: "{{lookup('file', 'example.crt') }}"
183 fb_url: 10.10.10.2
184 api_token: T-55a68eb5-c785-4720-a2ca-8b03903bf641
185 """
186
187 RETURN = r"""
188 """
189
190 HAS_PURESTORAGE = True
191 try:
192 from pypureclient.flashblade import (
193 CertificatePost,
194 CertificateSigningRequestPost,
195 Reference,
196 Certificate,
197 CertificatePatch,
198 )
199 except ImportError:
200 HAS_PURESTORAGE = False
201
202 HAS_PYCOUNTRY = True
203 try:
204 import pycountry
205 except ImportError:
206 HAS_PYCOUNTRY = False
207
208 import re
209 from ansible.module_utils.basic import AnsibleModule
210 from ansible_collections.purestorage.flashblade.plugins.module_utils.purefb import (
211 get_system,
212 purefb_argument_spec,
213 )
214
215
216 CERT_TYPE_VERSION = "2.15"
217 CSR_API_VERSION = "2.20"
218
219
220 def update_cert(module, blade):
221 """Update existing SSL Certificate"""
222 api_versions = list(blade.get_versions().items)
223 changed = False
224 if CSR_API_VERSION in api_versions:
225 current_cert = list(
226 blade.get_certificates(names=[module.params["name"]]).items
227 )[0]
228 new_cert = current_cert
229 if module.params["certificate"] and module.params["certificate"] != getattr(
230 current_cert, "certificate", None
231 ):
232 new_cert.certificate = module.params["certificate"]
233 else:
234 new_cert.certificate = getattr(current_cert, "certificate", None)
235 if module.params["common_name"] and module.params["common_name"] != getattr(
236 current_cert, "common_name", None
237 ):
238 new_cert.common_name = module.params["common_name"]
239 else:
240 new_cert.common_name = getattr(current_cert, "common_name", None)
241 if module.params["country"] and module.params["country"] != getattr(
242 current_cert, "country", None
243 ):
244 new_cert.country = module.params["country"]
245 else:
246 new_cert.country = getattr(current_cert, "country")
247 if module.params["email"] and module.params["email"] != getattr(
248 current_cert, "email", None
249 ):
250 new_cert.email = module.params["email"]
251 else:
252 new_cert.email = getattr(current_cert, "email", None)
253 if module.params["key_size"] and module.params["key_size"] != getattr(
254 current_cert, "key_size", None
255 ):
256 new_cert.key_size = module.params["key_size"]
257 else:
258 new_cert.key_size = getattr(current_cert, "key_size", None)
259 if module.params["locality"] and module.params["locality"] != getattr(
260 current_cert, "locality", None
261 ):
262 new_cert.locality = module.params["locality"]
263 else:
264 new_cert.locality = getattr(current_cert, "locality", None)
265 if module.params["province"] and module.params["province"] != getattr(
266 current_cert, "state", None
267 ):
268 new_cert.state = module.params["province"]
269 else:
270 new_cert.state = getattr(current_cert, "state", None)
271 if module.params["organization"] and module.params["organization"] != getattr(
272 current_cert, "organization", None
273 ):
274 new_cert.organization = module.params["organization"]
275 else:
276 new_cert.organization = getattr(current_cert, "organization", None)
277 if module.params["org_unit"] and module.params["org_unit"] != getattr(
278 current_cert, "organizational_unit", None
279 ):
280 new_cert.organizational_unit = module.params["org_unit"]
281 else:
282 new_cert.organizational_unit = getattr(
283 current_cert, "organizational_unit", None
284 )
285 if module.params["key_algorithm"] and module.params["key_algorithm"] != getattr(
286 current_cert, "key_algorithm", None
287 ):
288 new_cert.key_algorithm = module.params["key_algorithm"]
289 else:
290 new_cert.key_algorithm = getattr(current_cert, "key_algorithm", None)
291 if new_cert != current_cert:
292 changed = True
293 certificate = CertificatePost(
294 certificate=new_cert.certificate,
295 certificate_type="array",
296 common_name=new_cert.common_name,
297 country=getattr(new_cert, "country", None),
298 email=getattr(new_cert, "email", None),
299 key_size=getattr(new_cert, "key_size", None),
300 locality=getattr(new_cert, "locality", None),
301 organization=getattr(new_cert, "organization", None),
302 organizational_unit=getattr(new_cert, "organizational_unit", None),
303 key_algorithm=getattr(new_cert, "key_algorithm", None),
304 state=getattr(new_cert, "state", None),
305 days=module.params["days"],
306 )
307 if not module.check_mode:
308 res = blade.patch_certificates(
309 names=[module.params["name"]],
310 certificate=certificate,
311 generate_new_key=module.params["generate"],
312 )
313 if res.status_code != 200:
314 module.fail_json(
315 msg="Updating existing SSL certificate {0} failed. Error: {1}".format(
316 module.params["name"], res.errors[0].message
317 )
318 )
319 else:
320 changed = True
321 certificate = CertificatePatch(
322 certificate=module.params["certificate"],
323 intermeadiate_certificate=module.params["intermeadiate_cert"],
324 private_key=module.params["key"],
325 passphrase=module.params["passphrase"],
326 )
327 res = blade.patch_certificates(
328 names=[module.params["name"]], certificate=certificate
329 )
330 if res.status_code != 200:
331 module.fail_json(
332 msg="Updating existing SSL certificate {0} failed. Error: {1}".format(
333 module.params["name"], res.errors[0].message
334 )
335 )
336 module.exit_json(changed=changed)
337
338
339 def create_cert(module, blade):
340 changed = True
341 api_versions = list(blade.get_versions().items)
342 if CERT_TYPE_VERSION in api_versions:
343 certificate = CertificatePost(
344 certificate=module.params["certificate"],
345 certificate_type="array",
346 common_name=module.params["common_name"],
347 country=module.params["country"],
348 email=module.params["email"],
349 key_size=module.params["key_size"],
350 locality=module.params["locality"],
351 organization=module.params["organization"],
352 organizational_unit=module.params["org_unit"],
353 state=module.params["province"],
354 status="self-signed",
355 days=module.params["days"],
356 )
357 else:
358 certificate = CertificatePost(
359 certificate=module.params["certificate"],
360 certificate_type="array",
361 common_name=module.params["common_name"],
362 country=module.params["country"],
363 email=module.params["email"],
364 key_size=module.params["key_size"],
365 locality=module.params["locality"],
366 organization=module.params["organization"],
367 organizational_unit=module.params["org_unit"],
368 state=module.params["province"],
369 status="self-signed",
370 days=module.params["days"],
371 )
372 if not module.check_mode:
373 res = blade.post_certificates(
374 names=[module.params["name"]], certificate=certificate
375 )
376 if res.status_code != 200:
377 module.fail_json(
378 msg="Creating SSL certificate {0} failed. Error: {1}".format(
379 module.params["name"], res.errors[0].message
380 )
381 )
382
383 module.exit_json(changed=changed)
384
385
386 def delete_cert(module, blade):
387 changed = True
388 if module.params["name"] == "management":
389 module.fail_json(msg="management SSL cannot be deleted")
390 if not module.check_mode:
391 res = blade.delete_certificates(names=[module.params["name"]])
392 if res.status_code != 200:
393 module.fail_json(
394 msg="Failed to delete {0} SSL certifcate. Error: {1}".format(
395 module.params["name"], res.errors[0].message
396 )
397 )
398 module.exit_json(changed=changed)
399
400
401 def import_cert(module, blade):
402 """Import a CA provided SSL certificate"""
403 changed = True
404 if not module.check_mode:
405 if CERT_TYPE_VERSION in list(blade.get_versions().items):
406 certificate = CertificatePost(
407 certificate_type="external",
408 certificate=module.params["certificate"],
409 status="imported",
410 )
411 else:
412 certificate = CertificatePost(
413 certificate=module.params["certificate"],
414 intermediate_certificate=module.params["intermediate_cert"],
415 key_size=module.params["key_size"],
416 passphrase=module.params["passphrase"],
417 status="imported",
418 )
419 res = blade.post_certificates(
420 names=[module.params["name"]], certificate=certificate
421 )
422 if res.status_code != 200:
423 module.fail_json(
424 msg="Importing Certificate failed. Error: {0}".format(res.errors[0].message)
425 )
426 module.exit_json(changed=changed)
427
428
429 def export_cert(module, blade):
430 """Export current SSL certificate"""
431 changed = True
432 if not module.check_mode:
433 ssl = blade.get_certificates(names=[module.params["name"]])
434 if ssl.status_code != 200:
435 module.fail_json(
436 msg="Exporting Certificate failed. Error: {0}".format(
437 ssl.errors[0].message
438 )
439 )
440 with open(module.params["export_file"], "w", encoding="utf-8") as ssl_file:
441 ssl_file.write(list(ssl.items)[0].certificate)
442 module.exit_json(changed=changed)
443
444
445 def create_csr(module, blade):
446 """Construct a Certificate Signing Request
447
448 Output the result to a specified file
449 """
450 changed = True
451 current_attr = Certificate()
452 res = blade.get_certificates(names=[module.params["name"]])
453 if res.status_code == 200:
454 current_attr = list(res.items)[0]
455 if module.params["common_name"] and module.params["common_name"] != getattr(
456 current_attr, "common_name", None
457 ):
458 current_attr.common_name = module.params["common_name"]
459 if module.params["country"] and module.params["country"] != getattr(
460 current_attr, "country", None
461 ):
462 current_attr.country = module.params["country"]
463 if module.params["email"] and module.params["email"] != getattr(
464 current_attr, "email", None
465 ):
466 current_attr.email = module.params["email"]
467 if module.params["locality"] and module.params["locality"] != getattr(
468 current_attr, "locality", None
469 ):
470 current_attr.locality = module.params["locality"]
471 if module.params["province"] and module.params["province"] != getattr(
472 current_attr, "state", None
473 ):
474 current_attr.state = module.params["province"]
475 if module.params["organization"] and module.params["organization"] != getattr(
476 current_attr, "organization", None
477 ):
478 current_attr.organization = module.params["organization"]
479 if module.params["org_unit"] and module.params["org_unit"] != getattr(
480 current_attr, "organizational_unit", None
481 ):
482 current_attr.organizational_unit = module.params["org_unit"]
483 if not module.check_mode:
484 certificate = CertificateSigningRequestPost(
485 certificate=Reference(name=module.params["name"]),
486 common_name=getattr(current_attr, "common_name", None),
487 country=getattr(current_attr, "country", None),
488 email=getattr(current_attr, "email", None),
489 locality=getattr(current_attr, "locality", None),
490 state=getattr(current_attr, "state", None),
491 organization=getattr(current_attr, "organization", None),
492 organizational_unit=getattr(current_attr, "organizational_unit", None),
493 )
494 csr = list(
495 blade.post_certificates_certificate_signing_requests(
496 certificate=certificate
497 ).items
498 )[0].certificate_signing_request
499 with open(module.params["export_file"], "w", encoding="utf-8") as csr_file:
500 csr_file.writelines(list(csr))
501 module.exit_json(changed=changed)
502
503
504 def main():
505 argument_spec = purefb_argument_spec()
506 argument_spec.update(
507 dict(
508 state=dict(
509 type="str",
510 default="present",
511 choices=["absent", "present", "import", "export", "sign"],
512 ),
513 generate=dict(type="bool", default=False),
514 name=dict(type="str", default="management"),
515 country=dict(type="str"),
516 province=dict(type="str"),
517 locality=dict(type="str"),
518 organization=dict(type="str"),
519 org_unit=dict(type="str"),
520 common_name=dict(type="str"),
521 email=dict(type="str"),
522 key_size=dict(type="int", default=2048, choices=[1024, 2048, 4096]),
523 certificate=dict(type="str", no_log=True, aliases=["contents"]),
524 intermediate_cert=dict(
525 type="str", no_log=True, aliases=["intermeadiate_cert"]
526 ),
527 key=dict(type="str", no_log=True, aliases=["private_key"]),
528 export_file=dict(type="str"),
529 passphrase=dict(type="str", no_log=True),
530 days=dict(type="int", default=3650),
531 key_algorithm=dict(type="str", choices=["rsa", "ec", "ed448", "ed25519"]),
532 )
533 )
534
535 mutually_exclusive = [["certificate", "key_size"]]
536 required_if = [
537 ["state", "import", ["certificate"]],
538 ["state", "export", ["export_file"]],
539 ["state", "sign", ["export_file"]],
540 ]
541
542 module = AnsibleModule(
543 argument_spec,
544 mutually_exclusive=mutually_exclusive,
545 required_if=required_if,
546 supports_check_mode=True,
547 )
548
549 if not HAS_PURESTORAGE:
550 module.fail_json(msg="py-pure-client sdk is required for this module")
551
552 if not HAS_PYCOUNTRY:
553 module.fail_json(msg="pycountry sdk is required for this module")
554
555 email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
556 blade = get_system(module)
557 api_versions = list(blade.get_versions().items)
558
559 if module.params["email"]:
560 if not re.search(email_pattern, module.params["email"]):
561 module.fail_json(
562 msg="Email {0} is not valid".format(module.params["email"])
563 )
564 if module.params["country"]:
565 if len(module.params["country"]) != 2:
566 module.fail_json(msg="Country must be a two-letter country (ISO) code")
567 if not pycountry.countries.get(alpha_2=module.params["country"].upper()):
568 module.fail_json(
569 msg="Country code {0} is not an assigned ISO 3166-1 code".format(
570 module.params["country"].upper()
571 )
572 )
573 state = module.params["state"]
574 if state in ["present"]:
575 if not module.params["common_name"]:
576 module.params["common_name"] = list(blade.get_arrays().items)[0].name
577 module.params["common_name"] = module.params["common_name"][:64]
578
579 exists = bool(
580 blade.get_certificates(names=[module.params["name"]]).status_code == 200
581 )
582
583 if not exists and state == "present":
584 create_cert(module, blade)
585 elif exists and state == "present":
586 update_cert(module, blade)
587 elif state == "sign":
588 if CSR_API_VERSION not in api_versions:
589 module.fail_json(msg="Purity//FB 4.6.3+ is required for CSRs")
590 create_csr(module, blade)
591 elif not exists and state == "import":
592 import_cert(module, blade)
593 elif exists and state == "import":
594 module.fail_json(msg="External Certificates cannot be reimported")
595 elif state == "export":
596 export_cert(module, blade)
597 elif exists and state == "absent":
598 delete_cert(module, blade)
599
600 module.exit_json(changed=False)
601
602
603 if __name__ == "__main__":
604 main()