この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
はじめに
こんにちは、あべいかです。 AWS Tools for Windows PowerShellを使ったスクリプトを作成しましたので、共有します。 本スクリプトは、指定したタグを持つEC2インスタンスをstartします。
スクリプトの使い方
EC2インスタンスへのタグ付け
startしたいEC2インスタンスには、Key="Env"を設定します。 Valueは任意の値を設定します。以下の例では、Value="Test"としました。
実行方法
Envタグの値を引数とし、実行します。 「Key="Env",Value="Test"」のインスタンスをstartする場合、以下のように実行します。
start-by-tags.ps1 Test
スクリプト(start-by-tags.ps1)
各インスタンスのタグを確認し、Key:Envが指定した値かつstopped状態の場合に「Start-EC2Instance」を実行します。 タグの比較に「-ceq」を使う事で、大文字小文字を区別します。
## 変数定義
# start対象のキー
$StartKey = "Env"
# start対象のバリュー
$StartValue = $args[0]
## 処理開始
# EC2インスタンス情報を取得
$result = Get-EC2Instance
# EC2インスタンスの数だけループする
for($i=0; $i -lt $result.Instances.Count; $i++)
{
# 各インスタンスのタグの数だけループする
for($j=0; $j -lt $result.Instances[$i].tags.Count; $j++)
{
# タグのKeyとValueを確認する
if(($result.Instances[$i].tags.Key[$j] -ceq $StartKey) -and ($result.Instances[$i].tags.Value[$j] -ceq $StartValue))
{
# stopped状態であれば、startする。
if($result.Instances[$i].State.Name -ceq "stopped"){
# start処理
Start-EC2Instance -Instance $result.Instances[$i].InstanceId
break;
}
}
}
}
スクリプト(stop-by-tags.ps1)
せっかくなので、stop用のスクリプトも作成しました。 各インスタンスのタグを確認し、Key:Envが指定した値かつrunning状態の場合に「Stop-EC2Instance」を実行します。 実行方法は、start-by-tags.ps1と同様です。
## 変数定義
# stop対象のキー
$StopKey = "Env"
# stop対象のバリュー
$StopValue = $args[0]
## 処理開始
# EC2インスタンス情報を取得
$result = Get-EC2Instance
# EC2インスタンスの数だけループする
for($i=0; $i -lt $result.Instances.Count; $i++)
{
# 各インスタンスのタグの数だけループする
for($j=0; $j -lt $result.Instances[$i].tags.Count; $j++)
{
# タグのKeyとValueを確認する
if(($result.Instances[$i].tags.Key[$j] -ceq $StopKey) -and ($result.Instances[$i].tags.Value[$j] -ceq $StopValue))
{
# running状態であれば、stopする。
if($result.Instances[$i].State.Name -ceq "running"){
# stop処理
Stop-EC2Instance -Instance $result.Instances[$i].InstanceId
break;
}
}
}
}
さいごに
AWS CLIと比べると、AWS Tools for Windows PowerShellの情報量は少ないようです。 今後もスクリプトを共有していきますので、ご期待下さい。