Skip to content

Instantly share code, notes, and snippets.

@tyzbit
Created January 23, 2020 16:36
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tyzbit/c9947809cc5146d36ae4ae6c312ce538 to your computer and use it in GitHub Desktop.
Save tyzbit/c9947809cc5146d36ae4ae6c312ce538 to your computer and use it in GitHub Desktop.
Cache EKS tokens for kubectl
function usage() {
echo "Usage: $0 [region] [cluster name] [role arn]"
echo "If you're not using a role, [region] and [role arn] are optional"
echo "If you just use cluster name, you need aws-iam-authenticator installed"
}
if [ -z $1 ]; then
usage
exit 1
fi
now=$(date +%s)
if [ ! -z $3 ]; then
tokenfile="$HOME/.kube/.$2.eks-token"
else
tokenfile="$HOME/.kube/.$1.eks-token"
fi
if [ -f $tokenfile ]; then
accesstime=$(date +%s -r $tokenfile)
if [[ $(($now-800)) -gt $accesstime ]]; then
generate_new_token="true"
fi
# In case the credential file exists but is messed up, we'll generate a new one
if [[ $(grep -q 'ExecCredential' $tokenfile; echo $?) -gt 0 ]]; then
generate_new_token="true"
fi
else
generate_new_token="true"
fi
if [[ $generate_new_token == "true" ]]; then
if [ ! -z $3 ]; then
aws eks get-token \
--region $1 \
--cluster-name $2 \
--role $3 > $tokenfile
else
aws-iam-authenticator token \
-i $1 > $tokenfile
fi
fi
cat $tokenfile
@tyzbit
Copy link
Author

tyzbit commented Jan 23, 2020

Add this to the users array in your kubeconfig

- name: arn:aws:eks:us-east-2:[accountID]:cluster/[AWSCluster]
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1alpha1
      args:
      - [region]
      - [AWSCluster]
      - arn:aws:iam::[accountID]:role/[role]
      command: /home/[user]/scripts/cache-eks-token.sh
      env: null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment