Skip to content

Instantly share code, notes, and snippets.

@abdennour
Last active January 16, 2024 19:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdennour/eb1f7cd3d1ca03ae92156633aa945a7b to your computer and use it in GitHub Desktop.
Save abdennour/eb1f7cd3d1ca03ae92156633aa945a7b to your computer and use it in GitHub Desktop.
Vault - Enable Kubernetes Auth Method
# $1: vault namespace
# $2: Vault Token Reviewer Service Account
vault_namespace=${1:-"vault"}
token_reviewer_sa=${2:-"vault"}
if [ -z "${VAULT_TOKEN}" ] || [ -z "${VAULT_ADDR}" ]; then
echo "ERROR: VAULT_TOKEN and VAULT_ADDR env vars are required"
exit 404
fi
cat <<EOF | kubectl apply -f -
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: ${token_reviewer_sa}
namespace: ${vault_namespace}
labels:
role: vault-token-review-for-k8s-auth
---
apiVersion: rbac.authorization.k8s.io/v1beta1
kind: ClusterRoleBinding
metadata:
name: role-tokenreview-binding
namespace: ${vault_namespace}
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: system:auth-delegator
subjects:
- kind: ServiceAccount
name: ${token_reviewer_sa}
namespace: ${vault_namespace}
EOF
# 1. enabling kube auth already done with Operator
export VAULT_SA_NAME=$(kubectl -n ${vault_namespace} get sa ${token_reviewer_sa} -o jsonpath="{.secrets[*]['name']}")
export SA_JWT_TOKEN=$(kubectl -n ${vault_namespace} get secret $VAULT_SA_NAME -o jsonpath="{.data.token}" | base64 --decode; echo)
export SA_CA_CRT=$(kubectl -n ${vault_namespace} get secret $VAULT_SA_NAME -o jsonpath="{.data['ca\.crt']}" | base64 --decode; echo)
export K8S_HOST=$(kubectl -n default get svc kubernetes -o jsonpath='{.spec.clusterIP}')
# 2. configure token reviewer for serviceaccount
vault write auth/kubernetes/config \
token_reviewer_jwt="$SA_JWT_TOKEN" \
kubernetes_host="https://$K8S_HOST" \
kubernetes_ca_cert="$SA_CA_CRT"
# 3. Add Role in Vault under the kube auth
#---------> Already done by the Operator
# 4. Test it - Validation
## Go to any pod matches the configuration of the role
## then LOGIN
###############################
# role_name=jekins
# curl --request POST
# --data '{"jwt": "'$(cat /run/secrets/kubernetes.io/serviceaccount/token;echo)'", "role": "jenkins"}'
# --cacert /run/secrets/kubernetes.io/serviceaccount/ca.crt
# http://vault.vault:8200/v1/auth/kubernetes/login
### Now try to read/write secrets ####################
# vault kv get --field=x secret/hello/world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment