An opinionated template for deploying serverless functions to AWS Lambda using Swift AWS Lambda Runtime.
Goals:
- streamline deployment
- promote best practices
- improve performance
- build and deploy with single
make deploy
- provision all resources using AWS CloudFormation (with help from AWS SAM CLI)
-
tracing using AWS X-Ray SDK for SwiftTODO: restore - CI workflows using GitHub Actions
- code formatting using swiftformat
- generate documentation using swift-doc
- Swift compiler and Package Manager - both included in XCode
- Docker
- Amazon Web Services (AWS) Account
- AWS Serverless Application Model (SAM) CLI
- GNU Make
- swiftformat
The template contains code with two AWS Lambda functions:
- HelloWorldAPI handling Amazon API Gateway events
as well as a AWS SAM template used to deploy them using AWS SAM CLI.
Since SAM CLI does not support Swift, a Docker image is created and used to cross compile and package Swift code to run in AWS Lambda environment.
-
Package.swift
- Swift Package Manager manifest file defining the package’s name, its contents and dependencies -
template.yaml
- AWS SAM Template defining the application's AWS resources -
samconfig.toml
- AWS SAM CLI project-level configuration file -
Swift AWS Lambda Runtime Configuration can be fine tuned using environment variables
Build and deploy:
$ make deploy
This will:
- build Docker image used to cross compile the code (if it does not exist)
- cross compile and package Lambda functions and Swift Linux Runtime Lambda Layer
- prompt to configure AWS SAM project (if
samconfig.toml
does not exist) - deploy (create or update) AWS resources defined in
template.yaml
including Lambda functions and layers
The HelloWorldAPI endpoint is printed after successful deployment, example: https://xxx.execute-api.us-east-1.amazonaws.com/Prod/hello/
When prompted, confirm that it is okay to deploy an endpoint without authorization, see:
HelloWorldAPIFunction may not have authorization defined, Is this okay? [y/N]: y
Build and run tests:
$ swift test
Set the LOCAL_LAMBDA_SERVER_ENABLED
environment variable to true
.
Build and run Lambda:
$ swift run HelloWorldAPI
Invoke the Lambda with curl
:
$ curl --header "Content-Type: application/json" \
--request POST --data @events/api2.json \
http://localhost:7000/invoke
or with HTTPie:
$ http POST http://localhost:7000/invoke @events/api2.json
Format code using swiftformat:
swiftformat .
Consider creating Git pre-commit hook
echo 'swiftformat --lint .' > .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
- Test - Run tests
- Package - Tests creating of packages with lambda functions
- Lint - validates code formatting using swiftformat
- Documentation generates documentation using swift-doc
Note github-wiki-publish-action used by Documentation workflow requires that your repository has the following:
- A wiki with at least one page in it
- A secret named
GH_PERSONAL_ACCESS_TOKEN
with a Github personal access token with "repo" authorization