aws.plugin.zsh 9.5 KB

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