Skip to content

Instantly share code, notes, and snippets.

@alevikpes
Forked from apparentlymart/extract-certs.py
Last active August 16, 2017 12:01
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 alevikpes/546a7be292b51e08a8cf341d18475d64 to your computer and use it in GitHub Desktop.
Save alevikpes/546a7be292b51e08a8cf341d18475d64 to your computer and use it in GitHub Desktop.
Python script to extract generated TLS certificates and keys from a Terraform state
#!/usr/bin/python3
import errno
import json
import os
def main():
tf_state_path = os.path.join(os.path.dirname(__file__), 'root.tfstate')
with open(tf_state_path, 'r') as f:
tf_state = json.load(f)
cert_path = os.path.join(os.path.dirname(__file__), "certs")
try:
os.makedirs(cert_path)
except OSError as exc:
if exc.errno == errno.EEXIST:
pass
else:
raise
root_resources = [mod["resources"] for mod in tf_state["modules"]
if mod["path"] == ["root"]][0]
# collect all certificates
root_cert = root_resources["tls_self_signed_cert.root"]
root_cert_pem = root_cert["primary"]["attributes"]["cert_pem"]
certs = {'ca': root_cert_pem}
issued_certs = {i: r for i, r in root_resources.items()
if r["type"] == "tls_locally_signed_cert"}
for resource_id, cert in issued_certs.items():
name = resource_id[len("tls_locally_signed_cert."):]
attrs = cert["primary"]["attributes"]
certs[name] = attrs['cert_pem']
# save all certs into corresponding files
for cert in certs:
filename = os.path.join(cert_path, cert + ".crt")
write_to_file(filename, certs[cert])
# If we also generated our own key for this certificate,
# (as opposed to just being given a CSR from elsewhere)
# then we'll write that out too, so we have all the
# information needed to configure a server.
if "tls_private_key." + cert in root_resources:
key_resource = root_resources["tls_private_key." + cert]
key_pem = key_resource["primary"]["attributes"]["private_key_pem"]
cert_file = os.path.join(cert_path, cert + ".key")
write_to_file(cert_file, key_pem)
# create a chained cert file
filename = os.path.join(cert_path, "fullchain.crt")
write_to_file(filename, '\n'.join(certs))
def write_to_file(filename, certname):
with open(filename, 'w') as f:
f.write(certname)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment