-
-
Save akhilsreddy1/d371641e39f108151cfef74b798e7368 to your computer and use it in GitHub Desktop.
Kubernetes Service Account
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
# Inspired by: https://stackoverflow.com/questions/42170380/how-to-add-users-to-kubernetes-kubectl | |
# this script creates a service account (user1) on a Kubernetes cluster (tested with AWS EKS 1.9) | |
# prereqs: a kubectl ver 1.10 installed and proper configuration of the heptio authenticator | |
# this has been tested on Linux in a Cloud9 environment (for MacOS the syntax may be slightly different) | |
************************************************** | |
******* Create an account ******* | |
************************************************** | |
# Create service account for user user1 | |
kubectl create sa user1 | |
# Get related secret | |
secret=$(kubectl get sa user1 -o json | jq -r .secrets[].name) | |
# Get ca.crt from secret | |
kubectl get secret $secret -o json | jq -r '.data["ca.crt"]' | base64 -d > ca.crt | |
# Get service account token from secret | |
user_token=$(kubectl get secret $secret -o json | jq -r '.data["token"]' | base64 -d) | |
# Get information from your kubectl config (current-context, server..) | |
# get current context | |
c=`kubectl config current-context` | |
# get cluster name of context | |
name=`kubectl config get-contexts $c | awk '{print $3}' | tail -n 1` | |
# get endpoint of current context | |
endpoint=`kubectl config view -o jsonpath="{.clusters[?(@.name == \"$name\")].cluster.server}"` | |
************************************************** | |
******* Consume the account ******* | |
************************************************** | |
# Set cluster | |
kubectl config set-cluster eks-cluster --embed-certs=true --server=$endpoint --certificate-authority=./ca.crt | |
# Set user credentials | |
kubectl config set-credentials user1-eks-cluster --token=$user_token | |
# Create the yaml to bind the cluster admin role to user1 | |
cat <<EOF >> rbac-config-user1.yaml | |
apiVersion: rbac.authorization.k8s.io/v1beta1 | |
kind: ClusterRoleBinding | |
metadata: | |
name: user1 | |
roleRef: | |
apiGroup: rbac.authorization.k8s.io | |
kind: ClusterRole | |
name: cluster-admin | |
subjects: | |
- kind: ServiceAccount | |
name: user1 | |
namespace: default | |
EOF | |
# Apply the policy to user1 | |
kubectl apply -f rbac-config-user1.yaml | |
# Define the combination of user1 user with the EKS cluster | |
kubectl config set-context user1-eks-cluster --cluster=eks-cluster --user=user1-eks-cluster --namespace=default | |
kubectl config use-context user1-eks-cluster | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment