0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ローカルのAWS_PROFILEをfzfでいい感じに切り替える

Posted at

前提

  • AWSのPROFILEをaws-vaultで管理していること
  • fzfが使える環境であること

モチベーション

  • 複数のAWSアカウントやロールに頻繁にアクセスする際に、TerminalでPROFILEを切り替えるのが面倒
  • PROFILEをfuzzyに検索して選択したい

実現方法

  • aws-vault list --profiles の結果をfzfに渡して、選択したプロファイルで環境変数を書き換える
  • zsh関数として.zshrcに定義する

コード

AWS IAM Identity CenterでSSOを設定しており、sso_session用のPROFIELも定義されている。sso_session用のPROFIELE名をxxx-ssoという命名規則にし、ssoという文字列を除外している。

function aws-sw() {
  export AWS_PROFILE=$(aws-vault list --profiles | grep -v -E "sso|default" | sort | fzf)
}

番外編

よく使う一連のコマンド群をfzfを使用して、関数化しておくと便利です。

Regionを切り替える関数

function aws-rg-sw() {
  region=$(aws ec2 describe-regions | jq -r '.Regions[].RegionName' | sort | fzf)
  if [ -z "$region" ]; then
    return
  fi
  export AWS_DEFAULT_REGION=$region
}

EC2にSSMで接続する関数

function dive-ec2() {
  instanceId=$(aws ec2 describe-instances | jq -r '.Reservations[].Instances[] | select(.State.Name="running") | [.InstanceId, (.Tags[] | select(.Key == "Name").Value)] | @tsv' | fzf | awk '{print $1}')
  if [ -z "$instanceId" ]; then
    return
  fi
  cmd="aws ssm start-session --target $instanceId"
  echo -e "\e[32m\$$cmd\e[m"
  print -s $cmd
  eval $cmd
}

ECSコンテナに接続する関数

function dive-ecs() {
  cluster=$(aws ecs list-clusters | jq -r ".clusterArns[]" | sed 's/.*\///g' | fzf)
  if [ -z "$cluster" ]; then
    return
  fi
  service=$(aws ecs list-services --cluster $cluster | jq -r ".serviceArns[]" | sed 's/.*\///g' | fzf)
  if [ -z "$service" ]; then
    return
  fi
  task=$(aws ecs list-tasks --cluster $cluster --service-name $service | jq -r ".taskArns[]" | sed 's/.*\///g' | fzf)
  if [ -z "$task" ]; then
    return
  fi
  container=$(aws ecs describe-tasks --cluster $cluster --task $task | jq -r '.tasks[].containers[].name' | fzf)
  if [ -z "$container" ]; then
    return
  fi
  cmd="aws ecs execute-command --cluster $cluster --task $task --container $container --interactive --command bash"
  echo -e "\e[32m\$$cmd\e[m"
  print -s $cmd
  eval $cmd
}

CloudWatchLogsをtailする関数

function aws-logs() {
  logGroupName=$(aws logs list-log-groups | jq -r '.logGroups[].logGroupName' | fzf)
  if [ -z "$logGroupName" ]; then
    return
  fi
  exec_aws_command "aws logs tail --follow $logGroupName"
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?