AWS Lambda 自动化和 PowerShell

这两天我都在看如何使用Lambda和Python,但是平常更习惯使用PowerShell来管理各种系统。试试看如何在Lambda里面使用PowerShell吧。

首先在本地计算机上需要安装下面三个模块。

安装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

安装好了,在Powershell6的控制台 里面执行
New-AWSPowerShellLambda -ScriptName awstag -Template basic

他会自动根据basic的模板创建一个目录,里面用一个空白的ps文件,和一个readme文件。这个空白的ps文件自动加载了powershellcore的模块,如果我们需要添加其他的模块,需要在这里修改。下面是我的一个测试脚本。这个脚本主要的功能是检查tag,确保EC2,Volume和Snapshot都有对应的tag,因为每个月我需要通过tag来显示不同诊所的账单。另外如果snapshot如果超过60天,顺便也自动给我删除了。

# 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

[email protected]()
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
    }
}

接下来在Powershell6 的控制台执行,他会自动绑定iam的role,压缩相关的模块和执行脚本,然后上传到Lambda的控制台。这里的iam role我是随便写的,允许访问ec2和 cloudwatch log。

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

等个1分钟,登录aws 就可以看见上传的函数了。

代码这一块不像Python能直接看见,直接告诉你太大 没法显示 但是我可以直接调用

测试一下试试,显示成功

去对应的cloudwatch 看看

Done!

原文地址:https://blog.51cto.com/beanxyz/2442543

时间: 2024-08-29 16:08:15

AWS Lambda 自动化和 PowerShell的相关文章

AWS Lambda 自动化和 Python - 自动创建S3 Bucket lifecycle

最近经常需要创建一些S3 Bucket用于备份.每个新建的Bucket都应该配置lifecycle,自动删除旧的数据,以便节约空间和开支. 豆子写了一个简单的Lambda函数来自动实现.每次当我们创建一个Bucket的时候,他会调用对应的API,Cloudtrail监测到这个事件后,会发送给Cloudwatch, 然后Cloudwatch会自动调用我的函数来创建lifecycle policy. 下面是简单的截图说明. 创建一个新的Cloudwatch Rule 对应的Lambda函数 他默认的

什么是AWS Lambda?——事件驱动的函数执行环境

AWS CTO Werner Vogels在AWS re:Invent 2014大会的第二场主题演讲上公布了两个新服务和一系列新的实例,两个新服务都相当令人瞩目:第一个宣布的新服务是Amazon EC2 Container Service,跟Docker紧密联合的管理服务,令人兴奋,不过不是本篇报道的重点. 本篇报道主要想向大家介绍一下今天宣布的第二个服务:AWS Lambda. 什么是AWS Lambda? 根据Jeff Barr在博客上的描述,Lambda是一个"可简单创建Lambda函数.

[AWS Lambda] Scheduling Events with AWS Lambda (a.k.a. Lambda cron jobs)

Learn how to create AWS Lambda functions that execute on a scheduled interval, much like a cron job would. In this lesson we will create a Lambda function that checks for a string of text on a website to verify the website is up and operational. The

[AWS Lambda] Use AWS Lambda and API Gateway to return data

In this lesson, you will learn how to create a simple AWS Lambda function to submit a name via an API Gateway and return a resume for that person. At the end of the lesson, you will be able to create a Lambda function, and API Gateway, and understand

AWS Lambda

AWS Lambda 知识点总结 参考资料:Amazon 占位符

Automated EBS Snapshots using AWS Lambda & CloudWatch

Overview In this post, we'll cover how to automate EBS snapshots for your AWS infrastructure using Lambda and CloudWatch.   We'll build a solution that creates nightly snapshots for volumes attached to EC2 instances and deletes any snapshots older th

重新开始继续准备AWS Dev认证考试:AWS Lambda 环境变量

利用 Lambda 函数的环境变量,您可以将设置动态传递到函数代码和库,而无需对代码进行任何更改.环境变量是您使用 AWS Lambda 控制台.AWS Lambda CLI 或 AWS Lambda 开发工具包作为函数配置的一部分创建并修改的密钥值对.AWS Lambda 随后会使用相应语言所支持的标准 API(如适用于 Node.js 函数的 process.env 将这些密钥值对提供给您的 Lambda 函数代码. 您可以使用环境变量帮助库了解以下信息:安装文件的目录.存储输出的位置.存储

访问 AWS Lambda 的 Amazon CloudWatch 日志

AWS Lambda 会自动替您监控 Lambda 函数,并通过 Amazon CloudWatch 报告各项指标.为帮助您诊断函数中的问题,Lambda 会记录您的函数处理的所有请求,并通过 Amazon CloudWatch Logs 自动存储您的代码生成的日志. 您可以在代码中插入日志记录语句来帮助验证代码是否按预期运行.Lambda 自动与 CloudWatch Logs 集成,并将您的代码的所有日志推送到与 Lambda 函数关联的 CloudWatch Logs 组(即名为 /aws

AWS Lambda 别名简介

您可以为 Lambda 函数创建一个或多个别名.AWS Lambda 别名类似于指向特定 Lambda 函数版本的指针. AWS Lambda 别名支持以下使用案例: 根据需要更轻松地支持 Lambda 函数的新版本的提升和回滚 – 在最初创建 Lambda 函数($LATEST 版本)后,可以先发布其版本 1.通过创建名为 PROD 的指向版本 1 的别名,现在可以使用 PROD 别名调用 Lambda 函数的版本 1. 现在您可以使用所有改进来更新代码($LATEST 版本),然后发布另一个