AWS Lambda automation and PowerShell

Keywords: Lambda snapshot AWS Python

I've been watching how to use Lambda and Python for the past two days, but I'm usually more used to using PowerShell to manage various systems. Try using PowerShell in Lambda.

First, you need to install the following three modules on the local computer.

Install PowerShell Core
https://github.com/powershell/powershell

Install the. Net core software development kit (SDK)
https://www.microsoft.com/net/download

Install AWS lambdapscore module
Install-Module AWSLambdaPSCore -Scope CurrentUser

It is installed and executed in the console of PowerShell 6.
New-AWSPowerShellLambda -ScriptName awstag -Template basic

He will automatically create a directory based on the basic template, which uses a blank ps file and a readme file. This blank ps file automatically loads the modules of powershellcore. If we need to add other modules, we need to modify them here. Here is a test script for me. The main function of this script is to check the tags and ensure that EC2, Volume and snapshot have corresponding tags, because I need to display the bills of different clinics through tags every month. In addition, if the snapshot is longer than 60 days, it will be automatically deleted by the way.

# PowerShell script file to be executed as a AWS Lambda function. 
# 
# When executing in Lambda the following variables will be predefined.
#   $LambdaInput - A PSObject that contains the Lambda function input data.
#   $LambdaContext - An Amazon.Lambda.Core.ILambdaContext object that contains information about the currently running Lambda environment.
#
# The last item in the PowerShell pipeline will be returned as the result of the Lambda function.
#
# To include PowerShell modules with your Lambda function, like the AWSPowerShell.NetCore module, add a "#Requires" statement 
# indicating the module and version.

#Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.335.0'}

# Uncomment to send the input event to CloudWatch Logs
# Write-Host (ConvertTo-Json -InputObject $LambdaInput -Compress -Depth 5)

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

$all=Get-EC2Instance | select -expand instances

$return=$all | Where-Object {$_.tag.key -notcontains "Clinic"}

if($return -ne $null){
$username = "test@abc.com" 
$password = "Passwordtest" | ConvertTo-SecureString -asPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
$id=$return.InstanceId

Send-MailMessage -From test@abc.com -to test@abc.com -SmtpServer smtp.office365.com -Port 587 -UseSsl -Subject "EC2 instance Tag" -body "$id" -Credential $credential
exit

}
# 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
    $item | add-member -NotePropertyName Description -NotePropertyValue $name
    $item | add-member -NotePropertyName Clinic -NotePropertyValue $clinic

    $item = $item | select *
    $result+=$item

}

$result | select Description, InstanceId, privateIpaddress, Clinic | Group-Object Clinic

write-host "Updating Volume Tags Status ... " -ForegroundColor Yellow 
#Tag all volumes based on their attached EC2 Clinic Tag

$allvol=Get-EC2Volume | Where-Object {$_.tag.key -notcontains "Clinic"}

foreach($item in $result){
    foreach($item2 in $allvol){

        if ($item2.attachments.instanceid -eq $item.InstanceId){
                $value=$item.Clinic
              New-EC2Tag -Resource $item2.VolumeId -Tag @{Key="Clinic";value=$value} 
           }

        }

}

Write-Host "Updating Snapshot Tags Status..." -ForegroundColor Yellow 
#Tag all snapshots based on the volume Tag
$allvol=Get-EC2Volume 
$filter= New-Object Amazon.EC2.Model.Filter -Property @{Name = "owner-id"; Values ='386115804199' } 
$snapshots=Get-EC2Snapshot -Filter $filter 

$snapshots1= $snapshots | ? {$_.Tag.key -notcontains "Clinic"} 

foreach($i in $snapshots1){
    $volid=$i.VolumeId

    foreach($j in $allvol){

        if($volid -eq $j.Volumeid){

            $value=$j.tag | Where-Object {$_.key -eq 'Clinic'} | select -ExpandProperty value

            $name=$j.Tag | Where-Object {$_.key -eq "Name"} | select -ExpandProperty value

            $snapid=$i.snapshotid
            write-host "--$snapid--"  
            New-EC2Tag -Resource $snapid -Tag @{Key="Clinic";value=$value} 
            New-EC2Tag -Resource $snapid -Tag @{Key="Name";value=$name}

        }
    }

}

write-host "Deleting Snapshots older than over 60 days !" -ForegroundColor Yellow

$date=(get-date).AddDays(-40)

foreach($snapshot in $snapshots){
    $id=$snapshot.snapshotid

    if($snapshot.starttime -lt $date){
        $snapshot
        Remove-EC2Snapshot -SnapshotId $id -Confirm:$false
    }
}

Next, it is executed in the console of PowerShell 6. It will automatically bind the role of iam, compress related modules and execute scripts, and then upload them to the console of Lambda. I write the iam role here casually, allowing access to ec2 and cloudwatch log.

Publish-AWSPowerShellLambda -ScriptPath .\awstag.ps1 -name awstag -iamrole 'ec2fullaccess' -Region ap-southeast-2

Wait a minute, log in to aws and you will see the uploaded function.

This piece of code is not directly visible in Python. It tells you that it is too big to display, but I can call it directly.

Give it a test and it will show success

Go to the corresponding cloudwatch

Done!

Posted by matthewc on Tue, 15 Oct 2019 07:43:45 -0700