get-aws-login 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. # ignore existing credentials
  4. unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
  5. profile=$1
  6. duration=${2:-28800}
  7. mfa_serial_number=$(aws configure get mfa_serial)
  8. if [ "$profile" != "default" ]; then
  9. if ! role_arn=$(aws configure get "profile.$profile.role_arn"); then
  10. echo "role_arn not set for profile $profile"
  11. echo "run aws configure set profile.$profile.role_arn <role arn>"
  12. exit 1
  13. fi
  14. fi
  15. read -srp "Password: " password
  16. >&2 echo ""
  17. use_cache=0
  18. cache_gpg="$XDG_RUNTIME_DIR/aws-$profile.gpg"
  19. if [ -z "${2:-}" ]; then
  20. use_cache=1
  21. fi
  22. function get_credentials {
  23. keepassxc-cli show -q "$KEEPASS_FILE" "$KEEPASS_AWS_ENTRY" -a "$1" <<< "$password"
  24. }
  25. function get_cached {
  26. if [ "$use_cache" -eq 0 ]; then
  27. return 1
  28. fi
  29. if [ ! -f "$cache_gpg" ]; then
  30. >&2 echo "No cached credentials, requesting new"
  31. return 1
  32. fi
  33. if ! cached=$(gpg --batch -d --passphrase "$password" "$cache_gpg"); then
  34. >&2 echo "Error getting cached credentials"
  35. exit 1
  36. fi
  37. expiration=$(date -d "$(jq -r '.Credentials.Expiration' <<< "$cached")" +%s)
  38. if [ "$expiration" -lt "$(date +%s)" ]; then
  39. >&2 echo "Cached credentials expired, requesting new"
  40. return 1
  41. fi
  42. >&2 echo "Using cached credentials, expires $(date -d "@$expiration" +%H:%M)"
  43. echo "$cached"
  44. }
  45. AWS_ACCESS_KEY_ID=$(get_credentials UserName)
  46. AWS_SECRET_ACCESS_KEY=$(get_credentials Password)
  47. if ! credentials=$(get_cached); then
  48. export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY
  49. read -rp "MFA: " mfa
  50. if [ "$profile" = "default" ]; then
  51. credentials=$(aws sts get-session-token --serial-number $mfa_serial_number --token-code "$mfa" --duration-seconds "$duration")
  52. else
  53. credentials=$(aws sts assume-role --serial-number $mfa_serial_number --token-code "$mfa" --role-arn "$role_arn" --role-session-name "$(hostname)" --duration-seconds "$duration")
  54. fi
  55. if [ "$use_cache" -eq 1 ]; then
  56. gpg --batch -c --passphrase "$password" <<< "$credentials" > "$cache_gpg"
  57. fi
  58. fi
  59. jq -r '.Credentials | @sh "
  60. export AWS_ACCESS_KEY_ID=\(.AccessKeyId)
  61. export AWS_SECRET_ACCESS_KEY=\(.SecretAccessKey)
  62. export AWS_SESSION_TOKEN=\(.SessionToken)
  63. "' <<< "$credentials"