aws.plugin.zsh 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. function agp() {
  2. echo $AWS_PROFILE
  3. }
  4. function agr() {
  5. echo $AWS_REGION
  6. }
  7. # AWS profile selection
  8. function asp() {
  9. if [[ -z "$1" ]]; then
  10. unset AWS_DEFAULT_PROFILE AWS_PROFILE AWS_EB_PROFILE AWS_PROFILE_REGION
  11. echo AWS profile cleared.
  12. return
  13. fi
  14. local -a available_profiles
  15. available_profiles=($(aws_profiles))
  16. if [[ -z "${available_profiles[(r)$1]}" ]]; then
  17. echo "${fg[red]}Profile '$1' not found in '${AWS_CONFIG_FILE:-$HOME/.aws/config}'" >&2
  18. echo "Available profiles: ${(j:, :)available_profiles:-no profiles found}${reset_color}" >&2
  19. return 1
  20. fi
  21. export AWS_DEFAULT_PROFILE=$1
  22. export AWS_PROFILE=$1
  23. export AWS_EB_PROFILE=$1
  24. export AWS_PROFILE_REGION=$(aws configure get region)
  25. if [[ "$2" == "login" ]]; then
  26. aws sso login
  27. fi
  28. }
  29. # AWS region selection
  30. function asr() {
  31. if [[ -z "$1" ]]; then
  32. unset AWS_DEFAULT_REGION AWS_REGION
  33. echo AWS region cleared.
  34. return
  35. fi
  36. local -a available_regions
  37. available_regions=($(aws_regions))
  38. if [[ -z "${available_regions[(r)$1]}" ]]; then
  39. echo "${fg[red]}Available regions: \n$(aws_regions)"
  40. return 1
  41. fi
  42. export AWS_REGION=$1
  43. export AWS_DEFAULT_REGION=$1
  44. }
  45. # AWS profile switch
  46. function acp() {
  47. if [[ -z "$1" ]]; then
  48. unset AWS_DEFAULT_PROFILE AWS_PROFILE AWS_EB_PROFILE
  49. unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
  50. echo AWS profile cleared.
  51. return
  52. fi
  53. local -a available_profiles
  54. available_profiles=($(aws_profiles))
  55. if [[ -z "${available_profiles[(r)$1]}" ]]; then
  56. echo "${fg[red]}Profile '$1' not found in '${AWS_CONFIG_FILE:-$HOME/.aws/config}'" >&2
  57. echo "Available profiles: ${(j:, :)available_profiles:-no profiles found}${reset_color}" >&2
  58. return 1
  59. fi
  60. local profile="$1"
  61. local mfa_token="$2"
  62. # Get fallback credentials for if the aws command fails or no command is run
  63. local aws_access_key_id="$(aws configure get aws_access_key_id --profile $profile)"
  64. local aws_secret_access_key="$(aws configure get aws_secret_access_key --profile $profile)"
  65. local aws_session_token="$(aws configure get aws_session_token --profile $profile)"
  66. # First, if the profile has MFA configured, lets get the token and session duration
  67. local mfa_serial="$(aws configure get mfa_serial --profile $profile)"
  68. local sess_duration="$(aws configure get duration_seconds --profile $profile)"
  69. if [[ -n "$mfa_serial" ]]; then
  70. local -a mfa_opt
  71. if [[ -z "$mfa_token" ]]; then
  72. echo -n "Please enter your MFA token for $mfa_serial: "
  73. read -r mfa_token
  74. fi
  75. if [[ -z "$sess_duration" ]]; then
  76. echo -n "Please enter the session duration in seconds (900-43200; default: 3600, which is the default maximum for a role): "
  77. read -r sess_duration
  78. fi
  79. mfa_opt=(--serial-number "$mfa_serial" --token-code "$mfa_token" --duration-seconds "${sess_duration:-3600}")
  80. fi
  81. # Now see whether we need to just MFA for the current role, or assume a different one
  82. local role_arn="$(aws configure get role_arn --profile $profile)"
  83. local sess_name="$(aws configure get role_session_name --profile $profile)"
  84. if [[ -n "$role_arn" ]]; then
  85. # Means we need to assume a specified role
  86. aws_command=(aws sts assume-role --role-arn "$role_arn" "${mfa_opt[@]}")
  87. # Check whether external_id is configured to use while assuming the role
  88. local external_id="$(aws configure get external_id --profile $profile)"
  89. if [[ -n "$external_id" ]]; then
  90. aws_command+=(--external-id "$external_id")
  91. fi
  92. # Get source profile to use to assume role
  93. local source_profile="$(aws configure get source_profile --profile $profile)"
  94. if [[ -z "$sess_name" ]]; then
  95. sess_name="${source_profile:-profile}"
  96. fi
  97. aws_command+=(--profile="${source_profile:-profile}" --role-session-name "${sess_name}")
  98. echo "Assuming role $role_arn using profile ${source_profile:-profile}"
  99. else
  100. # Means we only need to do MFA
  101. aws_command=(aws sts get-session-token --profile="$profile" "${mfa_opt[@]}")
  102. echo "Obtaining session token for profile $profile"
  103. fi
  104. # Format output of aws command for easier processing
  105. aws_command+=(--query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' --output text)
  106. # Run the aws command to obtain credentials
  107. local -a credentials
  108. credentials=(${(ps:\t:)"$(${aws_command[@]})"})
  109. if [[ -n "$credentials" ]]; then
  110. aws_access_key_id="${credentials[1]}"
  111. aws_secret_access_key="${credentials[2]}"
  112. aws_session_token="${credentials[3]}"
  113. fi
  114. # Switch to AWS profile
  115. if [[ -n "${aws_access_key_id}" && -n "$aws_secret_access_key" ]]; then
  116. export AWS_DEFAULT_PROFILE="$profile"
  117. export AWS_PROFILE="$profile"
  118. export AWS_EB_PROFILE="$profile"
  119. export AWS_ACCESS_KEY_ID="$aws_access_key_id"
  120. export AWS_SECRET_ACCESS_KEY="$aws_secret_access_key"
  121. if [[ -n "$aws_session_token" ]]; then
  122. export AWS_SESSION_TOKEN="$aws_session_token"
  123. else
  124. unset AWS_SESSION_TOKEN
  125. fi
  126. echo "Switched to AWS Profile: $profile"
  127. fi
  128. }
  129. function aws_change_access_key() {
  130. if [[ -z "$1" ]]; then
  131. echo "usage: $0 <profile>"
  132. return 1
  133. fi
  134. echo "Insert the credentials when asked."
  135. asp "$1" || return 1
  136. AWS_PAGER="" aws iam create-access-key
  137. AWS_PAGER="" aws configure --profile "$1"
  138. echo "You can now safely delete the old access key running \`aws iam delete-access-key --access-key-id ID\`"
  139. echo "Your current keys are:"
  140. AWS_PAGER="" aws iam list-access-keys
  141. }
  142. function aws_regions() {
  143. if [[ $AWS_DEFAULT_PROFILE || $AWS_PROFILE ]];then
  144. aws ec2 describe-regions |grep RegionName | awk -F ':' '{gsub(/"/, "", $2);gsub(/,/, "", $2);gsub(/ /, "", $2); print $2}'
  145. else
  146. echo "You must specify a AWS profile."
  147. fi
  148. }
  149. function aws_profiles() {
  150. aws --no-cli-pager configure list-profiles 2> /dev/null && return
  151. [[ -r "${AWS_CONFIG_FILE:-$HOME/.aws/config}" ]] || return 1
  152. grep --color=never -Eo '\[.*\]' "${AWS_CONFIG_FILE:-$HOME/.aws/config}" | sed -E 's/^[[:space:]]*\[(profile)?[[:space:]]*([^[:space:]]+)\][[:space:]]*$/\2/g'
  153. }
  154. function _aws_regions() {
  155. reply=($(aws_regions))
  156. }
  157. compctl -K _aws_regions asr
  158. function _aws_profiles() {
  159. reply=($(aws_profiles))
  160. }
  161. compctl -K _aws_profiles asp acp aws_change_access_key
  162. # AWS prompt
  163. function aws_prompt_info() {
  164. local _aws_to_show
  165. if [[ -n $AWS_PROFILE ]];then
  166. _aws_to_show+="${ZSH_THEME_AWS_PROFILE_PREFIX:=<aws:}${AWS_PROFILE}${ZSH_THEME_AWS_PROFILE_SUFFIX:=>}"
  167. fi
  168. if [[ -n $AWS_REGION ]]; then
  169. [[ -n $AWS_PROFILE ]] && _aws_to_show+=" "
  170. _aws_to_show+="${ZSH_THEME_AWS_REGION_PREFIX:=<region:}${region}${ZSH_THEME_AWS_REGION_SUFFIX:=>}"
  171. fi
  172. echo "$_aws_to_show"
  173. }
  174. if [[ "$SHOW_AWS_PROMPT" != false && "$RPROMPT" != *'$(aws_prompt_info)'* ]]; then
  175. RPROMPT='$(aws_prompt_info)'"$RPROMPT"
  176. fi
  177. # Load awscli completions
  178. # AWS CLI v2 comes with its own autocompletion. Check if that is there, otherwise fall back
  179. if command -v aws_completer &> /dev/null; then
  180. autoload -Uz bashcompinit && bashcompinit
  181. complete -C aws_completer aws
  182. else
  183. function _awscli-homebrew-installed() {
  184. # check if Homebrew is installed
  185. (( $+commands[brew] )) || return 1
  186. # speculatively check default brew prefix
  187. if [ -h /usr/local/opt/awscli ]; then
  188. _brew_prefix=/usr/local/opt/awscli
  189. else
  190. # ok, it is not in the default prefix
  191. # this call to brew is expensive (about 400 ms), so at least let's make it only once
  192. _brew_prefix=$(brew --prefix awscli)
  193. fi
  194. }
  195. # get aws_zsh_completer.sh location from $PATH
  196. _aws_zsh_completer_path="$commands[aws_zsh_completer.sh]"
  197. # otherwise check common locations
  198. if [[ -z $_aws_zsh_completer_path ]]; then
  199. # Homebrew
  200. if _awscli-homebrew-installed; then
  201. _aws_zsh_completer_path=$_brew_prefix/libexec/bin/aws_zsh_completer.sh
  202. # Ubuntu
  203. elif [[ -e /usr/share/zsh/vendor-completions/_awscli ]]; then
  204. _aws_zsh_completer_path=/usr/share/zsh/vendor-completions/_awscli
  205. # NixOS
  206. elif [[ -e "${commands[aws]:P:h:h}/share/zsh/site-functions/aws_zsh_completer.sh" ]]; then
  207. _aws_zsh_completer_path="${commands[aws]:P:h:h}/share/zsh/site-functions/aws_zsh_completer.sh"
  208. # RPM
  209. else
  210. _aws_zsh_completer_path=/usr/share/zsh/site-functions/aws_zsh_completer.sh
  211. fi
  212. fi
  213. [[ -r $_aws_zsh_completer_path ]] && source $_aws_zsh_completer_path
  214. unset _aws_zsh_completer_path _brew_prefix
  215. fi