#!/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" # 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 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 echo "Vault initialized. Keys saved to /vault/data/init.json" fi # 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 "$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, unsealing..." vault operator unseal "$UNSEAL_KEY" echo "Vault unsealed." else echo "Vault is already unsealed." fi else echo "No unseal key available, skipping auto-unseal." fi wait $VAULT_PID