Last active
May 31, 2022 19:22
-
-
Save vergenzt/38ef14b4e64ad5157aa3a63f00833641 to your computer and use it in GitHub Desktop.
aws_op_auto_reauth.sh
This file contains 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 python3 | |
: "${AWS_ADFS_HOST:?}" | |
: "${AWS_ADFS_REGION:?}" | |
: "${AWS_ADFS_OP_ITEM_UUID:?}" | |
# op session expires after 30 minutes of inactivity, so reauth every 25 minutes by default | |
: "${AUTH_INTERVAL:=+25 minutes}" | |
aws_adfs_auth() { | |
AWS_PROFILE=$1; AWS_ROLE_ARN=$2; | |
echo "Authenticating $AWS_PROFILE with aws-adfs... " | |
( | |
username=$(op item get "$AWS_ADFS_OP_ITEM_UUID" --fields username) | |
password=$(op item get "$AWS_ADFS_OP_ITEM_UUID" --fields password) | |
export username password | |
# show our work (just not username or password) | |
set -x | |
rm -f ~/.aws/adfs_cookies | |
# sometimes aws-adfs fails with "This account does not have access to any roles" | |
# ... so retry up to N-1 times | |
for _ in {1..5}; do | |
aws-adfs login \ | |
--profile="$AWS_PROFILE" \ | |
--role-arn="$AWS_ROLE_ARN" \ | |
--adfs-host="$AWS_ADFS_HOST" \ | |
--region="$AWS_ADFS_REGION" \ | |
--env \ | |
< <( | |
# sometimes aws-adfs prompts for the totp more than once... so let's keep giving it | |
yes "$( | |
op item get "$AWS_ADFS_OP_ITEM_UUID" --otp | |
)" | |
) \ | |
&& break \ | |
sleep 10 | |
done | |
) | |
echo 'Done. ' | |
echo 'Verifying... ' | |
( | |
set -x | |
aws --profile="$AWS_PROFILE" sts get-caller-identity >/dev/null | |
) | |
echo 'Done.' | |
} | |
while true; do | |
now="$(date -Is)" | |
if [[ "$now" > "${later:-}" ]]; then | |
if [[ "${later:-}" ]]; then echo 'Reached reauthentication time.'; fi # finish the "current time"/"waiting until" line | |
# aws_adfs_auth PROFILE_1 arn:aws:iam::123456789012:role/ADFS-ROLE-1 | |
# aws_adfs_auth PROFILE_2 arn:aws:iam::123456789012:role/ADFS-ROLE-2 | |
# aws_adfs_auth PROFILE_3 arn:aws:iam::123456789012:role/ADFS-ROLE-3 | |
later=$(date -Is -d "$AUTH_INTERVAL") | |
echo | |
echo "Waiting until $later to reauthenticate." | |
fi | |
echo -en "\rCurrent time: $now... " | |
sleep 1 | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment