Konstantin Emelyanov - Fotolia

Get started Bring yourself up to speed with our introductory content.

Follow this step-by-step guide to use AWS Lambda with PowerShell

Explore the process needed to prepare, package and publish Lambda functions with PowerShell modules. Use the examples in each step to model your own functions.

AWS Lambda functions enable you to run code without worrying about what server it runs on -- even if you work in a Microsoft shop.

This serverless, event-driven compute service manages back-end resources with zero administration, so developers can focus on their applications. In this tutorial, you will learn how to create an AWS Lambda function using PowerShell v6 running on .NET Core.

Set up development environment and AWS credentials

First, you need to set up the development environment and install PowerShell Core v6, the .NET Core SDK and the AWSLambdaPSCore module. Make sure to import the PowerShell modules using the following PowerShell commands:

Install-Module AWSLambdaPSCore, AWSPowerShell -Scope CurrentUser -Verbose -Force -Confirm:$false
Import-Module AWSLambdaPSCore, AWSPowerShell

Editor's note: For more best practices and step-by-step guidance to install PowerShell Core, the .NET Core SDK and the AWSLambdaPSCore module, check out this video tutorial.

Once the installation is complete, follow these steps to create a user in AWS Management Console that has programmatic access:

  1. Launch the Identity and Access Management (IAM) console in AWS.
  2. Click Users from the navigation menu.
  3. Click Add User in the pop-up window.
  4. In the new window, provide a user name, choose Programmatic Access for access type and click next.
  5. To set the permissions, choose Attach Existing Policies Directly. In the policy filter, type AmazonEC2FullAccess. You can choose any permission level, but for the sake of this example, we'll click the AmazonEC2FullAccess box and then next .
  6. Review the user and permission levels, and click Create User.
  7. The next page will show your access ID and secret key. But these are only available once, so it would be wise to download and save them safely in a secure location.

After you obtain your credentials, configure them in the PowerShell development environment before you manage any Amazon cloud services. Use the PowerShell cmdlet Initialize-AWSDefaultConfigurations and pass your access ID and secret key as shown below:

$AccessKey = 'YOUR ACCESS KEY'
$SecretKey = 'YOUR SECRET KEY'
$Region ='us-east-1'

Initialize-AWSDefaultConfiguration -AccessKey $accessKey -SecretKey $secretKey -Region $Region

Create an AWS Lambda function with PowerShell

For the purposes of this tutorial, we'll create an AWS Lambda function that can provision EC2 instances as determined by user inputs and requirements. We'll begin by creating our first AWS Lambda function using a basic template and name it LaunchEC2:

New-AWSPowerShellLambda -ScriptName LaunchEC2 -Template Basic

This will scaffold a directory structure on the local system to create your AWS Lambda function PowerShell script file.

PowerShell script file

When you open this file, find the PowerShell #Requires statement, flagged below. Use the statement to define what you want packaged within your AWS Lambda function. This makes it easy for other developers to understand the module dependencies of the function. It also identifies the modules that will be packaged with the Lambda function.

#Requires -Modules @{ModuleName='AWSPowerShell.NetCore';ModuleVersion='3.3.283.0'}
PowerShell #Requires statement

When we invoke this Lambda function later, it will automatically create a $LambdaInput variable. We can pass a custom input to the Lambda function through this variable, which will store EC2 launch information, such as the number of instances, image ID and region.

We will have to add another PowerShell cmdlet -- New-EC2Instance -- to handle the input-variable information needed to provision VMs in AWS based on user inputs:

New-EC2Instance -ImageId $LambdaInput.ImageId -MaxCount $LambdaInput.Count -Region $LambdaInput.Region -InstanceType $LambdaInput.InstanceType

Once you've input data in a Lambda function, the next step is to get the function to return data post-execution. This is important in event-driven application architectures. Luckily, a Lambda function automatically returns the last added object to its caller. It does so by converting objects to JSON using the ConvertTo-Json PowerShell cmdlet.

However, those strings will be returned without any conversions. To address this, add another line to the end of the Lambda function so it returns a string to the caller that includes details of function execution. This will handle input data, core functionality and data returned by your first AWS Lambda function.

"{0} EC2 Instances of type:'{1}' launched with Amazon Machine Image:'{2}'" -f $LambdaInput.Count, $LambdaInput.InstanceType, $LambdaInput.ImageId

Publish your PowerShell Lambda function package to AWS

After we've prepared our Lambda function locally, we can publish it to AWS using the PowerShell cmdlet Publish-AWSPowerShellLambda. To do so, we'll pass the name of the function and path to the function script and assign it to the right IAM role for execution on AWS.

$Parameters = @{
    Name = 'LaunchEC2'
    ScriptPath = '.\LaunchEC2\LaunchEC2.ps1'
    IAMRoleArn = 'arn:aws:iam::527896940414:role/service-role/MyLambdaRole'
}


Publish-AWSPowerShellLambda @Parameters

As shown below, it will take a few minutes to package the Lambda function script and its dependencies and then publish it to AWS.

AWS Lambda function PowerShell script packaged with dependencies

List the AWS Lambda function using PowerShell

Once you've deployed the Lambda function successfully, you can retrieve the list of all currently deployed functions from AWS Lambda using the cmdlet Get-LMFunctionList. This can be useful to validate whether your Lambda functions are properly published to AWS with desired properties -- permissions, timeouts, etc. It can also be useful to view all the published and unpublished versions of the Lambda function.

Get-LMFunctionlist PowerShell cmdlet

Invoke the AWS Lambda function

After your Lambda function is deployed, set it to process input variables and provision VMs. Use the Invoke-LMFunction cmdlet to call the Lambda function as a JSON payload from PowerShell.

$InputData = @{
    ImageId = 'ami-0080e4c5bc078760e'
    Count = 2
    InstanceType = 't2.micro'
} | ConvertTo-Json
 
$Result = Invoke-LMFunction -FunctionName LaunchEC2 -Payload $InputData

This AWS Lambda function post-execution will return a string response that can be obtained from the Payload property of the returned object. However, this response will have to be read using the .NET class StreamReader, as demonstrated in the following code sample:

$StreamReader = [System.IO.StreamReader]::new($Result.Payload)
$StreamReader.ReadToEnd()
Post execution AWS Lambda function in PowerShell

Validate the Lambda function execution

You can also validate the execution of a function by filtering out the Lambda logs that are automatically collected by Amazon CloudWatch. Use the Get-CWLFilteredLogEvent cmdlet, which will return a timestamp and messages logged after the invocation of the Lambda function:

Get-CWLFilteredLogEvent -LogGroupName /aws/lambda/LaunchEC2 | Foreach-Object Events
Get-CWLFilteredLogEvent PowerShell cmdlet
This was last published in May 2019

Dig Deeper on AWS Lambda

Join the conversation

1 comment

Send me notifications when other members comment.

Please create a username to comment.

How do you use PowerShell to provision AWS resources?
Cancel

-ADS BY GOOGLE

SearchCloudApplications

TheServerSide.com

SearchSoftwareQuality

SearchCloudComputing

Close