Created
June 29, 2020 16:51
-
-
Save tkalus/0f1be62e8e9cd4b8880fbb32cc029213 to your computer and use it in GitHub Desktop.
Friendlier AWS AssumeRole for Shell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
assume_role_sh() { | |
local AWSCLI_PYTHON | |
# Grab the shebang from the awscli | |
AWSCLI_PYTHON="$(sed -n '/^#!/s/^#!\([^ ]*\).*$/\1/p' "$(command -v aws)")" | |
"${AWSCLI_PYTHON:-command python3}" - "${@}" << EOD | |
"""AssumeRole for Shell""" | |
import os | |
import subprocess | |
import sys | |
import botocore.session | |
ENV_VARS = ( | |
("AWS_ACCESS_KEY_ID", "AccessKeyId"), | |
("AWS_SECRET_ACCESS_KEY", "SecretAccessKey"), | |
("AWS_SESSION_TOKEN", "SessionToken"), | |
) | |
cmd_line = dict(enumerate(sys.argv)) | |
role_arn = cmd_line[1] | |
role_session_name = ( | |
cmd_line.get(2, "") | |
or subprocess.run( | |
["git", "config", "user.email"], | |
stdout=subprocess.PIPE, | |
).stdout.decode('utf-8').rstrip() | |
or "[email protected]" | |
) | |
session = botocore.session.get_session() | |
sts = session.create_client("sts", region_name="us-east-1") | |
creds = sts.assume_role( | |
RoleArn=role_arn, | |
RoleSessionName=role_session_name, | |
).get("Credentials", {}) | |
for env_var, cred_key in ENV_VARS: | |
print(f"export {env_var}={creds.get(cred_key, '')}") | |
sys.exit(0) | |
EOD | |
} | |
assume_role_sh "${@}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment