Skip to content

Instantly share code, notes, and snippets.

@realjktu
Forked from mreferre/k8s-sa
Created October 3, 2018 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save realjktu/46971d28edc7f7edf8681de3dec1d070 to your computer and use it in GitHub Desktop.
Save realjktu/46971d28edc7f7edf8681de3dec1d070 to your computer and use it in GitHub Desktop.
Kubernetes Service Account
# 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