diff --git a/.github/workflows/execute-release.yml b/.github/workflows/execute-release.yml index d191dc3b1..9ee52ac80 100644 --- a/.github/workflows/execute-release.yml +++ b/.github/workflows/execute-release.yml @@ -35,7 +35,7 @@ concurrency: env: # The CodePipelines to start (space-separated). The target account is the one the # assumed role lives in; the role must allow StartPipelineExecution on all of them. - PIPELINE_NAMES: "aws-lambda-dotnet aws-lambda-dotnet-powershell aws-lambda-testtool" + PIPELINE_NAMES: "aws-lambda-dotnet aws-lambda-dotnet-powershell aws-lambda-testtool aws-lambda-dotnet-lambdapsruntime" AWS_REGION: us-west-2 INPUT_OVERRIDE_VERSION: ${{ github.event.inputs.OVERRIDE_VERSION }} diff --git a/CHANGELOG.md b/CHANGELOG.md index a97288f0f..6d6eb7e1d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +### AWS.ToolExtras.LambdaPSRuntime PowerShell Module (1.0.0) +* Initial release. Scaffolds, builds, deploys and invokes PowerShell Lambda functions on a custom runtime, as a Layer, a self-contained .zip, a container image or a Lambda customer-managed runtime. + ## Release 2026-11-19 ### Amazon.Lambda.Templates (8.1.3) diff --git a/PowerShell/CustomRuntime/.gitattributes b/PowerShell/CustomRuntime/.gitattributes new file mode 100644 index 000000000..4f932d5d5 --- /dev/null +++ b/PowerShell/CustomRuntime/.gitattributes @@ -0,0 +1,5 @@ +# Everything under Templates/ is copied into a Linux Lambda runtime or image. The bootstraps are +# executed directly by the kernel: with CRLF line endings the shebang reads '/bin/sh\r' and the runtime +# fails to start with "bad interpreter". Force LF on checkout regardless of core.autocrlf, so a Windows +# clone scaffolds working projects. +src/AWS.ToolExtras.LambdaPSRuntime/Templates/** text eol=lf diff --git a/PowerShell/CustomRuntime/.gitignore b/PowerShell/CustomRuntime/.gitignore new file mode 100644 index 000000000..192bfb509 --- /dev/null +++ b/PowerShell/CustomRuntime/.gitignore @@ -0,0 +1,15 @@ +# PowerShell / .NET build and test artifacts +bin/ +obj/ +*.zip +# Built by build.ps1 -Task Library +src/AWS.ToolExtras.LambdaPSRuntime/lib/ +coverage.xml +testResults*.xml +pester*.xml + +# Editor / OS +.vs/ +.vscode/ +*.user +.DS_Store diff --git a/PowerShell/CustomRuntime/PSScriptAnalyzerSettings.Relaxed.psd1 b/PowerShell/CustomRuntime/PSScriptAnalyzerSettings.Relaxed.psd1 new file mode 100644 index 000000000..c5bc0df9a --- /dev/null +++ b/PowerShell/CustomRuntime/PSScriptAnalyzerSettings.Relaxed.psd1 @@ -0,0 +1,34 @@ +# PSScriptAnalyzer contract for Tests/ and Templates/ -- code that is NOT shipping cmdlet source and +# is legitimately written to different rules. `build.ps1 -Task Lint` reports findings from this scope +# but does not fail on them (it still fails on Error and ParseError severity). +# +# Each exclusion below is excluded because the pattern it flags is CORRECT in these directories. None +# of these rules is excluded for the module source, which is linted with the strict +# PSScriptAnalyzerSettings.psd1 instead. +@{ + IncludeDefaultRules = $true + + # ParseError is listed so a file that does not parse is reported: it yields only ParseError records. + Severity = @( + 'ParseError' + 'Error' + 'Warning' + 'Information' + ) + + ExcludeRules = @( + # Templates/: the runtime (runtime.ps1 and the runtime interface client modules) logs to the + # console on purpose. Lambda captures stdout/stderr into CloudWatch Logs, and Write-Host is how + # the runtime reports progress before any structured logging exists. (All in Templates/. The + # cmdlet source has none, and the strict settings keep it that way.) + 'PSAvoidUsingWriteHost' + + # Tests/: many tests declare a stub such as `function New-LMCRuntime { param($Name, $Region, ...) }` + # purely to give Pester a command with the right parameter names to mock. The parameters are + # unused BY DESIGN -- the stub body is empty and the mock replaces it. (All in Tests/.) + 'PSReviewUnusedParameter' + + # Tests/ and Templates/: plural nouns in helper names that are not exported cmdlets. + 'PSUseSingularNouns' + ) +} diff --git a/PowerShell/CustomRuntime/PSScriptAnalyzerSettings.psd1 b/PowerShell/CustomRuntime/PSScriptAnalyzerSettings.psd1 new file mode 100644 index 000000000..a3fef2d59 --- /dev/null +++ b/PowerShell/CustomRuntime/PSScriptAnalyzerSettings.psd1 @@ -0,0 +1,41 @@ +# PSScriptAnalyzer contract for the MODULE SOURCE (Public/, Private/, Config/, the .psm1 and .psd1). +# +# This scope is held to the full default rule set with NO rule exclusions, and `build.ps1 -Task Lint` +# fails on ANY finding here, at any severity. The source is kept at zero findings, and the gate is +# worth keeping: a rule excluded here would be excluded everywhere in the +# shipping cmdlet code. +# +# Findings that are genuinely wrong are suppressed AT THE SITE with a +# [Diagnostics.CodeAnalysis.SuppressMessageAttribute] carrying a Justification, so the reason lives +# next to the code a reviewer is reading. The suppressed rules, and why (each site's Justification +# says which case it is): +# +# PSUseOutputTypeCorrectly A comma-wrapped return (`return , ([string[]]$x)`) emits one +# object whose runtime type is the declared one, or a collected +# @(...) is unrolled on emit; the rule infers Object[] from the +# static shape. +# PSShouldProcess The scaffolders declare SupportsShouldProcess and leave every +# write to helpers that gate themselves. +# PSUseShouldProcessForState- New-* helpers that only build an in-memory object or +# ChangingFunctions ErrorRecord change no state. +# PSUsePSCredentialType, -Credential takes an AWS.Tools AWSCredentials object, as on every +# PSAvoidUsingPlainTextForPassword AWS.Tools cmdlet, not a PSCredential or a password string. +# PSReviewUnusedParameter A helper keeps a parameter it does not read so that every caller +# calls it the same way. +# +# `grep -rn SuppressMessageAttribute src/` lists every site. +# +# Tests/ and Templates/ are NOT linted with this file -- they are different contexts with their own +# legitimate patterns (mockable stub signatures, bootstrap console logging). See +# PSScriptAnalyzerSettings.Relaxed.psd1. +@{ + IncludeDefaultRules = $true + + # ParseError is listed so a file that does not parse is reported: it yields only ParseError records. + Severity = @( + 'ParseError' + 'Error' + 'Warning' + 'Information' + ) +} diff --git a/PowerShell/CustomRuntime/README.md b/PowerShell/CustomRuntime/README.md new file mode 100644 index 000000000..522d3cd79 --- /dev/null +++ b/PowerShell/CustomRuntime/README.md @@ -0,0 +1,468 @@ +# AWS.ToolExtras.LambdaPSRuntime + +Value-add PowerShell tooling for running PowerShell on AWS Lambda via a **customer-managed runtime** +or a **custom runtime**. It scaffolds, validates, builds, and packages runtime and function projects, +and offers one-command deployments for the common case. + +AWS Lambda has no managed PowerShell runtime, so PowerShell brings its own: a native `pwsh` +interpreter plus a bootstrap implementing the Lambda Runtime API loop. That runtime ships as a +customer-managed runtime (a container image that functions bind to by alias), as a custom runtime on +`provided.al2023` (a layer, or bundled into the function's .zip), or inside a function's own container +image. This module automates building and deploying it. It lives deliberately outside the +`AWS.Tools.*` family so it is not tied to that family's unified-versioning lockstep. + +## Requirements + +- PowerShell 7.4+ +- For the container-based approaches (CMR, container-per-function): **Docker with `buildx`** on + `PATH`, or no container CLI at all. Where Docker or buildx is missing, or the Docker daemon isn't + running, the image build + (`-BuildMethod Auto`, the default) builds and pushes the image of a project as scaffolded, without + Docker. A local build (`-Tag`) or an edited Dockerfile still needs Docker. Docker is the only + container CLI this module supports. A customer-managed runtime needs a + Docker v2 Schema 2 manifest, which the image build emits with buildx's `--provenance=false`, + `--sbom=false` and `oci-mediatypes=false`. Other CLIs can produce one too (for example `podman push --format v2s2`), + but the module builds and tests with Docker only. + `Test-LambdaPSContainerRuntime` preflights both the CLI and the plugin. +- The container-free approaches (Layer, self-contained `.zip`) need no container runtime at all. +- AWS.Tools 5.0.336 or later (`AWS.Tools.Lambda`, `AWS.Tools.LambdaCore`, `AWS.Tools.ECR`, + `AWS.Tools.SecurityToken`), with an `AWS.Tools.LambdaCore` that exports the Lambda + customer-managed runtime cmdlets (`New-LMCRuntime`, `New-LMCRuntimeVersion`, + `New-LMCRuntimeAlias`, …) and an `AWS.Tools.Lambda` whose function cmdlets accept the runtime + binding (`Publish-LMFunction -RuntimeConfig_RuntimeArn -RuntimeConfig_RuntimeAlias`). + +## Concepts + +The runtime can be packaged four ways; they differ only in packaging, each a scaffolding template +with its own lint rules: + +| Approach | Scaffold with | `pwsh` | Container | One-command deploy | +| --- | --- | --- | --- | --- | +| **CMR** (default) | `New-LambdaPSRuntimeProject -Path ./rt -PowerShellVersion 7.6.*` (`-Target CMR` is the default) | installed in image | Yes | Yes | +| Layer | `New-LambdaPSRuntimeProject -Path ./rt -PowerShellVersion 7.6.* -Target Layer` | bundled on `provided.al2023` | No | No | +| Self-contained `.zip` | `New-LambdaPSFunctionProject -Path ./fn -Handler handler -Target SelfContainedZip -PowerShellVersion 7.6.*` | bundled on `provided.al2023` | No | No | +| Container-per-function | `New-LambdaPSFunctionProject -Path ./fn -Handler handler -Target Container -PowerShellVersion 7.6.*` | installed in image | Yes | No | + +A function bound to a customer-managed runtime needs only its handler code: `New-LambdaPSFunctionProject +-Path ./fn -Handler handler` scaffolds one (`-Target RuntimeBound`, the default). + +CMR (customer-managed runtime) is the default: publish the runtime once as a container image, +reference it by alias, and roll the whole fleet forward by moving the alias — no per-function +redeploy. Each PowerShell line (7.4, 7.5, 7.6) installs a pinned pwsh release by default, unless +`New-LambdaPSRuntimeDeployment` finds a newer one it can verify (see +[Patching a runtime](#patching-a-runtime)); the +releases and their tarball SHA256s are listed in `Config/pwsh.psd1`. `-PowerShellVersion` takes an exact release (`7.6.9`), a line (`7.6.*`) or the +highest line of a major version (`7.*`); a bare `7.6` is refused. For an exact +release, an x86_64 image built with Docker installs any from Microsoft's signed RPM repository, +while an arm64 or no-Docker image and the Layer and .zip targets need one whose SHA256 is listed there. A module release moves +each line to its newest servicing release and keeps the SHA256s of the earlier ones, so a project pinned to an earlier release still builds. +PowerShell 7.4 and 7.5 reach end of support on 10 November 2026 +([lifecycle](https://learn.microsoft.com/en-us/powershell/scripting/install/powershell-support-lifecycle)): +the first module release after that date stops installing them by default, so +`-PowerShellVersion 7.4.*` or `7.5.*` then needs a full release (`7.4.22`) instead. Use 7.6 for new projects. The +container-free targets run in invariant-globalization mode (`DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1`) +so no ICU libraries are needed. Runtime images have ICU, so cultures such as `de-DE` work: the Docker +build installs libicu, and the no-Docker build adds Microsoft's ICU package next to pwsh. + +The Layer and self-contained `.zip` packages bundle pwsh, so they are large: for PowerShell 7.6, about +70 MB zipped and 178 MB unzipped on x86_64 (194 MB on arm64), before any modules. That is over Lambda's direct-upload +limit, so upload the `.zip` to S3 and pass `-Code_S3Bucket`/`-Code_S3Key` (`-Content_S3Bucket`/ +`-Content_S3Key` for `Publish-LMLayerVersion`). The 250 MB unzipped limit leaves roughly 70 MB for modules and code (55 MB on arm64). +`Build-LambdaPSRuntimePackage` and `Compress-LambdaPSFunctionPackage` stop with `UnzippedPackageTooLarge` +before writing a package over 250 MB unzipped, warn over 225 MB, and name the largest modules. +`New-LambdaPSFunctionDeployment` stops before it creates or updates the function: with `PackageTooLarge` +over 50 MB zipped, and with `UnzippedPackageTooLarge` over 250 MB unzipped. + +## Quick start (high-level) + +Deploy the runtime once, then deploy functions bound to its alias. + +```powershell +Import-Module ./src/AWS.ToolExtras.LambdaPSRuntime/AWS.ToolExtras.LambdaPSRuntime.psd1 + +# 1. Deploy the runtime (preflight container CLI -> scaffold -> build/push image -> +# publish version -> point the 'default' alias at it). -RuntimeAlias is required, as every function +# bound to the alias runs the new version; Tab offers 'default' and the runtime's aliases. +New-LambdaPSRuntimeDeployment -RuntimeName my-powershell-runtime -PowerShellVersion 7.6.* -RuntimeAlias default ` + -IncludeModule @( + @{ ModuleName = 'AWS.Tools.S3'; RequiredVersion = '5.0.274' }, + @{ ModuleName = 'AWS.Tools.DynamoDBv2'; RequiredVersion = '5.0.274' } + ) -Region us-east-1 + +# 2. Scaffold a function: ./hello/handler.ps1 is a starter handler to edit. +New-LambdaPSFunctionProject -Path ./hello -Handler handler + +# 3. Deploy it bound to the runtime alias (resolves the runtime ARN for you). The role must exist +# and trust lambda.amazonaws.com. +New-LambdaPSFunctionDeployment -FunctionName hello-powershell -ProjectPath ./hello ` + -RuntimeName my-powershell-runtime -RuntimeAlias default ` + -Role arn:aws:iam::111122223333:role/hello-powershell-role -Region us-east-1 + +# 4. Invoke it. +Invoke-LambdaPSFunction -FunctionName hello-powershell -Payload @{ name = 'world' } -Region us-east-1 ` + -IncludeLog -InformationAction Continue +``` + +The three cmdlets that call AWS take `-ProfileName`, `-ProfileLocation` and `-Credential`; a +relative `-ProfileLocation` is resolved against the current PowerShell location. Without them, +AWS.Tools uses its default credentials (`Set-AWSCredential`, environment variables, the default +profile, or an instance or container role). `-Region` is optional +the same way: without it, the region comes from `Set-DefaultAWSRegion`, the `-ProfileName` profile, the +default profile, `AWS_REGION`, the `AWS_PROFILE` profile, or the instance or container, in that order +(`AWS_DEFAULT_REGION` is not read), and a deploy that finds none fails with `RegionNotResolved`. For `New-LambdaPSFunctionDeployment` and +`Invoke-LambdaPSFunction`, a full function ARN in `-FunctionName` supplies the region when `-Region` is +omitted, and a `-Region` that differs from the ARN's fails with `FunctionRegionMismatch`. + +A handler reads the parsed event as `$LambdaInput` and the runtime details as `$LambdaContext`. A script +handler has both in scope, with or without `param($LambdaInput, $LambdaContext)`; a function handler +receives them positionally, so it declares that param block. +Whatever the handler leaves on the pipeline is returned as the response. `-Handler` takes one of three +forms: `