Last active
May 18, 2023 13:50
-
-
Save sergei-zaiaev/31df48c1c14696d5095f7d610885e0be to your computer and use it in GitHub Desktop.
The script for kubeconfig generating.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# This script creates a service account and role binding between it and provided role as well as generates kubeconfig file. | |
# Requirements: | |
# 1. connection to k8s cluster | |
# 2. presence of role for binding. | |
# List of arguments: | |
# 1. Server URL | |
# 2. Namespace | |
# 3. Service account name | |
# 4. Role name | |
# Output: | |
# file `<namespace>.kubeconfig` containing kubeconfig data | |
set -e | |
SERVER=$1 | |
NAMESPACE=$2 | |
SERVICE_ACCOUNT_NAME=$3 | |
ROLE_NAME=$4 | |
echo "[+] Server URL: ${SERVER}" | |
echo "[+] Namespace: ${NAMESPACE}" | |
echo "[+] SA name: ${SERVICE_ACCOUNT_NAME}" | |
echo "[+] Role name: ${ROLE_NAME}" | |
echo "[+] Creating service account" | |
kubectl create sa ${SERVICE_ACCOUNT_NAME} -n ${NAMESPACE} -o yaml | |
echo | |
echo "[+] Creating rolebinding" | |
kubectl create rolebinding ${SERVICE_ACCOUNT_NAME} -n ${NAMESPACE} --role=${ROLE_NAME} --serviceaccount=${NAMESPACE}:${SERVICE_ACCOUNT_NAME} -o=yaml | |
echo | |
echo "[+] Getting CA cert and token" | |
SECRET_NAME=$(kubectl get sa/${SERVICE_ACCOUNT_NAME} -n ${NAMESPACE} -o jsonpath='{.secrets[0].name}') | |
CA=$(kubectl get secret/${SECRET_NAME} -n ${NAMESPACE} -o jsonpath='{.data.ca\.crt}') | |
TOKEN=$(kubectl get secret/${SECRET_NAME} -n ${NAMESPACE} -o jsonpath='{.data.token}' | base64 --decode) | |
echo | |
echo "[+] Creating kubeconfig" | |
echo " | |
apiVersion: v1 | |
kind: Config | |
clusters: | |
- name: kubernetes | |
cluster: | |
certificate-authority-data: ${CA} | |
server: ${SERVER} | |
contexts: | |
- name: ${NAMESPACE} | |
context: | |
cluster: kubernetes | |
namespace: ${NAMESPACE} | |
user: ${SERVICE_ACCOUNT_NAME} | |
current-context: ${NAMESPACE} | |
users: | |
- name: ${SERVICE_ACCOUNT_NAME} | |
user: | |
token: ${TOKEN} | |
" > ${NAMESPACE}.kubeconfig |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment