How do I create an AWS Lambda function in TypeScript?
In this guide, we will create an AWS Lambda function using Pulumi and TypeScript. AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. We will define a simple Lambda function and deploy it to AWS.
Key Points:
- Define an AWS Lambda function using Pulumi.
- Specify the function’s runtime, handler, and code.
- Deploy the Lambda function to AWS.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Define the IAM role for the Lambda function
const lambdaRole = new aws.iam.Role("lambdaRole", {
assumeRolePolicy: {
Version: "2012-10-17",
Statement: [{
Action: "sts:AssumeRole",
Principal: {
Service: "lambda.amazonaws.com",
},
Effect: "Allow",
Sid: "",
}],
},
});
// Attach the AWSLambdaBasicExecutionRole policy to the role
const lambdaRolePolicy = new aws.iam.RolePolicyAttachment("lambdaRolePolicy", {
role: lambdaRole.name,
policyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
});
// Define the Lambda function
const lambdaFunction = new aws.lambda.Function("myLambdaFunction", {
runtime: aws.lambda.NodeJS12dXRuntime,
role: lambdaRole.arn,
handler: "index.handler",
code: new pulumi.asset.AssetArchive({
"index.js": new pulumi.asset.StringAsset(`
exports.handler = async function(event) {
console.log("request:", JSON.stringify(event, undefined, 2));
return {
statusCode: 200,
body: JSON.stringify({ message: "Hello, world!" })
};
};
`),
}),
});
// Export the Lambda function name and ARN
export const lambdaFunctionName = lambdaFunction.name;
export const lambdaFunctionArn = lambdaFunction.arn;
Summary
In this guide, we created an AWS Lambda function using Pulumi and TypeScript. We defined an IAM role for the Lambda function, attached the necessary policy, and created the Lambda function with a simple handler. The function was then deployed to AWS, and we exported its name and ARN for reference. This setup allows you to run serverless code without managing servers, providing a scalable and cost-effective solution for various use cases.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.