Skip to content

Instantly share code, notes, and snippets.

@mexisme
Last active March 27, 2017 11:42
Show Gist options
  • Save mexisme/f516b600b27032cd48aeeb6c79feebf7 to your computer and use it in GitHub Desktop.
Save mexisme/f516b600b27032cd48aeeb6c79feebf7 to your computer and use it in GitHub Desktop.
#!/bin/bash
PROGNAME=$(basename $0)
PROGDIR=$(dirname $0)
: ${MyTemp:=$(mktemp -d "${TMPDIR:-/tmp/}${PROGNAME}.XXXXXXXXXXXX")}
## TODO: Allow me to set this up via $AWS_PROFILE (i.e. read the credentials file)
: ${ROLE_ARN:=arn:aws:iam::XXXX:role/XXXX}
: ${ROLE_SESSION:=${USER}-assume-admin}
credentials_file="assume-role-credentials.txt"
( cd "${MyTemp}"
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
if ! [ -f "${credentials_file}" ]; then
## TODO: Allow easy-overriding of the Role session:
aws sts assume-role --role-arn="${ROLE_ARN}" --role-session-name="${ROLE_SESSION}" >"${credentials_file}"
fi
# ${PROGDIR}/assume-role.rb "${credentials_file}"
cat "${credentials_file}" >&2
ruby <<EOT
creds = '${credentials_file}'
#creds = ARGV[0]
fail 'No files given' unless creds
File.open(creds, 'r') do |f|
kv_pairs = f.readlines.map do |l|
l.chomp!
m = /^\s+"([a-zA-Z]+)":\s+"(.+)"/.match(l)
[m[1], m[2]] if m
end
tokens = kv_pairs.map do |l|
if l
case l[0]
when /AccessKeyId/
['AWS_ACCESS_KEY_ID', l[1]]
when /SecretAccessKey/
['AWS_SECRET_ACCESS_KEY', l[1]]
when /SessionToken/
['AWS_SESSION_TOKEN', l[1]]
else
nil
end
end
end.compact
lines = tokens.map do |l|
"#{l[0]}='#{l[1]}'; export #{l[0]}"
end
puts lines.join "\n"
end
EOT
)
rm -rf "${MyTemp}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment