aws.plugin.zsh 9.6 KB

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