123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- #!/usr/bin/env bash
- set -euo pipefail
- # ignore existing credentials
- unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
- profile=$1
- duration=${2:-28800}
- mfa_serial_number=$(aws configure get mfa_serial)
- if [ "$profile" != "default" ]; then
- if ! role_arn=$(aws configure get "profile.$profile.role_arn"); then
- echo "role_arn not set for profile $profile"
- echo "run aws configure set profile.$profile.role_arn <role arn>"
- exit 1
- fi
- fi
- read -srp "Password: " password
- >&2 echo ""
- use_cache=0
- cache_gpg="$XDG_RUNTIME_DIR/aws-$profile.gpg"
- if [ -z "${2:-}" ]; then
- use_cache=1
- fi
- function get_credentials {
- keepassxc-cli show -q "$KEEPASS_FILE" "$KEEPASS_AWS_ENTRY" -a "$1" <<< "$password"
- }
- function get_cached {
- if [ "$use_cache" -eq 0 ]; then
- return 1
- fi
- if [ ! -f "$cache_gpg" ]; then
- >&2 echo "No cached credentials, requesting new"
- return 1
- fi
- if ! cached=$(gpg --batch -d --passphrase "$password" "$cache_gpg"); then
- >&2 echo "Error getting cached credentials"
- exit 1
- fi
- expiration=$(date -d "$(jq -r '.Credentials.Expiration' <<< "$cached")" +%s)
- if [ "$expiration" -lt "$(date +%s)" ]; then
- >&2 echo "Cached credentials expired, requesting new"
- return 1
- fi
- >&2 echo "Using cached credentials, expires $(date -d "@$expiration" +%H:%M)"
- echo "$cached"
- }
- AWS_ACCESS_KEY_ID=$(get_credentials UserName)
- AWS_SECRET_ACCESS_KEY=$(get_credentials Password)
- if ! credentials=$(get_cached); then
- export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY
- read -rp "MFA: " mfa
- if [ "$profile" = "default" ]; then
- credentials=$(aws sts get-session-token --serial-number $mfa_serial_number --token-code "$mfa" --duration-seconds "$duration")
- else
- credentials=$(aws sts assume-role --serial-number $mfa_serial_number --token-code "$mfa" --role-arn "$role_arn" --role-session-name "$(hostname)" --duration-seconds "$duration")
- fi
- if [ "$use_cache" -eq 1 ]; then
- gpg --batch -c --passphrase "$password" <<< "$credentials" > "$cache_gpg"
- fi
- fi
- jq -r '.Credentials | @sh "
- export AWS_ACCESS_KEY_ID=\(.AccessKeyId)
- export AWS_SECRET_ACCESS_KEY=\(.SecretAccessKey)
- export AWS_SESSION_TOKEN=\(.SessionToken)
- "' <<< "$credentials"
|