fix(vault): properly use VAULT_UNSEAL_KEY from env

This commit is contained in:
Ruslan Bakiev
2026-03-10 20:49:57 +07:00
parent 8eec280b9d
commit bb2fab8b40

View File

@@ -6,6 +6,10 @@ vault server -config=/vault/config/vault.hcl &
VAULT_PID=$!
export VAULT_ADDR="http://127.0.0.1:8200"
# Save env unseal key before anything overwrites it
SAVED_UNSEAL_KEY="${VAULT_UNSEAL_KEY}"
echo "Waiting for Vault to start..."
until vault status -format=json 2>/dev/null | grep -q '"initialized"\|"sealed"'; do
sleep 1
@@ -17,29 +21,30 @@ INITIALIZED=$(vault status -format=json 2>/dev/null | grep '"initialized"' | gre
if [ "$INITIALIZED" != "1" ]; then
echo "Vault not initialized, running operator init..."
vault operator init -key-shares=1 -key-threshold=1 -format=json > /vault/data/init.json
VAULT_UNSEAL_KEY=$(cat /vault/data/init.json | sed -n 's/.*"unseal_keys_b64":\["\([^"]*\)".*/\1/p')
export VAULT_UNSEAL_KEY
echo "Vault initialized. Unseal key saved to /vault/data/init.json"
echo "Vault initialized. Keys saved to /vault/data/init.json"
fi
# If no env key, try to read from saved init.json
if [ -z "$VAULT_UNSEAL_KEY" ] && [ -f /vault/data/init.json ]; then
VAULT_UNSEAL_KEY=$(cat /vault/data/init.json | sed -n 's/.*"unseal_keys_b64":\["\([^"]*\)".*/\1/p')
# Determine unseal key: env > init.json
if [ -n "$SAVED_UNSEAL_KEY" ]; then
UNSEAL_KEY="$SAVED_UNSEAL_KEY"
echo "Using VAULT_UNSEAL_KEY from environment."
elif [ -f /vault/data/init.json ]; then
UNSEAL_KEY=$(grep -o '"unseal_keys_b64":\["[^"]*"' /vault/data/init.json | grep -o '\["[^"]*"' | tr -d '["')
echo "Using unseal key from /vault/data/init.json."
fi
# Auto-unseal
if [ -n "$VAULT_UNSEAL_KEY" ]; then
if [ -n "$UNSEAL_KEY" ]; then
SEALED=$(vault status -format=json 2>/dev/null | grep '"sealed"' | grep -c 'true' || true)
if [ "$SEALED" = "1" ]; then
echo "Vault is sealed, auto-unsealing..."
vault operator unseal "$VAULT_UNSEAL_KEY"
echo "Vault is sealed, unsealing..."
vault operator unseal "$UNSEAL_KEY"
echo "Vault unsealed."
else
echo "Vault is already unsealed."
fi
else
echo "VAULT_UNSEAL_KEY not set and no init.json found, skipping auto-unseal."
echo "No unseal key available, skipping auto-unseal."
fi
# Wait for Vault process
wait $VAULT_PID