Skip to content

Instantly share code, notes, and snippets.

@ktrysmt
Last active November 18, 2020 16:41
Show Gist options
  • Save ktrysmt/a24a183fa5ab32d53115f16b933e37ad to your computer and use it in GitHub Desktop.
Save ktrysmt/a24a183fa5ab32d53115f16b933e37ad to your computer and use it in GitHub Desktop.
aws account context switcher by Makefile
[profile iamA]
aws_access_key_id =
aws_secret_access_key =
region = ap-northeast-1
.DEFAULT_GOAL:=help
THIS_FILE := $(lastword $(MAKEFILE_LIST))
CRED_TMP := /tmp/.credentials.tmp
CRED := ~/.aws/credentials
PARENT:=iamA
SERIAL:=arn:aws:iam::1234567890ab:mfa/iam-username
DURATION:=
code:=000000
setup: ## install dependency
@brew install jq
assume/roleA: ## get credential: `make assume/roleA code=000000`
@$(MAKE) -f $(THIS_FILE) assume \
ROLE_ARN=arn:aws:iam::1234567890cd:role/role-a
assume/roleA/long ## get credential longer: `make assume/roleA/long code=000000`
@$(MAKE) -f $(THIS_FILE) assume \
ROLE_ARN=arn:aws:iam::1234567890cd:role/role-a \
DURATION='--duration-seconds 43200'
assume/roleB: ## get credential: `make assume/roleB code=000000`
@$(MAKE) -f $(THIS_FILE) assume \
ROLE_ARN=arn:aws:iam::1234567890ab:role/role-b
token/iamA : ## get credential: `make token/iamA CODE=000000`
aws --profile $(PARENT) sts get-session-token --serial-number $(SERIAL) --token-code $(CODE) > $(CRED_TMP)
@$(MAKE) -f $(THIS_FILE) output
assume:
aws --profile $(PARENT) sts assume-role \
--role-arn $(ROLE_ARN) \
--role-session-name temp-session \
--serial-number $(SERIAL) $(DURATION) \
--token-code $(code) > $(CRED_TMP)
@$(MAKE) -f $(THIS_FILE) output
output:
@echo "[default]" > $(CRED)
@echo aws_access_key_id=$$(cat ${CRED_TMP} | jq -r ".Credentials.AccessKeyId") >> $(CRED)
@echo aws_secret_access_key=$$(cat ${CRED_TMP} | jq -r ".Credentials.SecretAccessKey") >> $(CRED)
@echo aws_session_token=$$(cat ${CRED_TMP} | jq -r ".Credentials.SessionToken") >> $(CRED)
@echo "region = ap-northeast-1" >> $(CRED)
help: ## This STDOUT
@grep -E '^[/a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment