PowerShell batch open EC2 Termination Protection

Keywords: snapshot Attribute

My colleague planned to restart an EC2 instance two days ago, but the result was that his hand slipped to Termination, and then EC2 was tragic. Fortunately, there was a Snapshot backup, and the server was successfully restored after 15 minutes.

It can be seen that reboot and terminate are very close, so in order to avoid the tragedy happening again, we need to open the termination protection

If there are only a few EC2, you can click it manually, as shown in the figure

But if there are many, it is more convenient to write scripts

Here's what PowerShell does.

function Scan-EC2(){

    Write-Host "Checking EC2 instance Tags status" -ForegroundColor Yellow

    $all=Get-EC2Instance | select -expand instances

    # confirm EC2 instances were tagged

    $result=@()
    foreach($item in $all){

        $Name=$item.tag | Where-Object {$_.Key -eq 'Name'} | select -ExpandProperty value
        $clinic=$item.tag | Where-Object {$_.Key -eq 'clinic'} | select -ExpandProperty value
        $terminationprotection=Get-EC2InstanceAttribute -InstanceId $item.instanceid -Attribute disableApiTermination | select -ExpandProperty DisableApiTermination
        $sg=$item.securitygroups.groupname
        $item | add-member -NotePropertyName Description -NotePropertyValue $name
        $item | add-member -NotePropertyName Clinic -NotePropertyValue $clinic
        $item | add-member -NotePropertyName sg -NotePropertyValue $sg
        $item | add-member -NotePropertyName TerminationProtection -NotePropertyValue $terminationprotection
        $item = $item | select *
        $result+=$item

    }

    $result | select Description, InstanceId, InstanceType,privateIpaddress, Clinic,@{n='Status';e={$_.state.name}},sg, TerminationProtection 
}

$result=Scan-EC2

foreach($one in $result){
if($one.terminationprotection -eq $false){

    Edit-EC2InstanceAttribute -InstanceId $one.instanceid -DisableApiTermination $true

}

}

$result=Scan-EC2 | Out-GridView

The output results show that they all turn to True successfully

You can schedule tasks on a regular basis so you don't have to worry about accidentally deleting important servers.

Posted by anler on Fri, 03 Apr 2020 14:16:44 -0700