generate sa kubeconfig.sh
#!/bin/bash
# This script generates a kubeconfig file for a ServiceAccount
# by reading from an existing Secret object.
# It assumes:
# 1. A ServiceAccount named $1 exists in namespace $2.
# 2. A Secret named $1 (same as SA_NAME) exists in namespace $2.
# 3. This Secret is of type 'kubernetes.io/service-account-token'.
# --- Configuration ---
if [[ -z "$1" ]] || [[ -z "$2" ]]; then
echo "Usage: $0 <service_account_name> <namespace>"
echo "Note: This script assumes a Secret with the same name as the ServiceAccount exists."
echo "Example: $0 foo bar"
exit 1
fi
SA_NAME=$1
SA_NAMESPACE=$2
# Assume Secret name matches SA name
SECRET_NAME=$SA_NAME
KUBECFG_FILE="${SA_NAME}-${SA_NAMESPACE}.kubeconfig"
# --- 1. Get Cluster Details Dynamically ---
echo "Getting cluster details from current context..."
CURRENT_CONTEXT=$(kubectl config current-context)
CLUSTER_NAME=$(kubectl config view -o jsonpath="{.contexts[?(@.name==\"$CURRENT_CONTEXT\")].context.cluster}")
SERVER_URL=$(kubectl config view -o jsonpath="{.clusters[?(@.name==\"$CLUSTER_NAME\")].cluster.server}")
# Get the cluster's CA data (must be base64 encoded for the kubeconfig)
# Use --raw to get the unredacted data.
CA_DATA=$(kubectl config view --raw -o jsonpath="{.clusters[?(@.name==\"$CLUSTER_NAME\")].cluster.certificate-authority-data}")
if [[ -z "$CA_DATA" ]]; then
echo "Error: Could not find 'certificate-authority-data' for cluster '$CLUSTER_NAME'."
echo "This script does not support clusters configured with 'certificate-authority' (file path)."
exit 1
fi
# --- 2. Get ServiceAccount Token from Secret ---
echo "Extracting token from Secret '$SECRET_NAME' in '$SA_NAMESPACE'..."
# This command gets the base64-encoded token from the secret and decodes it.
TOKEN=$(kubectl get secret -n $SA_NAMESPACE $SECRET_NAME -o jsonpath={.data.token} | base64 -d)
if [[ -z "$TOKEN" ]]; then
echo "Error: Failed to get token from Secret '$SECRET_NAME'."
echo "Does the Secret exist and is it populated?"
exit 1
fi
# --- 3. Create the Kubeconfig File ---
echo "Creating kubeconfig file: $KUBECFG_FILE"
cat > "$KUBECFG_FILE" << EOF
apiVersion: v1
kind: Config
clusters:
- cluster:
server: $SERVER_URL
certificate-authority-data: $CA_DATA
name: cluster
contexts:
- context:
cluster: cluster
user: user
name: context
current-context: context
users:
- name: user
user:
token: $TOKEN
EOF