read grafana's datasource key from the store into /run, seeding an empty store from the old file
This commit is contained in:
parent
fcc9c8d0ba
commit
204abb1d0e
1 changed files with 236 additions and 69 deletions
58
nix/host-modules/lib/grafana-secret-key.nix
Normal file
58
nix/host-modules/lib/grafana-secret-key.nix
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
# The store's value for Grafana's datasource-encryption key, seeded once from
|
||||
# the file an earlier release generated in the container.
|
||||
#
|
||||
# Grafana cannot read datasource secrets encrypted with another key, so a store
|
||||
# with no value takes the file's, and a new key is minted only when there is no
|
||||
# file either. The store is written with `-cas=0`, so a value it holds is never
|
||||
# replaced and a lost race reads the winner's back. The file stays, unused.
|
||||
#
|
||||
# `grafana_secret_key` sets `GRAFANA_KEY` and returns 0, or returns 1 when the
|
||||
# store does not log in, answer or take a value; nothing is minted then.
|
||||
#
|
||||
# Pure function — NOT a NixOS module. Call it from a unit's `script`, with
|
||||
# `bao` and `coreutils` on its `path` and the `BAO_*` client environment set:
|
||||
#
|
||||
# script = ''
|
||||
# ${import ./lib/grafana-secret-key.nix { }}
|
||||
# grafana_secret_key secret/swarm/services/foo/secret-key /path/to/seed openssl rand -hex 32 || exit 1
|
||||
# '';
|
||||
{ }:
|
||||
''
|
||||
# <store leaf> <seed file> <mint command…>
|
||||
grafana_secret_key() {
|
||||
local leaf="$1" seed="$2" candidate err
|
||||
shift 2
|
||||
GRAFANA_KEY=""
|
||||
err="$(mktemp)"
|
||||
|
||||
if ! BAO_TOKEN="$(bao login -method=cert -token-only 2>"$err")"; then
|
||||
cat "$err" >&2
|
||||
rm -f "$err"
|
||||
echo "could not log in to the swarm secret store." >&2
|
||||
return 1
|
||||
fi
|
||||
export BAO_TOKEN
|
||||
|
||||
if ! GRAFANA_KEY="$(bao kv get -field=value "$leaf" 2>"$err")" || [ -z "$GRAFANA_KEY" ]; then
|
||||
if [ -s "$seed" ]; then
|
||||
candidate="$(tr -d '\n' < "$seed")"
|
||||
echo "storing the key at $seed in $leaf."
|
||||
else
|
||||
candidate="$("$@")"
|
||||
echo "no earlier key; minting one in $leaf."
|
||||
fi
|
||||
if ! printf '%s' "$candidate" | bao kv put -cas=0 "$leaf" value=- >/dev/null 2>"$err"; then
|
||||
cat "$err" >&2
|
||||
echo "could not create $leaf; reading it back in case another run created it." >&2
|
||||
fi
|
||||
if ! GRAFANA_KEY="$(bao kv get -field=value "$leaf" 2>"$err")" || [ -z "$GRAFANA_KEY" ]; then
|
||||
cat "$err" >&2
|
||||
rm -f "$err"
|
||||
echo "the store did not return $leaf." >&2
|
||||
GRAFANA_KEY=""
|
||||
return 1
|
||||
fi
|
||||
fi
|
||||
rm -f "$err"
|
||||
}
|
||||
''
|
||||
Loading…
Reference in a new issue