Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # requires jq - the command-line JSON processor - to be installed
  4.  
  5. function get-session-token() {
  6. AWSMFA_SERIAL="default_DEVICE"
  7. AWSCLI_STS_COMMAND="get-session-token"
  8.  
  9. unset AWSCLI_OPTIONS
  10. unset AWSCLI_STS_OPTIONS
  11. unset AWSMFA_CREDENTIALS
  12.  
  13. OPTIND=1
  14. while getopts ":p:r:h" opt
  15. do
  16. case ${opt} in
  17. h)
  18. echo "Usage: get-session-token [-p awscli-profile] [-r AWS_IAM_ROLE_ARN] | -h"
  19. echo -e " -h\tprint this help screen"
  20. echo -e " -p\trequest credentials using the given awscli profile instead of the default one"
  21. echo -e " -r\trequest credentials for the given IAM role ARN - can be combined with option '-p'"
  22. return 0
  23. ;;
  24. p)
  25. AWSCLI_OPTIONS=( "${AWSCLI_OPTIONS[@]}" "--profile ${OPTARG}" )
  26. case ${OPTARG} in
  27. profile1)
  28. AWSMFA_SERIAL="arn:aws:iam::111222333444:mfa/your.user"
  29. ;;
  30. profile2)
  31. AWSMFA_SERIAL="arn:aws:iam::555666777888:mfa/your.other-user"
  32. ;;
  33. profile3)
  34. unset AWSMFA_SERIAL
  35. ;;
  36. esac
  37. ;;
  38. r)
  39. AWSCLI_STS_COMMAND="assume-role"
  40. AWSCLI_STS_OPTIONS=( "${AWSCLI_STS_OPTIONS[@]}" "--role-arn ${OPTARG}" )
  41. AWSCLI_STS_OPTIONS=( "${AWSCLI_STS_OPTIONS[@]}" "--role-session-name ${USER}" )
  42. ;;
  43. \?)
  44. echo "Invalid option: -${OPTARG}" >&2
  45. return 1
  46. ;;
  47. :)
  48. unset OPTARG_DESCRIPTION
  49.  
  50. case ${OPTARG} in
  51. p)
  52. OPTARG_DESCRIPTION="aws-cli profile"
  53. ;;
  54. r)
  55. OPTARG_DESCRIPTION="aws iam role-arn"
  56. ;;
  57. esac
  58.  
  59. echo "Error: Option -${OPTARG} requires an argument: '${OPTARG_DESCRIPTION}'" >&2
  60. return 1
  61. ;;
  62. esac
  63. done
  64.  
  65. if [ -n "${AWSMFA_SERIAL}" ]
  66. then
  67. read -s -p "Enter MFA code: " token_code && echo
  68. AWSMFA_CREDENTIALS=( "--serial-number ${AWSMFA_SERIAL}" "--token-code ${token_code}" )
  69. fi
  70.  
  71. reset-session-token
  72. aws_session_information=$(aws ${AWSCLI_OPTIONS[@]} sts ${AWSCLI_STS_COMMAND} ${AWSCLI_STS_OPTIONS[@]} ${AWSMFA_CREDENTIALS[@]})
  73.  
  74. export AWS_ACCESS_KEY_ID=$(echo ${aws_session_information} | jq -r .Credentials.AccessKeyId)
  75. export AWS_SECRET_ACCESS_KEY=$(echo ${aws_session_information} | jq -r .Credentials.SecretAccessKey)
  76. export AWS_SESSION_TOKEN=$(echo ${aws_session_information} | jq -r .Credentials.SessionToken)
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement