AWS Serverless Application
The AWS Serverless Application template scaffolds a Pulumi project that deploys a serverless web application to AWS. It provisions an Amazon S3 bucket for static website hosting, an AWS Lambda function for the application backend, and an Amazon API Gateway REST API that routes requests to the static content and the Lambda function. The template ships with a placeholder web page that displays the current time so the project deploys end to end out of the box.
Before you begin#
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage AWS Lambda, API Gateway, and IAM resources
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage AWS Lambda, API Gateway, and IAM resources
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage AWS Lambda, API Gateway, and IAM resources
- A current version of Go installed locally
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage AWS Lambda, API Gateway, and IAM resources
- A current version of .NET installed locally
For this walkthrough, you'll need:
- The Pulumi CLI
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage AWS Lambda, API Gateway, and IAM resources
For this walkthrough, you'll need:
- A current version of the Pulumi CLI (Pulumi HCL requires no additional runtime)
- An AWS account with programmatic access
- The AWS CLI (optional, but recommended and used in this guide)
- Permission to manage AWS Lambda, API Gateway, and IAM resources
Create a new project#
Create a new project from the template:
mkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-typescriptmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-typescriptmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-pythonmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-pythonmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-gomkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-gomkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-csharpmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-csharpmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-yamlmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-yamlmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-hclmkdir my-serverless-app; cd my-serverless-apppulumi new serverless-aws-hclThe pulumi new command walks you through creating and configuring the new project and stack. A stack is an instance of a project, and you can have many of them (dev, staging, prod), each with its own configuration settings. Depending on the language, you may also be asked for your preferred package manager or toolchain.
This template’s settings include:
| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set aws:region "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set aws:region "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set aws:region "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set aws:region "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set aws:region "<value>"| Key | Description | Default |
|---|---|---|
| aws:region | The AWS region to deploy into | us-west-2 |
pulumi config set
:
pulumi config set aws:region <value>pulumi config set aws:region "<value>"Review the code#
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the resources it declares.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.
When setup completes, you’ll see a few files:
Pulumi.yamlcontains the project name and the language it’s written in.Pulumi.dev.yamlcontains thedevstack’s settings, including the values you just entered.index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tfcontains the program code that declares your cloud resources.
Take a moment to open them up and have a look. Here’s what’s in index.tsindex.js__main__.pymain.goProgram.csProgram.fsProgram.vbApp.javaPulumi.yamlmain.tf:
import * as pulumi from "@pulumi/pulumi";import * as aws from "@pulumi/aws";import * as apigateway from "@pulumi/aws-apigateway";
// A Lambda function to invokeconst fn = new aws.lambda.CallbackFunction("fn", { callback: async (ev, ctx) => { return { statusCode: 200, body: new Date().toISOString(), }; }})
// An AWS provider for the REST API to deploy its resources withconst provider = new aws.Provider("provider", { region: aws.config.region,});
// A REST API to route requests to HTML content and the Lambda functionconst api = new apigateway.RestAPI("api", { routes: [ { path: "/", localPath: "www"}, { path: "/date", method: "GET", eventHandler: fn }, ]}, { providers: [provider] });
// The URL at which the REST API will be served.export const url = api.url;import jsonimport pulumiimport pulumi_aws as awsimport pulumi_aws_apigateway as apigateway
# An execution role to use for the Lambda functionrole = aws.iam.Role("role", assume_role_policy=json.dumps({ "Version": "2012-10-17", "Statement": [{ "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com", }, }], }), managed_policy_arns=[aws.iam.ManagedPolicy.AWS_LAMBDA_BASIC_EXECUTION_ROLE])
# A Lambda function to invokefn = aws.lambda_.Function("fn", runtime="python3.12", handler="handler.handler", role=role.arn, code=pulumi.FileArchive("./function"))
# An AWS provider for the REST API to deploy its resources withprovider = aws.Provider("provider", region=aws.config.region)
# A REST API to route requests to HTML content and the Lambda functionapi = apigateway.RestAPI("api", routes=[ apigateway.RouteArgs(path="/", local_path="www"), apigateway.RouteArgs(path="/date", method=apigateway.Method.GET, event_handler=fn) ], opts=pulumi.ResourceOptions(providers=[provider]))
# The URL at which the REST API will be served.pulumi.export("url", api.url)package main
import ( "encoding/json"
"github.com/pulumi/pulumi-aws-apigateway/sdk/v3/go/apigateway" "github.com/pulumi/pulumi-aws/sdk/v7/go/aws" "github.com/pulumi/pulumi-aws/sdk/v7/go/aws/config" "github.com/pulumi/pulumi-aws/sdk/v7/go/aws/iam" "github.com/pulumi/pulumi-aws/sdk/v7/go/aws/lambda" "github.com/pulumi/pulumi/sdk/v3/go/pulumi")
func main() { pulumi.Run(func(ctx *pulumi.Context) error { // An execution role to use for the Lambda function policy, err := json.Marshal(map[string]interface{}{ "Version": "2012-10-17", "Statement": []map[string]interface{}{ map[string]interface{}{ "Action": "sts:AssumeRole", "Effect": "Allow", "Principal": map[string]interface{}{ "Service": "lambda.amazonaws.com", }, }, }, }) if err != nil { return err }
role, err := iam.NewRole(ctx, "role", &iam.RoleArgs{ AssumeRolePolicy: pulumi.String(policy), ManagedPolicyArns: pulumi.StringArray{ iam.ManagedPolicyAWSLambdaBasicExecutionRole, }, }) if err != nil { return err }
// A Lambda function to invoke fn, err := lambda.NewFunction(ctx, "fn", &lambda.FunctionArgs{ Runtime: pulumi.String("python3.12"), Handler: pulumi.String("handler.handler"), Role: role.Arn, Code: pulumi.NewFileArchive("./function"), }) if err != nil { return err }
// An AWS provider for the REST API to deploy its resources with provider, err := aws.NewProvider(ctx, "provider", &aws.ProviderArgs{ Region: pulumi.String(config.GetRegion(ctx)), }) if err != nil { return err }
// A REST API to route requests to HTML content and the Lambda function localPath := "www" method := apigateway.MethodGET api, err := apigateway.NewRestAPI(ctx, "api", &apigateway.RestAPIArgs{ Routes: []apigateway.RouteArgs{ apigateway.RouteArgs{Path: "/", LocalPath: &localPath}, apigateway.RouteArgs{Path: "/date", Method: &method, EventHandler: fn}, }, }, pulumi.Providers(provider)) if err != nil { return err }
// The URL at which the REST API will be served ctx.Export("url", api.Url) return nil })}using System.Collections.Generic;using System.Text.Json;using Pulumi;using Aws = Pulumi.Aws;using AwsApiGateway = Pulumi.AwsApiGateway;
return await Deployment.RunAsync(() =>{ var role = new Aws.Iam.Role("role", new() { AssumeRolePolicy = JsonSerializer.Serialize(new Dictionary<string, object?> { ["Version"] = "2012-10-17", ["Statement"] = new[] { new Dictionary<string, object?> { ["Action"] = "sts:AssumeRole", ["Effect"] = "Allow", ["Principal"] = new Dictionary<string, object?> { ["Service"] = "lambda.amazonaws.com", }, }, }, }), ManagedPolicyArns = new[] { "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", }, });
var fn = new Aws.Lambda.Function("fn", new() { Runtime = "python3.12", Handler = "handler.handler", Role = role.Arn, Code = new FileArchive("./function"), });
var provider = new Aws.Provider("provider", new() { Region = new Config("aws").Require("region"), });
var api = new AwsApiGateway.RestAPI("api", new() { Routes = { new AwsApiGateway.Inputs.RouteArgs { Path = "/", LocalPath = "www", }, new AwsApiGateway.Inputs.RouteArgs { Path = "/date", Method = AwsApiGateway.Method.GET, EventHandler = fn, }, }, }, new ComponentResourceOptions { Providers = { provider }, });
return new Dictionary<string, object?> { ["url"] = api.Url, };});name: my-projectdescription: A Pulumi YAML program to deploy a serverless application on AWSruntime: yamlresources: # An execution role to use for the Lambda function role: type: aws:iam:Role properties: assumeRolePolicy: fn::toJSON: Version: "2012-10-17" Statement: - Action: sts:AssumeRole Effect: Allow Principal: Service: lambda.amazonaws.com managedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
# A Lambda function to invoke fn: type: aws:lambda:Function properties: runtime: python3.12 handler: handler.handler role: ${role.arn} code: fn::fileArchive: ./function
# An AWS provider for the REST API to deploy its resources with provider: type: pulumi:providers:aws properties: region: ${aws:region}
# A REST API to route requests to HTML content and the Lambda function api: type: aws-apigateway:RestAPI properties: routes: - path: / localPath: www - path: /date method: GET eventHandler: ${fn} options: providers: - ${provider}
outputs: # The URL at which the REST API will be served. url: ${api.url}terraform { required_providers { aws = { source = "pulumi/aws" } aws-apigateway = { source = "pulumi/aws-apigateway" } }}
# An execution role to use for the Lambda functionresource "aws_iam_role" "role" { assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [{ Action = "sts:AssumeRole" Effect = "Allow" Principal = { Service = "lambda.amazonaws.com" } }] }) managed_policy_arns = ["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"]}
# A Lambda function to invokeresource "aws_lambda_function" "fn" { runtime = "python3.12" handler = "handler.handler" role = aws_iam_role.role.arn filename = filearchive("./function")}
# The AWS region to deploy intodata "aws_region" "current" {}
# An AWS provider for the REST API to deploy its resources withprovider "aws" { alias = "api" region = data.aws_region.current.region}
# A REST API to route requests to HTML content and the Lambda functionresource "aws-apigateway_rest_a_p_i" "api" { providers = [aws.api]
routes { path = "/" local_path = "www" }
routes { path = "/date" method = "GET" event_handler = aws_lambda_function.fn }}
# The URL at which the REST API will be served.output "url" { value = aws-apigateway_rest_a_p_i.api.url}Deploy the project#
Deploy with pulumi up. It starts with a preview of what it’s about to create and asks before it changes anything. Choose yes to deploy.
pulumi uppulumi upPulumi adds a random suffix to most resource names, so the Lambda function fn becomes something like fn-4f8a2c1. This is autonaming. It lets you deploy the same program to more than one stack, and lets Pulumi create a replacement before it deletes the old resource, without names colliding.
When it finishes, Pulumi prints the stack’s outputs, values it only knows once the resources exist:
- url
The HTTPS URL of the application, served by API Gateway.
Read one any time with pulumi stack output <name>, or pass it to another command. This opens the app in your browser:
open $(pulumi stack output url)xdg-open $(pulumi stack output url)Start-Process $(pulumi stack output url)The page gets the time from the Lambda function at the /date path. Call it from the terminal with curl; it prints the current time:
curl -s "$(pulumi stack output url)date"curl.exe -s "$(pulumi stack output url)date"Need help?
If pulumi up reports No valid credential sources found or ExpiredToken, sign in again:
aws loginaws loginStill stuck? Let us know.
Customize the project#
The template has no configuration settings of its own; aws:region is the only one pulumi new sets. It deploys the website from the www folder.
The Lambda function’s code is the callback in index.ts.
The Lambda function’s code is function/handler.py. It’s Python, whatever language the program is written in.
The Lambda function’s code is function/handler.py. It’s Python, whatever language the program is written in.
The Lambda function’s code is function/handler.py. It’s Python, whatever language the program is written in.
The Lambda function’s code is function/handler.py. It’s Python, whatever language the program is written in.
The Lambda function’s code is function/handler.py. It’s Python, whatever language the program is written in.
Using your own web content#
If you already have a website you’d like to deploy, you can do so by replacing the contents of the www folder and redeploying with pulumi up.
Customizing the application’s functionality#
You can customize the placeholder website by editing the Lambda function to perform another action, such as displaying a countdown to a future time. You can also add new functionality by creating a new Lambda function, adding a new path to the REST API, and updating the HTML to call the new path.
To start small, change the format of the time the function returns:
In index.ts:
const fn = new aws.lambda.CallbackFunction("fn", { callback: async (ev, ctx) => { return { statusCode: 200, body: new Date().toISOString(), body: new Date().toUTCString(), };In function/handler.py:
def handler(event, context): return { 'statusCode': 200, 'body': datetime.now().isoformat() 'body': datetime.now().ctime() }In function/handler.py:
def handler(event, context): return { 'statusCode': 200, 'body': datetime.now().isoformat() 'body': datetime.now().ctime() }In function/handler.py:
def handler(event, context): return { 'statusCode': 200, 'body': datetime.now().isoformat() 'body': datetime.now().ctime() }In function/handler.py:
def handler(event, context): return { 'statusCode': 200, 'body': datetime.now().isoformat() 'body': datetime.now().ctime() }In function/handler.py:
def handler(event, context): return { 'statusCode': 200, 'body': datetime.now().isoformat() 'body': datetime.now().ctime() }Deploy the change and call /date again:
pulumi upcurl -s "$(pulumi stack output url)date"pulumi upcurl.exe -s "$(pulumi stack output url)date"The time now comes back like Wed, 21 Oct 2026 14:05:09 GMT.
The time now comes back like Wed Oct 21 14:05:09 2026.
The time now comes back like Wed Oct 21 14:05:09 2026.
The time now comes back like Wed Oct 21 14:05:09 2026.
The time now comes back like Wed Oct 21 14:05:09 2026.
The time now comes back like Wed Oct 21 14:05:09 2026.
To see what else you can add, browse the AWS provider in the Pulumi Registry.
Cleaning up#
You can cleanly destroy the stack and all of its infrastructure with pulumi destroy:
pulumi destroypulumi destroyLearn more#
- Browse other architecture templates in the Templates gallery.
- Explore the AWS provider API docs in the Pulumi Registry.
- Walk through Pulumi from the ground up in Pulumi Tutorials.
- Read the latest serverless posts on the Pulumi blog.