46 lines
1.5 KiB
Bash
46 lines
1.5 KiB
Bash
#!/bin/sh
|
|
set -e
|
|
|
|
# Start Vault server in background
|
|
vault server -config=/vault/config/vault.hcl &
|
|
VAULT_PID=$!
|
|
|
|
export VAULT_ADDR="http://127.0.0.1:8200"
|
|
echo "Waiting for Vault to start..."
|
|
until vault status -format=json 2>/dev/null | grep -q '"initialized"\|"sealed"'; do
|
|
sleep 1
|
|
done
|
|
|
|
# Check if initialized
|
|
INITIALIZED=$(vault status -format=json 2>/dev/null | grep '"initialized"' | grep -c 'true' || true)
|
|
|
|
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"
|
|
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')
|
|
fi
|
|
|
|
# Auto-unseal
|
|
if [ -n "$VAULT_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 unsealed."
|
|
else
|
|
echo "Vault is already unsealed."
|
|
fi
|
|
else
|
|
echo "VAULT_UNSEAL_KEY not set and no init.json found, skipping auto-unseal."
|
|
fi
|
|
|
|
# Wait for Vault process
|
|
wait $VAULT_PID
|