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