Parent directory

aws.plugin.zsh

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