Skip to content

Instantly share code, notes, and snippets.

@dleske
Created October 23, 2022 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dleske/2600363ae7575fdea3b1222671bc9ac8 to your computer and use it in GitHub Desktop.
Save dleske/2600363ae7575fdea3b1222671bc9ac8 to your computer and use it in GitHub Desktop.
Python script to parse certificate data from Terraform output
#!/usr/bin/env python3
#
# Reads certificate information from Terraform output and creates certificate
# files ready for use.
#
# If Terraform variable for certificates is defined like:
#
# variable certificates {
# type = map(string)
# default = {}
# }
#
# And the output is defined like:
#
# output "certificates" {
# description = "Certificate details"
# value = {
# for name, domain in var.certificates:
# name => {
# certificate = acme_certificate.certificate[name].certificate_pem
# issuer = acme_certificate.certificate[name].issuer_pem
# key = acme_certificate.certificate[name].private_key_pem
# url = acme_certificate.certificate[name].certificate_url
# }
# }
# sensitive = true
# }
#
# use like: terraform output -json certificates | grokcerts.py
import sys
import json
data_json = "".join(sys.stdin.readlines())
data = json.loads(data_json)
for domain in data.keys():
print(domain)
# this is clumsy AF but it works
issuer = data[domain]['issuer'].split('-----END CERTIFICATE-----')[0] + '-----END CERTIFICATE-----'
with open(f"{domain}.key", "w") as fh:
fh.write(data[domain]['key'])
with open(f"{domain}.crt", "w") as fh:
fh.write(data[domain]['certificate'])
fh.write(issuer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment