tech.guitarrapc.cóm

Technical updates

AWS Tools for Windows PowerShell で EC2インスタンスの Terminate Protection を操作する

AWS EC2 使ってますか? Management Console で使っている? そうですか..... 頑張ってください! 私は PowerShell で楽をします。 今回は、 誤って Terminate したくない人の見方 「Terminate Protection」 を EC2インスタンスに対して有効化する方法です。

EC2 Instance の Terminate Protection

Terminate Protection は、名のごとく、 Terminate を実行できないようにしてくれます。 この設定が有効になったEC2 Instance は、 Terminate ボタンがグレイアウトして無効になり、 Terminate Protection を無効にしないと Terminate できないようになります。 特に AWS Management Console は、マウス操作のため、 Stop や Start, Reboot の近くに Terminate があるのは恐いものです。

PowerShell で Terminate Protectionを操作する

PowerShell での AWS操作が初めての方は、前回の記事を参照してください。
AWS Tools for Windows PowerShell のススメ
Terminate Protection は、 EC2 の属性 (Attribute) として設定されています。 ということで、使うコマンドレットはこれです。
Get-EC2InstanceAttribute
Edit-EC2InstanceAttribute
EC2 Instance の状態を取得するには、 Get-EC2InstanceAttribute Cmdlet を利用します。 Terminate Protection 状態を取得するならこうです。
Get-EC2InstanceAttribute -InstanceId i-xxxxxxx -Attribute disableApiTermination
Terminate Protection は、 disableApiTermination という名称なんですね。 有効にする場合はこのようにします。
Edit-EC2InstanceAttribute -InstanceId i-xxxxxxxx -Attribute disableApiTermination -Value $true
無効にする場合はこうです。
Edit-EC2InstanceAttribute -InstanceId i-xxxxxxxx -Attribute disableApiTermination -Value $false
指定したIPのInstanceを取得したい? それならこうです。
$IpAddress = "10.0.100.10"
(Get-EC2Instance).RunningInstance | where PrivateIpAddress -eq $IpAddress | Get-EC2InstanceAttribute -Attribute disableApiTermination
設定も簡単ですね。
$IpAddress = "10.0.100.10"
(Get-EC2Instance).RunningInstance | where PrivateIpAddress -eq $IpAddress | Edit-EC2InstanceAttribute -Attribute disableApiTermination -Value $false

まとめ

PowerShell は基本として Pipe Orientated です。 Pipe が使えない利用なら、別に PowerShell ではなくて .NET の方を使えばいいのです。 より効率書ける/利用できる場面に適したものを使えるといいですね。