Debian Codegraph @

ansible_collections/purestorage/flasharray/plugins/modules/purefa_certs.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2021, 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: purefa_certs
20 version_added: '1.8.0'
21 short_description: Manage FlashArray SSL Certificates
22 description:
23 - Create, delete, import and export FlashArray 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 existing 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 array
69 - For example, the common name for https://purearray.example.com is
70 purearray.example.com, or *.example.com for a wildcard certificate
71 - This can also be the management IP address of the array or the
72 shortname of the current array.
73 - Maximum of 64 characters
74 - If not provided this will default to the shortname of the array
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 type: str
99 description:
100 - Required for I(import)
101 - A valid signed certificate in PEM format (Base64 encoded)
102 - Includes the "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" lines
103 intermeadiate_cert:
104 type: str
105 description:
106 - Intermeadiate certificate provided by the CA
107 key:
108 type: str
109 description:
110 - If the Certificate Signed Request (CSR) was not constructed on the array
111 or the private key has changed since construction the CSR, provide
112 a new private key here
113 passphrase:
114 type: str
115 description:
116 - Passphrase if the private key is encrypted
117 export_file:
118 type: str
119 description:
120 - Name of file to contain Certificate Signing Request when `status sign`
121 - Name of file to export the current SSL Certificate when `status export`
122 - File will be overwritten if it already exists
123 extends_documentation_fragment:
124 - purestorage.flasharray.purestorage.fa
125 """
126
127 EXAMPLES = r"""
128 - name: Create SSL certificate foo
129 purestorage.flasharray.purefa_certs:
130 name: foo
131 key_size: 4096
132 country: US
133 province: FL
134 locality: Miami
135 organization: "Acme Inc"
136 org_unit: "DevOps"
137 fa_url: 10.10.10.2
138 api_token: e31060a7-21fc-e277-6240-25983c6c4592
139
140 - name: Delete SSL certificate foo
141 purestorage.flasharray.purefa_certs:
142 name: foo
143 state: absent
144 fa_url: 10.10.10.2
145 api_token: e31060a7-21fc-e277-6240-25983c6c4592
146
147 - name: Request CSR
148 purestorage.flasharray.purefa_certs:
149 state: sign
150 fa_url: 10.10.10.2
151 api_token: e31060a7-21fc-e277-6240-25983c6c4592
152
153 - name: Request CSR with updated fields
154 purestorage.flasharray.purefa_certs:
155 state: sign
156 org_unit: Development
157 fa_url: 10.10.10.2
158 api_token: e31060a7-21fc-e277-6240-25983c6c4592
159
160 - name: Regenerate key for SSL foo
161 purestorage.flasharray.purefa_certs:
162 generate: true
163 name: foo
164 fa_url: 10.10.10.2
165 api_token: e31060a7-21fc-e277-6240-25983c6c4592
166
167 - name: Import SSL Cert foo and Private Key
168 purestorage.flasharray.purefa_certs:
169 state: import
170 name: foo
171 certificate: "{{lookup('file', 'example.crt') }}"
172 key: "{{lookup('file', 'example.key') }}"
173 passphrase: password
174 fa_url: 10.10.10.2
175 api_token: e31060a7-21fc-e277-6240-25983c6c4592
176 """
177
178 RETURN = r"""
179 """
180
181 HAS_PURESTORAGE = True
182 try:
183 from pypureclient import flasharray
184 except ImportError:
185 HAS_PURESTORAGE = False
186
187 HAS_PYCOUNTRY = True
188 try:
189 import pycountry
190 except ImportError:
191 HAS_PYCOUNTRY = False
192
193 import re
194 from ansible.module_utils.basic import AnsibleModule
195 from ansible_collections.purestorage.flasharray.plugins.module_utils.purefa import (
196 get_array,
197 purefa_argument_spec,
198 )
199 from ansible_collections.purestorage.flasharray.plugins.module_utils.version import (
200 LooseVersion,
201 )
202
203 MIN_REQUIRED_API_VERSION = "2.4"
204
205
206 def update_cert(module, array):
207 """Update existing SSL Certificate"""
208 changed = False
209 current_cert = list(array.get_certificates(names=[module.params["name"]]).items)[0]
210 new_cert = current_cert
211 if module.params["common_name"] and module.params["common_name"] != getattr(
212 current_cert, "common_name", None
213 ):
214 new_cert.common_name = module.params["common_name"]
215 else:
216 new_cert.common_name = getattr(current_cert, "common_name", None)
217 if module.params["country"] and module.params["country"] != getattr(
218 current_cert, "country", None
219 ):
220 new_cert.country = module.params["country"]
221 else:
222 new_cert.country = getattr(current_cert, "country")
223 if module.params["email"] and module.params["email"] != getattr(
224 current_cert, "email", None
225 ):
226 new_cert.email = module.params["email"]
227 else:
228 new_cert.email = getattr(current_cert, "email", None)
229 if module.params["key_size"] and module.params["key_size"] != getattr(
230 current_cert, "key_size", None
231 ):
232 new_cert.key_size = module.params["key_size"]
233 else:
234 new_cert.key_size = getattr(current_cert, "key_size", None)
235 if module.params["locality"] and module.params["locality"] != getattr(
236 current_cert, "locality", None
237 ):
238 new_cert.locality = module.params["locality"]
239 else:
240 new_cert.locality = getattr(current_cert, "locality", None)
241 if module.params["province"] and module.params["province"] != getattr(
242 current_cert, "state", None
243 ):
244 new_cert.state = module.params["province"]
245 else:
246 new_cert.state = getattr(current_cert, "state", None)
247 if module.params["organization"] and module.params["organization"] != getattr(
248 current_cert, "organization", None
249 ):
250 new_cert.organization = module.params["organization"]
251 else:
252 new_cert.organization = getattr(current_cert, "organization", None)
253 if module.params["org_unit"] and module.params["org_unit"] != getattr(
254 current_cert, "organizational_unit", None
255 ):
256 new_cert.organizational_unit = module.params["org_unit"]
257 else:
258 new_cert.organizational_unit = getattr(
259 current_cert, "organizational_unit", None
260 )
261 if new_cert != current_cert:
262 changed = True
263 certificate = flasharray.CertificatePost(
264 common_name=new_cert.common_name,
265 country=getattr(new_cert, "country", None),
266 email=getattr(new_cert, "email", None),
267 key_size=getattr(new_cert, "key_size", None),
268 locality=getattr(new_cert, "locality", None),
269 organization=getattr(new_cert, "organization", None),
270 organizational_unit=getattr(new_cert, "organizational_unit", None),
271 state=getattr(new_cert, "state", None),
272 )
273 if not module.check_mode:
274 res = array.patch_certificates(
275 names=[module.params["name"]],
276 certificate=certificate,
277 generate_new_key=module.params["generate"],
278 )
279 if res.status_code != 200:
280 module.fail_json(
281 msg="Updating existing SSL certificate {0} failed. Error: {1}".format(
282 module.params["name"], res.errors[0].message
283 )
284 )
285
286 module.exit_json(changed=changed)
287
288
289 def create_cert(module, array):
290 changed = True
291 certificate = flasharray.CertificatePost(
292 common_name=module.params["common_name"],
293 country=module.params["country"],
294 email=module.params["email"],
295 key_size=module.params["key_size"],
296 locality=module.params["locality"],
297 organization=module.params["organization"],
298 organizational_unit=module.params["org_unit"],
299 state=module.params["province"],
300 status="self-signed",
301 days=module.params["days"],
302 )
303 if not module.check_mode:
304 res = array.post_certificates(
305 names=[module.params["name"]], certificate=certificate
306 )
307 if res.status_code != 200:
308 module.fail_json(
309 msg="Creating SSL certificate {0} failed. Error: {1}".format(
310 module.params["name"], res.errors[0].message
311 )
312 )
313
314 module.exit_json(changed=changed)
315
316
317 def delete_cert(module, array):
318 changed = True
319 if module.params["name"] == "management":
320 module.fail_json(msg="management SSL cannot be deleted")
321 if not module.check_mode:
322 res = array.delete_certificates(names=[module.params["name"]])
323 if res.status_code != 200:
324 module.fail_json(
325 msg="Failed to delete {0} SSL certificate. Error: {1}".format(
326 module.params["name"], res.errors[0].message
327 )
328 )
329 module.exit_json(changed=changed)
330
331
332 def import_cert(module, array, reimport=False):
333 """Import a CA provided SSL certificate"""
334 changed = True
335 certificate = flasharray.CertificatePost(
336 certificate=module.params["certificate"],
337 intermediate_certificate=module.params["intermeadiate_cert"],
338 key=module.params["key"],
339 passphrase=module.params["passphrase"],
340 status="imported",
341 )
342 if not module.check_mode:
343 if reimport:
344 res = array.patch_certificates(
345 names=[module.params["name"]], certificate=certificate
346 )
347 else:
348 res = array.post_certificates(
349 names=[module.params["name"]], certificate=certificate
350 )
351 if res.status_code != 200:
352 module.fail_json(
353 msg="Importing Certificate failed. Error: {0}".format(
354 res.errors[0].message
355 )
356 )
357 module.exit_json(changed=changed)
358
359
360 def export_cert(module, array):
361 """Export current SSL certificate"""
362 changed = True
363 if not module.check_mode:
364 ssl = array.get_certificates(names=[module.params["name"]])
365 if ssl.status_code != 200:
366 module.fail_json(
367 msg="Exporting Certificate failed. Error: {0}".format(
368 ssl.errors[0].message
369 )
370 )
371 with open(module.params["export_file"], "w", encoding="utf-8") as ssl_file:
372 ssl_file.write(list(ssl.items)[0].certificate)
373 module.exit_json(changed=changed)
374
375
376 def create_csr(module, array):
377 """Construct a Certificate Signing Request
378
379 Output the result to a specified file
380 """
381 changed = True
382 current_attr = list(array.get_certificates(names=[module.params["name"]]).items)[0]
383 try:
384 if module.params["common_name"] and module.params["common_name"] != getattr(
385 current_attr, "common_name", None
386 ):
387 current_attr.common_name = module.params["common_name"]
388 except AttributeError:
389 pass
390 try:
391 if module.params["country"] and module.params["country"] != getattr(
392 current_attr, "country", None
393 ):
394 current_attr.country = module.params["country"]
395 except AttributeError:
396 pass
397 try:
398 if module.params["email"] and module.params["email"] != getattr(
399 current_attr, "email", None
400 ):
401 current_attr.email = module.params["email"]
402 except AttributeError:
403 pass
404 try:
405 if module.params["locality"] and module.params["locality"] != getattr(
406 current_attr, "locality", None
407 ):
408 current_attr.locality = module.params["locality"]
409 except AttributeError:
410 pass
411 try:
412 if module.params["province"] and module.params["province"] != getattr(
413 current_attr, "state", None
414 ):
415 current_attr.state = module.params["province"]
416 except AttributeError:
417 pass
418 try:
419 if module.params["organization"] and module.params["organization"] != getattr(
420 current_attr, "organization", None
421 ):
422 current_attr.organization = module.params["organization"]
423 except AttributeError:
424 pass
425 try:
426 if module.params["org_unit"] and module.params["org_unit"] != getattr(
427 current_attr, "organizational_unit", None
428 ):
429 current_attr.organizational_unit = module.params["org_unit"]
430 except AttributeError:
431 pass
432 if not module.check_mode:
433 certificate = flasharray.CertificateSigningRequestPost(
434 certificate={"name": module.params["name"]},
435 common_name=getattr(current_attr, "common_name", None),
436 country=getattr(current_attr, "country", None),
437 email=getattr(current_attr, "email", None),
438 locality=getattr(current_attr, "locality", None),
439 state=getattr(current_attr, "state", None),
440 organization=getattr(current_attr, "organization", None),
441 organizational_unit=getattr(current_attr, "organizational_unit", None),
442 )
443 csr = list(
444 array.post_certificates_certificate_signing_requests(
445 certificate=certificate
446 ).items
447 )[0].certificate_signing_request
448 with open(module.params["export_file"], "w", encoding="utf-8") as csr_file:
449 csr_file.writelines(list(csr))
450 module.exit_json(changed=changed)
451
452
453 def main():
454 argument_spec = purefa_argument_spec()
455 argument_spec.update(
456 dict(
457 state=dict(
458 type="str",
459 default="present",
460 choices=["absent", "present", "import", "export", "sign"],
461 ),
462 generate=dict(type="bool", default=False),
463 name=dict(type="str", default="management"),
464 country=dict(type="str"),
465 province=dict(type="str"),
466 locality=dict(type="str"),
467 organization=dict(type="str"),
468 org_unit=dict(type="str"),
469 common_name=dict(type="str"),
470 email=dict(type="str"),
471 key_size=dict(type="int", default=2048, choices=[1024, 2048, 4096]),
472 certificate=dict(type="str", no_log=True),
473 intermeadiate_cert=dict(type="str", no_log=True),
474 key=dict(type="str", no_log=True),
475 export_file=dict(type="str"),
476 passphrase=dict(type="str", no_log=True),
477 days=dict(type="int", default=3650),
478 )
479 )
480
481 mutually_exclusive = [["certificate", "key_size"]]
482 required_if = [
483 ["state", "import", ["certificate"]],
484 ["state", "export", ["export_file"]],
485 ["state", "sign", ["export_file"]],
486 ]
487
488 module = AnsibleModule(
489 argument_spec,
490 mutually_exclusive=mutually_exclusive,
491 required_if=required_if,
492 supports_check_mode=True,
493 )
494
495 if not HAS_PURESTORAGE:
496 module.fail_json(msg="py-pure-client sdk is required for this module")
497
498 if not HAS_PYCOUNTRY:
499 module.fail_json(msg="pycountry sdk is required for this module")
500
501 email_pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"
502 array = get_array(module)
503 api_version = array.get_rest_version()
504
505 if LooseVersion(MIN_REQUIRED_API_VERSION) > LooseVersion(api_version):
506 module.fail_json(
507 msg="FlashArray REST version not supported. "
508 "Minimum version required: {0}".format(MIN_REQUIRED_API_VERSION)
509 )
510
511 if module.params["email"]:
512 if not re.search(email_pattern, module.params["email"]):
513 module.fail_json(
514 msg="Email {0} is not valid".format(module.params["email"])
515 )
516 if module.params["country"]:
517 if len(module.params["country"]) != 2:
518 module.fail_json(msg="Country must be a two-letter country (ISO) code")
519 if not pycountry.countries.get(alpha_2=module.params["country"].upper()):
520 module.fail_json(
521 msg="Country code {0} is not an assigned ISO 3166-1 code".format(
522 module.params["country"].upper()
523 )
524 )
525 state = module.params["state"]
526 if state in ["present"]:
527 if not module.params["common_name"]:
528 module.params["common_name"] = list(array.get_arrays().items)[0].name
529 module.params["common_name"] = module.params["common_name"][:64]
530
531 exists = bool(
532 array.get_certificates(names=[module.params["name"]]).status_code == 200
533 )
534
535 if not exists and state == "present":
536 create_cert(module, array)
537 elif exists and state == "present":
538 update_cert(module, array)
539 elif state == "sign":
540 create_csr(module, array)
541 elif not exists and state == "import":
542 import_cert(module, array)
543 elif exists and state == "import":
544 import_cert(module, array, reimport=True)
545 elif state == "export":
546 export_cert(module, array)
547 elif exists and state == "absent":
548 delete_cert(module, array)
549
550 module.exit_json(changed=False)
551
552
553 if __name__ == "__main__":
554 main()