LoginSignup
0

More than 5 years have passed since last update.

Amazon EC2で停止中のインスタンスをpecoで絞り込んで起動する

Last updated at Posted at 2016-07-01

Amazon EC2で停止中(stopped)のインスタンスを起動するときにインスタンスIDの取得が面倒くさかったので、Nameタグの値を使ってpecoで絞りこめるようにした。

ワンライナー

$ aws ec2 describe-instances \
    --filters 'Name=instance-state-name,Values=stopped' \
    --query 'Reservations[].Instances[].{InstanceId:InstanceId,Name:Tags[?Key==`Name`].Value|[0]}' \
    --output text \
  | peco \
  | cut -f1 \
  | xargs -n 1 -I{} aws ec2 start-instances --instance-ids {}

見やすさのために改行した。まあ、ワンライナーで都度実行するんじゃなくて、適当な関数にすればいいと思う。

Zsh用設定

キーバインドはお好みで。

~/.zshrc
function ec2_start_instance(){
  local target_instance=$(
    aws ec2 describe-instances \
      --filters 'Name=instance-state-name,Values=stopped' \
      --query 'Reservations[].Instances[].{InstanceId:InstanceId,Name:Tags[?Key==`Name`].Value|[0]}' \
      --output text \
    | peco --query "$LBUFFER" \
    | cut -f1 )
  if [ -n "${target_instance}" ];then
    BUFFER="aws ec2 start-instances --instance-ids ${target_instance}"
    zle accept-line
  fi
  zle clear-screen
}

zle -N ec2_start_instance
bindkey '^[' ec2_start_instance

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