Skip to content

Instantly share code, notes, and snippets.

@navicore
Created December 13, 2022 19:52
Show Gist options
  • Save navicore/d585b27315f0a0da736e684c629bb381 to your computer and use it in GitHub Desktop.
Save navicore/d585b27315f0a0da736e684c629bb381 to your computer and use it in GitHub Desktop.
eks saml2aws script for kubectl context setup

bin/ek

#!/usr/bin/env bash

# 
# install aws, saml2aws, kubectl 
# 
# Switch between AWS EKS environments w/o any menu selections.  You
# do not need to remember what AWS account or region a client is deployed in.
#
# usage: 
#
# ek demo 
#
# the above usage: 
#   1. authenticates to aws
#   2. obtains the kubeconfig
#   3. sets the current kubectl context with the namespace of the deployment, dtlab-demo-prod
#
# note, use "ek" together with "ek-complete.sh" to get tab completion
#

declare -A current_ns

#
# START declare all your environments here
#

#
# note: environments are grouped by AWS account
#
# declare your URN and ROLE values for each AWS account
#
#  - the benifit of maintaining them here is that you will never face
#  the saml2aws menu even if your MFA SSO needs refreshing
#

# PRD1 US EAST

US_EAST_URN="arn:aws:sts::xxxxxxxxxx:assumed-role/EKSTenant/navicore"
US_EAST_ROLE="arn:aws:iam::xxxxxxxxxx:role/EKSTenant"

current_ns["demo","urn"]=$US_EAST_URN
current_ns["demo","role"]=$US_EAST_ROLE
current_ns["demo","region"]="us-east-1"
current_ns["demo","name"]="green"
current_ns["demo","ENV_NAMESPACE"]="demo"

current_ns["prod","urn"]=$US_EAST_URN
current_ns["prod","role"]=$US_EAST_ROLE
current_ns["prod","region"]="us-east-1"
current_ns["prod","name"]="green"
current_ns["prod","ENV_NAMESPACE"]="prod"

#
# END declare all your environments here
#

key=$1

URN=${current_ns[${key},"urn"]}
ROLE=${current_ns[${key},"role"]}
REGION=${current_ns[${key},"region"]}
NAME=${current_ns[${key},"name"]}
ENV_NAMESPACE=${current_ns[${key},"ENV_NAMESPACE"]}

rm ~/.aws/credentials
saml2aws login --skip-prompt --duo-mfa-option "Duo Push" --aws-urn=$URN --role=$ROLE
aws eks --region $REGION update-kubeconfig --name $NAME > /dev/null
kubectl config set-context --current --namespace=${ENV_NAMESPACE} > /dev/null

bin/ek-complete.sh

#
# for tab completion with the "ek" script.
# run from your "~/.zshrc" or equiv shell init script:
#
# source ~/bin/ek-complete.sh
#
complete -W 'demo prod' ek
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment