Skip to content

Instantly share code, notes, and snippets.

@dleske
Created October 23, 2022 21:10
Show Gist options
  • Select an option

  • Save dleske/2600363ae7575fdea3b1222671bc9ac8 to your computer and use it in GitHub Desktop.

Select an option

Save dleske/2600363ae7575fdea3b1222671bc9ac8 to your computer and use it in GitHub Desktop.

Revisions

  1. dleske created this gist Oct 23, 2022.
    48 changes: 48 additions & 0 deletions grokcerts.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    #!/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)