aws.plugin.zsh 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. local profile="$1"
  135. # Get current access key
  136. local original_aws_access_key_id="$(aws configure get aws_access_key_id --profile $profile)"
  137. asp "$profile" || return 1
  138. echo "Generating a new access key pair for you now."
  139. if aws --no-cli-pager iam create-access-key; then
  140. echo "Insert the newly generated credentials when asked."
  141. aws --no-cli-pager configure --profile $profile
  142. else
  143. echo "Current access keys:"
  144. aws --no-cli-pager iam list-access-keys
  145. echo "Profile \"${profile}\" is currently using the $original_aws_access_key_id key. You can delete an old access key by running \`aws --profile $profile iam delete-access-key --access-key-id AccessKeyId\`"
  146. return 1
  147. fi
  148. read -q "yn?Would you like to disable your previous access key (${original_aws_access_key_id}) now? "
  149. case $yn in
  150. [Yy]*)
  151. echo -n "\nDisabling access key ${original_aws_access_key_id}..."
  152. if aws --no-cli-pager iam update-access-key --access-key-id ${original_aws_access_key_id} --status Inactive; then
  153. echo "done."
  154. else
  155. echo "\nFailed to disable ${original_aws_access_key_id} key."
  156. fi
  157. ;;
  158. *)
  159. echo ""
  160. ;;
  161. esac
  162. echo "You can now safely delete the old access key by running \`aws --profile $profile iam delete-access-key --access-key-id ${original_aws_access_key_id}\`"
  163. echo "Your current keys are:"
  164. aws --no-cli-pager iam list-access-keys
  165. }
  166. function aws_regions() {
  167. if [[ $AWS_DEFAULT_PROFILE || $AWS_PROFILE ]];then
  168. aws ec2 describe-regions |grep RegionName | awk -F ':' '{gsub(/"/, "", $2);gsub(/,/, "", $2);gsub(/ /, "", $2); print $2}'
  169. else
  170. echo "You must specify a AWS profile."
  171. fi
  172. }
  173. function aws_profiles() {
  174. aws --no-cli-pager configure list-profiles 2> /dev/null && return
  175. [[ -r "${AWS_CONFIG_FILE:-$HOME/.aws/config}" ]] || return 1
  176. grep --color=never -Eo '\[.*\]' "${AWS_CONFIG_FILE:-$HOME/.aws/config}" | sed -E 's/^[[:space:]]*\[(profile)?[[:space:]]*([^[:space:]]+)\][[:space:]]*$/\2/g'
  177. }
  178. function _aws_regions() {
  179. reply=($(aws_regions))
  180. }
  181. compctl -K _aws_regions asr
  182. function _aws_profiles() {
  183. reply=($(aws_profiles))
  184. }
  185. compctl -K _aws_profiles asp acp aws_change_access_key
  186. # AWS prompt
  187. function aws_prompt_info() {
  188. local _aws_to_show
  189. local region="${AWS_REGION:-${AWS_DEFAULT_REGION:-$AWS_PROFILE_REGION}}"
  190. if [[ -n "$AWS_PROFILE" ]];then
  191. _aws_to_show+="${ZSH_THEME_AWS_PROFILE_PREFIX="<aws:"}${AWS_PROFILE}${ZSH_THEME_AWS_PROFILE_SUFFIX=">"}"
  192. fi
  193. if [[ -n "$region" ]]; then
  194. [[ -n "$_aws_to_show" ]] && _aws_to_show+="${ZSH_THEME_AWS_DIVIDER=" "}"
  195. _aws_to_show+="${ZSH_THEME_AWS_REGION_PREFIX="<region:"}${region}${ZSH_THEME_AWS_REGION_SUFFIX=">"}"
  196. fi
  197. echo "$_aws_to_show"
  198. }
  199. if [[ "$SHOW_AWS_PROMPT" != false && "$RPROMPT" != *'$(aws_prompt_info)'* ]]; then
  200. RPROMPT='$(aws_prompt_info)'"$RPROMPT"
  201. fi
  202. # Load awscli completions
  203. # AWS CLI v2 comes with its own autocompletion. Check if that is there, otherwise fall back
  204. if command -v aws_completer &> /dev/null; then
  205. autoload -Uz bashcompinit && bashcompinit
  206. complete -C aws_completer aws
  207. else
  208. function _awscli-homebrew-installed() {
  209. # check if Homebrew is installed
  210. (( $+commands[brew] )) || return 1
  211. # speculatively check default brew prefix
  212. if [ -h /usr/local/opt/awscli ]; then
  213. _brew_prefix=/usr/local/opt/awscli
  214. else
  215. # ok, it is not in the default prefix
  216. # this call to brew is expensive (about 400 ms), so at least let's make it only once
  217. _brew_prefix=$(brew --prefix awscli)
  218. fi
  219. }
  220. # get aws_zsh_completer.sh location from $PATH
  221. _aws_zsh_completer_path="$commands[aws_zsh_completer.sh]"
  222. # otherwise check common locations
  223. if [[ -z $_aws_zsh_completer_path ]]; then
  224. # Homebrew
  225. if _awscli-homebrew-installed; then
  226. _aws_zsh_completer_path=$_brew_prefix/libexec/bin/aws_zsh_completer.sh
  227. # Ubuntu
  228. elif [[ -e /usr/share/zsh/vendor-completions/_awscli ]]; then
  229. _aws_zsh_completer_path=/usr/share/zsh/vendor-completions/_awscli
  230. # NixOS
  231. elif [[ -e "${commands[aws]:P:h:h}/share/zsh/site-functions/aws_zsh_completer.sh" ]]; then
  232. _aws_zsh_completer_path="${commands[aws]:P:h:h}/share/zsh/site-functions/aws_zsh_completer.sh"
  233. # RPM
  234. else
  235. _aws_zsh_completer_path=/usr/share/zsh/site-functions/aws_zsh_completer.sh
  236. fi
  237. fi
  238. [[ -r $_aws_zsh_completer_path ]] && source $_aws_zsh_completer_path
  239. unset _aws_zsh_completer_path _brew_prefix
  240. fi