はじめに
AWSのコンソールでも、複数のEC2をチェックして起動停止を行うことができます。
ですが数十台のEC2から定期的に特定の数台を操作する場合、チェックボックスの選択ミスのリスクが生じます。タグなどでフィルターできればよいのですが、綺麗にタグ付けされていないこともあるかと思います。
そのため起動するVMを変数で定義して、コマンドで行う方法を記事にしました。
以前AzureVMのを作成しており、そのEC2版です。
概要
- 複数のEC2を一度に起動、停止できるコマンド
- CloudShellで実行する想定
- 操作と、対象のインスタンスID群を引数にして、関数化した処理を実行
コマンド
まずは操作を変数に代入します。
# --- 1. 操作の定義 ---
# 実行するアクションを指定します ("start", "stop", または "GetVmInfo")
GLOBAL_ACTION="GetVmInfo"
GLOBAL_ACTION="start"
GLOBAL_ACTION="stop"
次に実行する関数を定義します。
# --- 2. 関数の定義 ---
# ActionExecutor 関数
# 引数: $1=アクション, $@=インスタンスIDリスト (配列として展開)
function ActionExecutor {
local ACTION="$1"
# 配列全体を受け取るために shift を使用
shift # 最初の引数 ($1, ACTION) を削除し、残りの引数を $1, $2, ... に詰める
local INSTANCE_IDS="$@" # 残りのすべての引数をスペース区切りの文字列として格納
local COUNT=$# # 残っている引数の数(インスタンス数)をカウント
echo "--- ${COUNT} 台のEC2に対して ${ACTION} を実行中 ---"
case "$ACTION" in
"start")
aws ec2 start-instances \
--instance-ids $INSTANCE_IDS
;;
"stop")
aws ec2 stop-instances \
--instance-ids $INSTANCE_IDS
;;
"GetVmInfo")
aws ec2 describe-instances \
--instance-ids $INSTANCE_IDS \
--query "Reservations[].Instances[].{Name:Tags[?Key=='Name']|[0].Value, InstanceId:InstanceId, State:State.Name, Type:InstanceType}" \
--output table
;;
*)
echo "エラー: 無効なアクションが指定されました: $ACTION" >&2
return 1
;;
esac
if [ $? -ne 0 ]; then
echo "警告: AWS CLIの操作中にエラーが発生しました。" >&2
return 1
fi
echo "操作 (${ACTION}) の要求を送信しました。"
return 0
}
そして実行するEC2のインスタンスIDを定義して、関数の引数に指定して実行します。
# 操作対象のEC2を配列として定義
VM_IDS_ARRAY=(
"i-xxxxxxxxxxxxxxxxx"
"i-yyyyyyyyyyyyyyyyy"
)
# 実行。ActionExecutor の後に配列を展開して渡す (${VM_IDS_ARRAY[@]})
ActionExecutor "$GLOBAL_ACTION" "${VM_IDS_ARRAY[@]}"
起動時は以下のようになります。
~ $ ActionExecutor "$GLOBAL_ACTION" "${VM_IDS_ARRAY[@]}"
--- 2 台のEC2に対して start を実行中 ---
{
"StartingInstances": [
{
"InstanceId": "i-xxxxxxxxxxxxxxxxx",
"CurrentState": {
"Code": 0,
"Name": "pending"
},
"PreviousState": {
"Code": 80,
"Name": "stopped"
}
},
{
"InstanceId": "i-yyyyyyyyyyyyyyyyy",
"CurrentState": {
"Code": 0,
"Name": "pending"
},
"PreviousState": {
"Code": 80,
"Name": "stopped"
}
}
]
}
操作 (start) の要求を送信しました
EC2の情報は以下のような情報を出しています。
~ $ ActionExecutor "$GLOBAL_ACTION" "${VM_IDS_ARRAY[@]}"
--- 2 台のEC2に対して GetVmInfo を実行中 ---
----------------------------------------------------------------
| DescribeInstances |
+----------------------+-----------------+----------+----------+
| InstanceId | Name | State | Type |
+----------------------+-----------------+----------+----------+
| i-xxxxxxxxxxxxxxxxx | temp202511_01 | running | t2.nano |
| i-yyyyyyyyyyyyyyyyy | temp202511_02 | running | t2.nano |
+----------------------+-----------------+----------+----------+
操作 (GetVmInfo) の要求を送信しました。
おわりに
今回は複数のEC2を起動停止するコマンドを記事にしました。
綺麗に整理できていない環境ではGUIでの操作は危険のため、IDで指定する方法をコマンドを作ってみました。
この記事がどなたかのお役に立ちましたら幸いです。