Makefile: improve encryption and decryption of secrets

This commit is contained in:
ryan-distrust.co 2023-05-12 00:32:49 -04:00
parent 430622c716
commit 2906f910c0
Signed by untrusted user who does not match committer: ryan
GPG Key ID: 8E401478A3FBEF72
1 changed files with 30 additions and 4 deletions

View File

@ -92,6 +92,10 @@ apply: \
$(OUT_DIR)/terraform \
$(OUT_DIR)/sops \
infra/main/.terraform
$(call maybe_decrypt_secret,secrets/$(ENVIRONMENT).talosconfig,infra/main/talos/talosconfig)
$(call maybe_decrypt_secret,secrets/$(ENVIRONMENT).kubeconfig,infra/main/talos/kubeconfig)
$(call maybe_decrypt_secret,secrets/$(ENVIRONMENT).controlplane.yaml,infra/main/talos/controlplane.yaml)
$(call maybe_decrypt_secret,secrets/$(ENVIRONMENT).worker.yaml,infra/main/talos/worker.yaml)
$(SOPS) exec-env secrets/$(ENVIRONMENT).enc.env '\
env -C infra/main \
$(TERRAFORM) apply \
@ -99,10 +103,10 @@ apply: \
-var namespace=$(ENVIRONMENT) \
-var region=$(REGION) \
'
$(SOPS) --encrypt infra/main/talos/talosconfig > secrets/$(ENVIRONMENT).talosconfig
$(SOPS) --encrypt infra/main/talos/kubeconfig > secrets/$(ENVIRONMENT).kubeconfig
$(SOPS) --encrypt infra/main/talos/controlplane.yaml > secrets/$(ENVIRONMENT).controlplane.yaml
$(SOPS) --encrypt infra/main/talos/worker.yaml > secrets/$(ENVIRONMENT).worker.yaml
$(call maybe_encrypt_secret,infra/main/talos/talosconfig,secrets/$(ENVIRONMENT).talosconfig)
$(call maybe_encrypt_secret,infra/main/talos/kubeconfig,secrets/$(ENVIRONMENT).kubeconfig)
$(call maybe_encrypt_secret,infra/main/talos/controlplane.yaml,secrets/$(ENVIRONMENT).controlplane.yaml)
$(call maybe_encrypt_secret,infra/main/talos/worker.yaml,secrets/$(ENVIRONMENT).worker.yaml)
$(CACHE_DIR)/secrets:
mkdir -p $@
@ -155,3 +159,25 @@ $(OUT_DIR)/talosctl: $(FETCH_DIR)/talosctl
-ldflags='-w -extldflags=-static' \
-o /home/build/$@ $(TALOSCTL_PKG) \
")
# Note: Decryption MUST reset the mod time to avoid encryption/decryption loops
# Encrypt if:
# - Both files exist, local is newer than remote
# - Only local exists
define maybe_encrypt_secret
test \( -f $(1) -a -f $(2) -a $(1) -nt $(2) \) -o \
\( -f $(1) -a ! -f $(2) \) && \
$(SOPS) --encrypt $(1) > $(2) || true
endef
# Only decrypt when local files don't exist
# Unfortunately, this means we can't decrypt if the secrets update. We can't
# do that because otherwise it creates a loop. The secrets update, therefore we
# decrypt secrets, but because the modtime of the decrypted secrets is newer
# than the encrypted secrets, we want to reencrypt encrypted secrets.
define maybe_decrypt_secret
test -f $(1) -a ! -f $(2) && \
$(SOPS) --decrypt $(1) > $(2) && \
touch -d 1970-01-01 $(2) || \
true
endef