na4ma4 / traefik-acme

Extract certificates from acme.json created by traefik.
Apache License 2.0
18 stars 2 forks source link

Feature: script to write cert's to kubernetes #32

Open jochumdev opened 1 year ago

jochumdev commented 1 year ago

I've written a simple script that export's certifcates from acme.json to kubernetes certificates.

#!/usr/bin/env bash

set -e # abort on errors
set -u # abort on unset variables
set -f # disable globbing

STORE="${ACME_STORE}"
RESOLVER="${ACME_RESOLVER}"

IFS=";"
DOMAINS=(${ACME_DOMAINS}) # Make a BASH array from ACME_DOMAINS split by ";"

if [[ ! -f "${STORE}" ]]; then
    echo "acme.json file '${STORE}' not found"
    exit 1
fi

# Do all operations in /tmp
pushd /tmp

for d in ${DOMAINS[@]}; do
    IFS=":"
    dnn=($d) # Split ${d} by ":"
    domain=${dnn[0]};

    second_part=${dnn[1]}
    IFS="/"
    nn=($second_part) # Split the second part of DOMAIN by "/"
    IFS=" "
    namespace=${nn[0]}
    name=${nn[1]}

    echo "Domain '${domain}' to '${namespace}/${name}'"

    # Do the actual export
    traefik-acme "${domain}" -r "${RESOLVER}" -a "${STORE}"

    if [[ ! -f "cert.pem" ]] || [[ ! -f "key.pem" ]]; then
        echo "Failed to export cert.pem or key.pem"
        rm -f cert.pem
        rm -f key.pem
        continue
    fi

    # Move so kube has the right names for them.
    mv cert.pem tls.crt
    mv key.pem tls.key

    # Delete and create the tls secret.
    kubectl delete secret "${name}" --namespace "${namespace}" --ignore-not-found
    kubectl create secret generic "${name}" \
        --namespace "${namespace}" \
        --from-file="tls.crt" \
        --from-file="tls.key"

    rm -f tls.crt
    rm -f tls.key
done

# Go back to the original directory.
popd

I use it with:

ACME_STORE="/home/user/somewhere/acme.json" ACME_RESOLVER="letsencrypt-prod" ACME_DOMAINS="mail.jochum.dev:mail/tls-dev-jochum-mail;webmail.jochum.dev:mail/tls-webmail-jochum-dev" ./bin/acmejson-to-secret.sh 

ACME_DOMAINS is in the format: $domain:$namespace/$name;$domain:$namespace/$name;$domain:$namespace/$name

Next step is to write a sidecar container for Traefik or a Job to run this.

na4ma4 commented 1 year ago

You could use a kubernetes cronjob to do it and maybe add a compare so it doesn't replace the secret unless it has actually changed.

Not sure what I can do in the traefik-acme tool to make this easier, we could probably bundle it with the binary in the docker container and make a sub container that is based on a distro (deb or alpine) ?

jochumdev commented 1 month ago

Finaly had some time to work on that.

Result is here: https://github.com/jochumdev/acmejson-to-secret

Feel free to copy&paste whatever you want: I have no compare yet.

jochumdev commented 1 month ago

I added cert compare.