AWS Lambda automation and PowerShell

These two days I have been watching how to use Lambda and Python, but usually more used to manage systems using PowerShell. How to use PowerShell to try it in Lambda inside.

First installed on the local computer requires the following three modules.

安装PowerShell Core
https://github.com/powershell/powershell

安装 the .NET Core Software Development Kit (SDK)
https://www.microsoft.com/net/download

安装 AWSLambdaPSCore module
Install-Module AWSLambdaPSCore -Scope CurrentUser

Installed, executed in Powershell6 console inside the
New-AWSPowerShellLambda -ScriptName awstag -Template basic

He will automatically create a table of contents based on basic template, which ps with a blank document, and a readme file. The blank ps files are automatically loaded powershellcore modules, if we need to add additional modules need to be modified here. Here is one of my test script. The main function is to check the script tag, make sure EC2, Volume Snapshot, and has a corresponding tag, because every month I need to display different clinics bill by tag. Also, if the snapshot if more than 60 days, by the way gave me automatically deleted.

# 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 = "[email protected]" 
$password = "Passwordtest" | ConvertTo-SecureString -asPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
$id=$return.InstanceId

Send-MailMessage -From [email protected] -to [email protected] -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 Console Powershell6 in, he will be automatically bound role iam compression related modules and execute scripts, and then uploaded to the Lambda console. Here iam role I just write, allowing access ec2 and cloudwatch log.

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

And so on a one minute, log aws you can see the upload function.

AWS Lambda automation and PowerShell

Unlike Python code for this one can directly see, tell you too much but I can not show a direct call

AWS Lambda automation and PowerShell

Test try, shows success

AWS Lambda automation and PowerShell

Go and see the corresponding cloudwatch

AWS Lambda automation and PowerShell

Done!

Guess you like

Origin blog.51cto.com/beanxyz/2442543