Skip to content

Instantly share code, notes, and snippets.

@ejhayes
Created December 12, 2019 18:19
Show Gist options
  • Save ejhayes/0d012f9630a600946163bfb92da40b0f to your computer and use it in GitHub Desktop.
Save ejhayes/0d012f9630a600946163bfb92da40b0f to your computer and use it in GitHub Desktop.
Cached STS token for Kubectl on AWS EKS
#!/usr/bin/env bash
CACHE_FILE=${HOME}/.kube/cache/aws-${AWS_PROFILE}.cache
MAXTIME=800
if [ -f $CACHE_FILE ]; then
TS_DB=$(stat -t "%s" ${CACHE_FILE} | cut -d' ' -f10 | tr -d '"')
AGE=$(( `date +%s` - $TS_DB ))
if [[ $AGE -le $MAXTIME ]]; then
cat ${CACHE_FILE}
else
aws "$@" | tee $CACHE_FILE
fi
else
aws "$@" | tee $CACHE_FILE
fi

cached token for kubectl on eks

This will greatly speed up any kubectl commands that run. Otherwise each kubectl call has to regenerate a STS token. This one caches the value for 800 seconds (tokens are valid for ~900 seconds).

To use:

  • Add cached-aws to /usr/local/bin and set chmod u+x /usr/local/bin/cached-aws
  • Update ~/.kube/config to use the cached command (switch command: aws to command: cached-aws

Verify with kubectl get pods or similar. After the first call you should notice API calls are much quicker.

- name: <cluster arn>
user:
exec:
apiVersion: client.authentication.k8s.io/v1alpha1
args:
- --region
- <region>
- eks
- get-token
- --cluster-name
- <cluster name>
- --role
- <role arn>
command: cached-aws
env:
- name: AWS_PROFILE
value: <profile name>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment