0

TL;DR: What is the proper way to login from Vault CLI in a Kubernetes Pod using the Kubernetes Auth Method.

I want to create regular snapshots from my HashiCorp Vault raft storage. So I created a Kubernetes CronJob running the same image as my Vault cluster, that executes the following command on a schedule:

vault operator raft snapshot save /backups/daily-$(date +"%Y-%m-%d-%H-%M").snap

/backups is a persistent volume mounted to the Pod.

Of course the Pod needs to be authenticated to Vault. I have the Kubernetes Auth Method enabled. The Pods created by the CronJob/Job are running with a service account vault-backups. So I added a role vault_backups to Vault, that is bound to the service account vault-backups in the vault namespace and assigned it a new policy raft_snapshots_read with the following content:

path "/sys/storage/raft/snapshot"
{
  capabilities = ["read"]
}

For the actual login I'm currently doing the following:

export VAULT_TOKEN=$(vault write auth/kubernetes/login \
    role=vault_backups \
    jwt=$(cat /run/secrets/kubernetes.io/serviceaccount/token) |\
  grep -w token |\
  awk '{print $2}')

This command now uses the JWT token of the service account vault-backups to login with the role vault_backup. It returns a formatted output (by default table) containing the token. I grep and parse the line with the token to save it into VAULT_TOKEN.

Afterwards the raft snapshot save command executes successfully and I have my snapshot saved to the volume.

The solution works, but I'm not sure if this is the proper way to do this. First of all parsing the output feels kind of strange. Especially since there is the vault login command. But for vault login -method kubernetes it fails with:

Unknown auth method: kubernetes. Use "vault auth list" to see the complete list of auth methods. Additionally, some auth methods are only available via the HTTP API.

vault auth list includes an entry with type kubernetes, so I assume it is only available via the HTTP API.

I know that there is the option to get the output of vault write auth/kubernetes/login as JSON, but a) there is nothing installed in the container to parse JSON (like jq) and b) this still is a two step procedure, that includes parsing the result. It's just more structured then.

So is there a better way to achieve the login?

Thanks in advance!

Max N.
  • 101
  • 1

1 Answers1

0

While looking through other tutorials I saw, that there is the parameter -field=<FIELD NAME>, that can be used to filter the output of vault write for specific fields.

So the login now looks like this:

export VAULT_TOKEN=$(vault write -field=token auth/kubernetes/login \
    role=vault_backups \
    jwt=$(cat /run/secrets/kubernetes.io/serviceaccount/token))

Thanks anyways.

Max N.
  • 101
  • 1