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?

EC2の終了保護を忘れていないか確認するスクリプト

0
Posted at

EC2の削除保護忘れがないかを確認するスクリプト

#!/bin/bash

echo "=== 終了保護なしのEC2インスタンス チェック中 ==="
echo ""

# 一時的に結果を保存する配列
unprotected_instances=()

aws ec2 describe-instances \
  --query 'Reservations[*].Instances[*].[InstanceId,State.Name,InstanceType,Tags[?Key==`Name`].Value|[0]]' \
  --output text | \
while read id state type name; do
  protection=$(aws ec2 describe-instance-attribute \
    --instance-id $id \
    --attribute disableApiTermination \
    --query 'DisableApiTermination.Value' \
    --output text 2>/dev/null)

  if [ "$protection" = "False" ]; then
    echo "$id|$state|$type|${name:-N/A}"
  fi
done > /tmp/unprotected_instances.txt

# 結果表示
if [ -s /tmp/unprotected_instances.txt ]; then
  echo "=== 検出結果 ==="
  echo ""
  printf "%-22s %-15s %-20s %s\n" "Instance ID" "State" "Instance Type" "Name"
  echo "--------------------------------------------------------------------------------"

  while IFS='|' read id state type name; do
    printf "%-22s %-15s %-20s %s\n" "$id" "$state" "$type" "$name"
  done < /tmp/unprotected_instances.txt

  echo ""
  echo "=== 終了保護なしのインスタンス一覧 ==="
  awk -F'|' '{print $1}' /tmp/unprotected_instances.txt
  echo ""
  count=$(wc -l < /tmp/unprotected_instances.txt)
  echo "合計: ${count}件"
else
  echo "終了保護なしのインスタンスは見つかりませんでした。"
fi

# 一時ファイル削除
rm -f /tmp/unprotected_instances.txt
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?