Function
Provides a Lambda Function resource. Lambda allows you to trigger execution of code in response to events in AWS, enabling serverless backend solutions. The Lambda Function itself includes source code and runtime configuration. For information about Lambda and how to use it, see What is AWS Lambda?
NOTE: Due to AWS Lambda improved VPC networking changes that began deploying in September 2019, EC2 subnets and security groups associated with Lambda Functions can take up to 45 minutes to successfully delete. NOTE: If you get a
KMSAccessDeniedException: Lambda was unable to decrypt the environment variables because KMS access was denied
error when invoking anaws.lambda.Function
with environment variables, the IAM role associated with the function may have been deleted and recreated after the function was created. You can fix the problem two ways: 1) updating the function's role to another role and then updating it back again to the recreated role, or 2) by using Pulumi totaint
the function andapply
your configuration again to recreate the function. (When you create a function, Lambda grants permissions on the KMS key to the function's IAM role. If the IAM role is recreated, the grant is no longer valid. Changing the function's role or recreating the function causes Lambda to update the grant.) To give an external source (like an EventBridge Rule, SNS, or S3) permission to access the Lambda function, use theaws.lambda.Permission
resource. See Lambda Permission Model for more details. On the other hand, therole
argument of this resource is the function's execution role for identity and access to AWS services and resources.
Example Usage
Basic Example
package generated_program;
import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.aws.iam.IamFunctions;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentArgs;
import com.pulumi.aws.iam.Role;
import com.pulumi.aws.iam.RoleArgs;
import com.pulumi.archive.ArchiveFunctions;
import com.pulumi.archive.inputs.GetFileArgs;
import com.pulumi.aws.lambda.Function;
import com.pulumi.aws.lambda.FunctionArgs;
import com.pulumi.aws.lambda.inputs.FunctionEnvironmentArgs;
import com.pulumi.asset.FileArchive;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) {
Pulumi.run(App::stack);
}
public static void stack(Context ctx) {
final var assumeRole = IamFunctions.getPolicyDocument(GetPolicyDocumentArgs.builder()
.statements(GetPolicyDocumentStatementArgs.builder()
.effect("Allow")
.principals(GetPolicyDocumentStatementPrincipalArgs.builder()
.type("Service")
.identifiers("lambda.amazonaws.com")
.build())
.actions("sts:AssumeRole")
.build())
.build());
var iamForLambda = new Role("iamForLambda", RoleArgs.builder()
.assumeRolePolicy(assumeRole.applyValue(getPolicyDocumentResult -> getPolicyDocumentResult.json()))
.build());
final var lambda = ArchiveFunctions.getFile(GetFileArgs.builder()
.type("zip")
.sourceFile("lambda.js")
.outputPath("lambda_function_payload.zip")
.build());
var testLambda = new Function("testLambda", FunctionArgs.builder()
.code(new FileArchive("lambda_function_payload.zip"))
.role(iamForLambda.arn())
.handler("index.test")
.runtime("nodejs18.x")
.environment(FunctionEnvironmentArgs.builder()
.variables(Map.of("foo", "bar"))
.build())
.build());
}
}
Lambda Layers
package generated_program;
import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.aws.lambda.LayerVersion;
import com.pulumi.aws.lambda.Function;
import com.pulumi.aws.lambda.FunctionArgs;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) {
Pulumi.run(App::stack);
}
public static void stack(Context ctx) {
var exampleLayerVersion = new LayerVersion("exampleLayerVersion");
var exampleFunction = new Function("exampleFunction", FunctionArgs.builder()
.layers(exampleLayerVersion.arn())
.build());
}
}
Lambda Ephemeral Storage
Lambda Function Ephemeral Storage(/tmp
) allows you to configure the storage upto 10
GB. The default value set to 512
MB.
package generated_program;
import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.aws.iam.IamFunctions;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentArgs;
import com.pulumi.aws.iam.Role;
import com.pulumi.aws.iam.RoleArgs;
import com.pulumi.aws.lambda.Function;
import com.pulumi.aws.lambda.FunctionArgs;
import com.pulumi.aws.lambda.inputs.FunctionEphemeralStorageArgs;
import com.pulumi.asset.FileArchive;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) {
Pulumi.run(App::stack);
}
public static void stack(Context ctx) {
final var assumeRole = IamFunctions.getPolicyDocument(GetPolicyDocumentArgs.builder()
.statements(GetPolicyDocumentStatementArgs.builder()
.effect("Allow")
.principals(GetPolicyDocumentStatementPrincipalArgs.builder()
.type("Service")
.identifiers("lambda.amazonaws.com")
.build())
.actions("sts:AssumeRole")
.build())
.build());
var iamForLambda = new Role("iamForLambda", RoleArgs.builder()
.assumeRolePolicy(assumeRole.applyValue(getPolicyDocumentResult -> getPolicyDocumentResult.json()))
.build());
var testLambda = new Function("testLambda", FunctionArgs.builder()
.code(new FileArchive("lambda_function_payload.zip"))
.role(iamForLambda.arn())
.handler("index.test")
.runtime("nodejs18.x")
.ephemeralStorage(FunctionEphemeralStorageArgs.builder()
.size(10240)
.build())
.build());
}
}
Lambda File Systems
Lambda File Systems allow you to connect an Amazon Elastic File System (EFS) file system to a Lambda function to share data across function invocations, access existing data including large files, and save function state.
package generated_program;
import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.aws.efs.FileSystem;
import com.pulumi.aws.efs.FileSystemArgs;
import com.pulumi.aws.efs.MountTarget;
import com.pulumi.aws.efs.MountTargetArgs;
import com.pulumi.aws.efs.AccessPoint;
import com.pulumi.aws.efs.AccessPointArgs;
import com.pulumi.aws.efs.inputs.AccessPointRootDirectoryArgs;
import com.pulumi.aws.efs.inputs.AccessPointRootDirectoryCreationInfoArgs;
import com.pulumi.aws.efs.inputs.AccessPointPosixUserArgs;
import com.pulumi.aws.lambda.Function;
import com.pulumi.aws.lambda.FunctionArgs;
import com.pulumi.aws.lambda.inputs.FunctionFileSystemConfigArgs;
import com.pulumi.aws.lambda.inputs.FunctionVpcConfigArgs;
import com.pulumi.resources.CustomResourceOptions;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) {
Pulumi.run(App::stack);
}
public static void stack(Context ctx) {
var efsForLambda = new FileSystem("efsForLambda", FileSystemArgs.builder()
.tags(Map.of("Name", "efs_for_lambda"))
.build());
var alpha = new MountTarget("alpha", MountTargetArgs.builder()
.fileSystemId(efsForLambda.id())
.subnetId(aws_subnet.subnet_for_lambda().id())
.securityGroups(aws_security_group.sg_for_lambda().id())
.build());
var accessPointForLambda = new AccessPoint("accessPointForLambda", AccessPointArgs.builder()
.fileSystemId(efsForLambda.id())
.rootDirectory(AccessPointRootDirectoryArgs.builder()
.path("/lambda")
.creationInfo(AccessPointRootDirectoryCreationInfoArgs.builder()
.ownerGid(1000)
.ownerUid(1000)
.permissions("777")
.build())
.build())
.posixUser(AccessPointPosixUserArgs.builder()
.gid(1000)
.uid(1000)
.build())
.build());
var example = new Function("example", FunctionArgs.builder()
.fileSystemConfig(FunctionFileSystemConfigArgs.builder()
.arn(accessPointForLambda.arn())
.localMountPath("/mnt/efs")
.build())
.vpcConfig(FunctionVpcConfigArgs.builder()
.subnetIds(aws_subnet.subnet_for_lambda().id())
.securityGroupIds(aws_security_group.sg_for_lambda().id())
.build())
.build(), CustomResourceOptions.builder()
.dependsOn(alpha)
.build());
}
}
CloudWatch Logging and Permissions
For more information about CloudWatch Logs for Lambda, see the Lambda User Guide.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
const config = new pulumi.Config();
const lambdaFunctionName = config.get("lambdaFunctionName") || "lambda_function_name";
// This is to optionally manage the CloudWatch Log Group for the Lambda Function.
// If skipping this resource configuration, also add "logs:CreateLogGroup" to the IAM policy below.
const example = new aws.cloudwatch.LogGroup("example", {retentionInDays: 14});
const lambdaLoggingPolicyDocument = aws.iam.getPolicyDocument({
statements: [{
effect: "Allow",
actions: [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
],
resources: ["arn:aws:logs:*:*:*"],
}],
});
const lambdaLoggingPolicy = new aws.iam.Policy("lambdaLoggingPolicy", {
path: "/",
description: "IAM policy for logging from a lambda",
policy: lambdaLoggingPolicyDocument.then(lambdaLoggingPolicyDocument => lambdaLoggingPolicyDocument.json),
});
const lambdaLogs = new aws.iam.RolePolicyAttachment("lambdaLogs", {
role: aws_iam_role.iam_for_lambda.name,
policyArn: lambdaLoggingPolicy.arn,
});
const testLambda = new aws.lambda.Function("testLambda", {}, {
dependsOn: [
lambdaLogs,
example,
],
});
import pulumi
import pulumi_aws as aws
config = pulumi.Config()
lambda_function_name = config.get("lambdaFunctionName")
if lambda_function_name is None:
lambda_function_name = "lambda_function_name"
# This is to optionally manage the CloudWatch Log Group for the Lambda Function.
# If skipping this resource configuration, also add "logs:CreateLogGroup" to the IAM policy below.
example = aws.cloudwatch.LogGroup("example", retention_in_days=14)
lambda_logging_policy_document = aws.iam.get_policy_document(statements=[aws.iam.GetPolicyDocumentStatementArgs(
effect="Allow",
actions=[
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
],
resources=["arn:aws:logs:*:*:*"],
)])
lambda_logging_policy = aws.iam.Policy("lambdaLoggingPolicy",
path="/",
description="IAM policy for logging from a lambda",
policy=lambda_logging_policy_document.json)
lambda_logs = aws.iam.RolePolicyAttachment("lambdaLogs",
role=aws_iam_role["iam_for_lambda"]["name"],
policy_arn=lambda_logging_policy.arn)
test_lambda = aws.lambda_.Function("testLambda", opts=pulumi.ResourceOptions(depends_on=[
lambda_logs,
example,
]))
using System.Collections.Generic;
using System.Linq;
using Pulumi;
using Aws = Pulumi.Aws;
return await Deployment.RunAsync(() =>
{
var config = new Config();
var lambdaFunctionName = config.Get("lambdaFunctionName") ?? "lambda_function_name";
// This is to optionally manage the CloudWatch Log Group for the Lambda Function.
// If skipping this resource configuration, also add "logs:CreateLogGroup" to the IAM policy below.
var example = new Aws.CloudWatch.LogGroup("example", new()
{
RetentionInDays = 14,
});
var lambdaLoggingPolicyDocument = Aws.Iam.GetPolicyDocument.Invoke(new()
{
Statements = new[]
{
new Aws.Iam.Inputs.GetPolicyDocumentStatementInputArgs
{
Effect = "Allow",
Actions = new[]
{
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
},
Resources = new[]
{
"arn:aws:logs:*:*:*",
},
},
},
});
var lambdaLoggingPolicy = new Aws.Iam.Policy("lambdaLoggingPolicy", new()
{
Path = "/",
Description = "IAM policy for logging from a lambda",
PolicyDocument = lambdaLoggingPolicyDocument.Apply(getPolicyDocumentResult => getPolicyDocumentResult.Json),
});
var lambdaLogs = new Aws.Iam.RolePolicyAttachment("lambdaLogs", new()
{
Role = aws_iam_role.Iam_for_lambda.Name,
PolicyArn = lambdaLoggingPolicy.Arn,
});
var testLambda = new Aws.Lambda.Function("testLambda", new()
{
}, new CustomResourceOptions
{
DependsOn = new[]
{
lambdaLogs,
example,
},
});
});
package main
import (
"github.com/pulumi/pulumi-aws/sdk/v6/go/aws/cloudwatch"
"github.com/pulumi/pulumi-aws/sdk/v6/go/aws/iam"
"github.com/pulumi/pulumi-aws/sdk/v6/go/aws/lambda"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi/config"
)
func main() {
pulumi.Run(func(ctx *pulumi.Context) error {
cfg := config.New(ctx, "")
lambdaFunctionName := "lambda_function_name"
if param := cfg.Get("lambdaFunctionName"); param != "" {
lambdaFunctionName = param
}
example, err := cloudwatch.NewLogGroup(ctx, "example", &cloudwatch.LogGroupArgs{
RetentionInDays: pulumi.Int(14),
})
if err != nil {
return err
}
lambdaLoggingPolicyDocument, err := iam.GetPolicyDocument(ctx, &iam.GetPolicyDocumentArgs{
Statements: []iam.GetPolicyDocumentStatement{
{
Effect: pulumi.StringRef("Allow"),
Actions: []string{
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
},
Resources: []string{
"arn:aws:logs:*:*:*",
},
},
},
}, nil)
if err != nil {
return err
}
lambdaLoggingPolicy, err := iam.NewPolicy(ctx, "lambdaLoggingPolicy", &iam.PolicyArgs{
Path: pulumi.String("/"),
Description: pulumi.String("IAM policy for logging from a lambda"),
Policy: *pulumi.String(lambdaLoggingPolicyDocument.Json),
})
if err != nil {
return err
}
lambdaLogs, err := iam.NewRolePolicyAttachment(ctx, "lambdaLogs", &iam.RolePolicyAttachmentArgs{
Role: pulumi.Any(aws_iam_role.Iam_for_lambda.Name),
PolicyArn: lambdaLoggingPolicy.Arn,
})
if err != nil {
return err
}
_, err = lambda.NewFunction(ctx, "testLambda", nil, pulumi.DependsOn([]pulumi.Resource{
lambdaLogs,
example,
}))
if err != nil {
return err
}
return nil
})
}
package generated_program;
import com.pulumi.Context;
import com.pulumi.Pulumi;
import com.pulumi.core.Output;
import com.pulumi.aws.cloudwatch.LogGroup;
import com.pulumi.aws.cloudwatch.LogGroupArgs;
import com.pulumi.aws.iam.IamFunctions;
import com.pulumi.aws.iam.inputs.GetPolicyDocumentArgs;
import com.pulumi.aws.iam.Policy;
import com.pulumi.aws.iam.PolicyArgs;
import com.pulumi.aws.iam.RolePolicyAttachment;
import com.pulumi.aws.iam.RolePolicyAttachmentArgs;
import com.pulumi.aws.lambda.Function;
import com.pulumi.aws.lambda.FunctionArgs;
import com.pulumi.resources.CustomResourceOptions;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
public class App {
public static void main(String[] args) {
Pulumi.run(App::stack);
}
public static void stack(Context ctx) {
final var config = ctx.config();
final var lambdaFunctionName = config.get("lambdaFunctionName").orElse("lambda_function_name");
var example = new LogGroup("example", LogGroupArgs.builder()
.retentionInDays(14)
.build());
final var lambdaLoggingPolicyDocument = IamFunctions.getPolicyDocument(GetPolicyDocumentArgs.builder()
.statements(GetPolicyDocumentStatementArgs.builder()
.effect("Allow")
.actions(
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents")
.resources("arn:aws:logs:*:*:*")
.build())
.build());
var lambdaLoggingPolicy = new Policy("lambdaLoggingPolicy", PolicyArgs.builder()
.path("/")
.description("IAM policy for logging from a lambda")
.policy(lambdaLoggingPolicyDocument.applyValue(getPolicyDocumentResult -> getPolicyDocumentResult.json()))
.build());
var lambdaLogs = new RolePolicyAttachment("lambdaLogs", RolePolicyAttachmentArgs.builder()
.role(aws_iam_role.iam_for_lambda().name())
.policyArn(lambdaLoggingPolicy.arn())
.build());
var testLambda = new Function("testLambda", FunctionArgs.Empty, CustomResourceOptions.builder()
.dependsOn(
lambdaLogs,
example)
.build());
}
}
configuration:
lambdaFunctionName:
type: string
default: lambda_function_name
resources:
testLambda:
type: aws:lambda:Function
options:
dependson:
- ${lambdaLogs}
- ${example}
# This is to optionally manage the CloudWatch Log Group for the Lambda Function.
# If skipping this resource configuration, also add "logs:CreateLogGroup" to the IAM policy below.
example:
type: aws:cloudwatch:LogGroup
properties:
retentionInDays: 14
lambdaLoggingPolicy:
type: aws:iam:Policy
properties:
path: /
description: IAM policy for logging from a lambda
policy: ${lambdaLoggingPolicyDocument.json}
lambdaLogs:
type: aws:iam:RolePolicyAttachment
properties:
role: ${aws_iam_role.iam_for_lambda.name}
policyArn: ${lambdaLoggingPolicy.arn}
variables:
lambdaLoggingPolicyDocument:
fn::invoke:
Function: aws:iam:getPolicyDocument
Arguments:
statements:
- effect: Allow
actions:
- logs:CreateLogGroup
- logs:CreateLogStream
- logs:PutLogEvents
resources:
- arn:aws:logs:*:*:*
Specifying the Deployment Package
AWS Lambda expects source code to be provided as a deployment package whose structure varies depending on which runtime
is in use. See Runtimes for the valid values of runtime
. The expected structure of the deployment package can be found in the AWS Lambda documentation for each runtime. Once you have created your deployment package you can specify it either directly as a local file (using the filename
argument) or indirectly via Amazon S3 (using the s3_bucket
, s3_key
and s3_object_version
arguments). When providing the deployment package via S3 it may be useful to use the aws.s3.BucketObjectv2
resource to upload it. For larger deployment packages it is recommended by Amazon to upload via S3, since the S3 API has better support for uploading large files efficiently.
Import
Using pulumi import
, import Lambda Functions using the function_name
. For example:
$ pulumi import aws:lambda/function:Function test_lambda my_test_lambda_function
Properties
Amazon Resource Name (ARN) of the AWS Key Management Service (KMS) key that is used to encrypt environment variables. If this configuration is not provided when environment variables are in use, AWS Lambda uses a default service key. If this configuration is provided when environment variables are not in use, the AWS Lambda API does not save this configuration and the provider will show a perpetual difference of adding the key. To fix the perpetual difference, remove this configuration.
List of Lambda Layer Version ARNs (maximum of 5) to attach to your Lambda Function. See Lambda Layers
Amount of memory in MB your Lambda Function can use at runtime. Defaults to 128
. See Limits
AWS no longer supports this operation. This attribute now has no effect and will be removed in a future major version. Whether to replace the security groups on associated lambda network interfaces upon destruction. Removing these security groups from orphaned network interfaces can speed up security group deletion times by avoiding a dependency on AWS's internal cleanup operations. By default, the ENI security groups will be replaced with the default
security group in the function's VPC. Set the replacement_security_group_ids
attribute to use a custom list of security groups for replacement.
Amount of reserved concurrent executions for this lambda function. A value of 0
disables lambda from being triggered and -1
removes any concurrency limitations. Defaults to Unreserved Concurrency Limits -1
. See Managing Concurrency