k8s-deployment/scripts/get_kubeconfig_from_sa.sh

50 lines
1.5 KiB
Bash
Raw Normal View History

2024-10-10 05:57:43 +00:00
#!/usr/bin/env bash
2024-10-10 05:52:30 +00:00
# you need to have kubectl on PATH with the context set to the cluster you want to create the config for
# Cosmetics for the created config
2024-10-10 05:57:43 +00:00
clusterName="${CLUSTER_NAME}"
2024-10-10 05:52:30 +00:00
# your server address goes here get it via `kubectl cluster-info`
2024-10-10 05:57:43 +00:00
server="${CLUSTER_URL}"
2024-10-10 05:52:30 +00:00
# the Namespace and ServiceAccount name that is used for the config
2024-10-10 05:57:43 +00:00
export namespace='pipelines'
export serviceAccount='woodpecker-ci'
2024-10-10 05:52:30 +00:00
# The following automation does not work from Kubernetes 1.24 and up.
# You might need to
# define a Secret, reference the ServiceAccount there and set the secretName by hand!
# See https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/#manually-create-a-long-lived-api-token-for-a-serviceaccount for details
secretName=$(kubectl --namespace="$namespace" get serviceAccount "$serviceAccount" -o=jsonpath='{.secrets[0].name}')
######################
# actual script starts
set -o errexit
ca=$(kubectl --namespace="$namespace" get secret/"$secretName" -o=jsonpath='{.data.ca\.crt}')
token=$(kubectl --namespace="$namespace" get secret/"$secretName" -o=jsonpath='{.data.token}' | base64 --decode)
echo "
---
apiVersion: v1
kind: Config
clusters:
- name: ${clusterName}
cluster:
certificate-authority-data: ${ca}
server: ${server}
contexts:
- name: ${serviceAccount}@${clusterName}
context:
cluster: ${clusterName}
namespace: ${namespace}
user: ${serviceAccount}
users:
- name: ${serviceAccount}
user:
token: ${token}
current-context: ${serviceAccount}@${clusterName}
"