Skip to content

Instantly share code, notes, and snippets.

@voron
Forked from tyzbit/cache-eks-token.sh
Last active May 15, 2023 15:32
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 voron/7c45572f754a1bf2870dc1c19fa7737e to your computer and use it in GitHub Desktop.
Save voron/7c45572f754a1bf2870dc1c19fa7737e to your computer and use it in GitHub Desktop.
Cache EKS tokens for kubectl
#!/bin/bash
# usage mimics aws execution to replace just the command, not args
function usage() {
echo "Usage: $0 --region eu-west-2 eks get-token --cluster-name prod"
}
if [ -z "$1" ]; then
usage
exit 1
fi
REGION=$2
CLUSTER_NAME=$6
NOW=$(date +%s)
TOKEN_FILE="$HOME/.kube/.${REGION}-${CLUSTER_NAME}.eks-token"
if [ -f "${TOKEN_FILE}" ]; then
ACCESS_TIME=$(date -r "${TOKEN_FILE}" +%s)
if [[ $((NOW-800)) -gt ${ACCESS_TIME} ]]; 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' "${TOKEN_FILE}"; echo $?) -gt 0 ]]; then
GENERATE_NEW_TOKEN="true"
fi
else
GENERATE_NEW_TOKEN="true"
fi
if [[ ${GENERATE_NEW_TOKEN} == "true" ]]; then
aws eks get-token \
--region "${REGION}" \
--cluster-name "${CLUSTER_NAME}" > "${TOKEN_FILE}"
fi
cat "${TOKEN_FILE}"
@voron
Copy link
Author

voron commented May 15, 2023

Save this script to ~/bin/ directory and replace command: aws with command: ../bin/cache-eks-token.sh inside your $KUBECONFIG or ${HOME}/.kube/config etc, f.e.

sed -i "" 's#command: aws#command: ../bin/cache-eks-token.sh#' ${KUBECONFIG}

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