Skip to content

Instantly share code, notes, and snippets.

@up1
Forked from winggundamth/vault-init.sh
Created October 17, 2022 06:22
Show Gist options
  • Select an option

  • Save up1/6a893a5de3a2992acf66d0b5a4d79ad9 to your computer and use it in GitHub Desktop.

Select an option

Save up1/6a893a5de3a2992acf66d0b5a4d79ad9 to your computer and use it in GitHub Desktop.

Revisions

  1. @winggundamth winggundamth created this gist Oct 17, 2022.
    57 changes: 57 additions & 0 deletions vault-init.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    #!/bin/sh

    cd /home/vault

    if [[ ! -f jq ]]
    then
    echo "Download jq command..."
    wget https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 -O jq
    chmod +x jq
    fi

    if vault status -format=json | ./jq -e "if ((.initialized) and (.sealed | not)) then true else false end" >/dev/null; then
    echo "Vault initialized and unsealed."
    exit 0
    fi

    while :
    do
    if [[ ! -f mc ]]
    then
    echo "Download mc command..."
    wget https://dl.min.io/client/mc/release/linux-amd64/mc
    chmod +x mc
    fi
    ./mc alias set minio-vault $MINIO_VAULT_URL vault $MINIO_VAULT_SECRET

    if vault status -format=json | ./jq -e "if (.initialized | not) then true else false end" >/dev/null; then
    if [ "$HOSTNAME" = vault-0 ]; then
    echo "Initial Vault..."
    initResult=$(vault operator init -format=json -key-shares=1 -key-threshold=1)
    unsealKey1=$(echo -n $initResult | ./jq -r '.unseal_keys_b64[0]')
    rootToken=$(echo -n $initResult | ./jq -r '.root_token')
    echo -n $unsealKey1 > unsealKey1
    echo -n $rootToken > rootToken
    echo "Upload Vault root token and unseal key to MinIO..."
    ./mc cp unsealKey1 rootToken minio-vault/vault/
    else
    echo "Join Vault Cluster..."
    vault operator raft join "http://vault-0.vault-internal:8200" || true
    echo "Download Vault unseal key from MinIO..."
    ./mc cp minio-vault/vault/unsealKey1 ./ || true
    fi
    fi

    if vault status -format=json | ./jq -e "if (.sealed) then true else false end" >/dev/null; then
    echo "Unseal Vault..."
    vault operator unseal `cat unsealKey1`
    fi

    if vault status -format=json | ./jq -e "if ((.initialized) and (.sealed | not)) then true else false end" >/dev/null; then
    echo "Vault initialized and unsealed."
    exit 0
    else
    echo "Wait 5 seconds for another trying..."
    sleep 5
    fi
    done