CallbackFunction class

A CallbackFunction is a special type of aws.lambda.Function that can be created out of an actual JavaScript function instance. The Pulumi compiler and runtime work in tandem to extract your function, package it up along with its dependencies, upload the package to AWS Lambda, and configure the resulting AWS Lambda resources automatically.

The JavaScript function may capture references to other variables in the surrounding code, including other resources and even imported modules. The Pulumi compiler figures out how to serialize the resulting closure as it uploads and configures the AWS Lambda. This works even if you are composing multiple functions together.

See Function Serialization for additional details on this process.

Lambda Function Handler

You can provide the JavaScript function used for the Lambda Function's Handler either directly by setting the callback input property or instead specify the callbackFactory, which is a Javascript function that will be called to produce the callback function that is the entrypoint for the AWS Lambda. Using callbackFactory is useful when there is expensive initialization work that should only be executed once. The factory-function will be invoked once when the final AWS Lambda module is loaded. It can run whatever code it needs, and will end by returning the actual function that Lambda will call into each time the Lambda is invoked.

It is recommended to use an async function, otherwise the Lambda execution will run until the callback parameter is called and the event loop is empty. See Define Lambda function handler in Node.js for additional details.

Lambda Function Permissions

If neither role nor policies is specified, CallbackFunction will create an IAM role and automatically use the following managed policies:

  • AWSLambda_FullAccess
  • CloudWatchFullAccessV2
  • CloudWatchEventsFullAccess
  • AmazonS3FullAccess
  • AmazonDynamoDBFullAccess
  • AmazonSQSFullAccess
  • AmazonKinesisFullAccess
  • AWSCloudFormationReadOnlyAccess
  • AmazonCognitoPowerUser
  • AWSXrayWriteOnlyAccess

Customizing Lambda function attributes

The Lambdas created by aws.lambda.CallbackFunction use reasonable defaults for CPU, memory, IAM, logging, and other configuration. Should you need to customize these settings, the aws.lambda.CallbackFunction resource offers all of the underlying AWS Lambda settings.

For example, to increase the RAM available to your function to 256MB:

import * as aws from "@pulumi/aws";

// Create an AWS Lambda function with 256MB RAM
const lambda = new aws.lambda.CallbackFunction("docsHandlerFunc", {
    callback: async(event: aws.s3.BucketEvent) => {
        // ...
    },

    memorySize: 256 /* MB */,
});

Adding/removing files from a function bundle

Occasionally you may need to customize the contents of function bundle before uploading it to AWS Lambda --- for example, to remove unneeded Node.js modules or add certain files or folders to the bundle explicitly. The codePathOptions property of CallbackFunction allows you to do this.

In this example, a local directory ./config is added to the function bundle, while an unneeded Node.js module mime is removed:

import * as aws from "@pulumi/aws";
import * as fs from "fs";

const lambda = new aws.lambda.CallbackFunction("docsHandlerFunc", {
    callback: async(event: aws.s3.BucketEvent) => {
        // ...
    },

    codePathOptions: {

        // Add local files or folders to the Lambda function bundle.
        extraIncludePaths: [
            "./config",
        ],

        // Remove unneeded Node.js packages from the bundle.
        extraExcludePackages: [
            "mime",
        ],
    },
});

Using Lambda layers {#lambda-layers}

Lambda layers allow you to share code, configuration, and other assets across multiple Lambda functions. At runtime, AWS Lambda extracts these files into the function's filesystem, where you can access their contents as though they belonged to the function bundle itself.

Layers are managed with the aws.lambda.LayerVersion resource, and you can attach them to as many lambda.Function or lambda.CallbackFunction resources as you need using the function's layers property. Here, the preceding program is updated to package the ./config folder as a Lambda layer instead:

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import * as fs from "fs";

// Create a Lambda layer containing some shared configuration.
const configLayer = new aws.lambda.LayerVersion("config-layer", {
    layerName: "my-config-layer",

    // Use a Pulumi AssetArchive to zip up the contents of the folder.
    code: new pulumi.asset.AssetArchive({
        "config": new pulumi.asset.FileArchive("./config"),
    }),
});

const lambda = new aws.lambda.CallbackFunction("docsHandlerFunc", {
    callback: async(event: aws.s3.BucketEvent) => {
        // ...
    },

    // Attach the config layer to the function.
    layers: [
        configLayer.arn,
    ],
});

Notice the path to the file is now /opt/config/config.json --- /opt being the path at which AWS Lambda extracts the contents of a layer. The configuration layer is now manageable and deployable independently of the Lambda itself, allowing changes to be applied immediately across all functions that use it.

Using layers for Node.js dependencies

This same approach can be used for sharing Node.js module dependencies. When you package your dependencies at the proper path within the layer zip file, (e.g., nodejs/node_modules), AWS Lambda will unpack and expose them automatically to the functions that use them at runtime. This approach can be useful in monorepo scenarios such as the example below, which adds a locally built Node.js module as a layer, then references references the module from within the body of a CallbackFunction:

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";

// Create a layer containing a locally built Node.js module.
const utilsLayer = new aws.lambda.LayerVersion("utils-layer", {
    layerName: "utils",
    code: new pulumi.asset.AssetArchive({

        // Store the module under nodejs/node_modules to make it available
        // on the Node.js module path.
        "nodejs/node_modules/@my-alias/utils": new pulumi.asset.FileArchive("./layers/utils/dist"),
    }),
});

const lambda =  new aws.lambda.CallbackFunction("docsHandlerFunc", {
    callback: async (event: aws.s3.BucketEvent) => {

        // Import the module from the layer at runtime.
        const { sayHello } = await import("@my-alias/utils");

        // Call a function from the utils module.
        console.log(sayHello());
    },

    // Attach the utils layer to the function.
    layers: [
        utilsLayer.arn,
    ],
});

Notice the example uses the module name @my-alias/utils. To make this work, you'll need to add a few lines to your Pulumi project's tsconfig.json file to map your chosen module name to the path of the module's TypeScript source code:

{
    "compilerOptions": {
        // ...
        "baseUrl": ".",
        "paths": {
            "@my-alias/utils": [
                "./layers/utils"
            ]
        }
    },
    // ...
}

{{% examples %}}

Example Usage

{{% example %}}

Basic Lambda Function

import * as aws from "@pulumi/aws";

// Create an AWS Lambda function that fetches the Pulumi website and returns the HTTP status
const lambda = new aws.lambda.CallbackFunction("fetcher", {
    callback: async(event) => {
        try {
            const res = await fetch("https://www.pulumi.com/robots.txt");
            console.info("status", res.status);
            return res.status;
        }
        catch (e) {
            console.error(e);
            return 500;
        }
    },
});

{{% /example %}}

{{% example %}}

Lambda Function with expensive initialization work

import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
import * as express from "express";
import * as serverlessExpress from "aws-serverless-express";
import * as middleware from "aws-serverless-express/middleware";

const lambda = new aws.lambda.CallbackFunction<any, any>("mylambda", {
  callbackFactory: () => {
    const app = express();
    app.use(middleware.eventContext());
    let ctx;

    app.get("/", (req, res) => {
      console.log("Invoked url: " + req.url);

      fetch('https://www.pulumi.com/robots.txt').then(resp => {
        res.json({
          message: "Hello, world!\n\nSucceeded with " + ctx.getRemainingTimeInMillis() + "ms remaining.",
          fetchStatus: resp.status,
          fetched: resp.text(),
        });
      });
    });

    const server = serverlessExpress.createServer(app);
    return (event, context) => {
      console.log("Lambda invoked");
      console.log("Invoked function: " + context.invokedFunctionArn);
      console.log("Proxying to express");
      ctx = context;
      serverlessExpress.proxy(server, event, <any>context);
    }
  }
});

{{% /example %}}

{{% example %}}

API Gateway Handler Function

import * as apigateway from "@pulumi/aws-apigateway";
import { APIGatewayProxyEvent, Context } from "aws-lambda";

const api = new apigateway.RestAPI("api", {
    routes: [
        {
            path: "/api",
            eventHandler: async (event: APIGatewayProxyEvent, context: Context) => {
                return {
                    statusCode: 200,
                    body: JSON.stringify({
                        eventPath: event.path,
                        functionName: context.functionName,
                    })
                };
            },
        },
    ],
});

export const url = api.url;

{{% /example %}} {{% /examples %}}

Constructors

CallbackFunction(String name, {CallbackFunctionArgs? args, CustomResourceOptions? options})
Creates a new CallbackFunction. name The Pulumi resource name. args Arguments used to configure this CallbackFunction. The set of arguments for CallbackFunction. options Resource options controlling this resource's behavior.
CallbackFunction.reference(String urn)
Creates a typed reference to an existing CallbackFunction resource.

Properties

architectures ↔ Output<List<String>?>
Instruction set architecture for your Lambda function. Valid values are ["x8664"] and ["arm64"]. Default is ["x8664"]. Removing this attribute, function's architecture stays the same.
latefinal
arn ↔ Output<String?>
ARN identifying your Lambda Function.
latefinal
capacityProviderConfig ↔ Output<FunctionCapacityProviderConfig?>
Configuration block for Lambda Capacity Provider. See below.
latefinal
childResources Set<Resource>
finalinherited
code ↔ Output
Path to the function's deployment package within the local filesystem. Conflicts with imageUri and s3Bucket. One of filename, imageUri, or s3Bucket must be specified.
latefinal
codeSha256 ↔ Output<String?>
Base64-encoded representation the source code package file. Use this argument to trigger updates when the function source code changes. For OCI, this value is relayed directly from the image digest. For zip files, this value is the Base64 encoded SHA-256 hash of the .zip file. Layers are not included in the calculation. To trigger updates using a non-standard hashing algorithm, use the sourceCodeHash argument instead.
latefinal
codeSigningConfigArn ↔ Output<String?>
ARN of a code-signing configuration to enable code signing for this function.
latefinal
completionSources Map<String, IOutputCompletionSource>
latefinalinherited
deadLetterConfig ↔ Output<FunctionDeadLetterConfig?>
Configuration block for dead letter queue. See below.
latefinal
description ↔ Output<String?>
Description of what your Lambda Function does.
latefinal
durableConfig ↔ Output<FunctionDurableConfig?>
Configuration block for durable function settings. See below. durableConfig may only be available in limited regions, including us-east-2.
latefinal
environment ↔ Output<FunctionEnvironment?>
Configuration block for environment variables. See below.
latefinal
ephemeralStorage ↔ Output<FunctionEphemeralStorage?>
Amount of ephemeral storage (/tmp) to allocate for the Lambda Function. See below.
latefinal
fileSystemConfig ↔ Output<FunctionFileSystemConfig?>
Configuration block for EFS or S3 Files file system. See below.
latefinal
handler ↔ Output<String?>
Function entry point in your code. Required if packageType is Zip.
latefinal
hashCode int
The hash code for this object.
no setterinherited
id ↔ Output<String>
getter/setter pairinherited
imageConfig ↔ Output<FunctionImageConfig?>
Container image configuration values. See below.
latefinal
imageUri ↔ Output<String?>
ECR image URI containing the function's deployment package. Conflicts with filename and s3Bucket. One of filename, imageUri, or s3Bucket must be specified.
latefinal
invokeArn ↔ Output<String?>
ARN to be used for invoking Lambda Function from API Gateway - to be used in aws.apigateway.Integration's uri.
latefinal
isCustom bool
Returns whether this resource is provider-managed.
no setterinherited
isProtected bool
Returns whether this resource is protected from deletion.
no setterinherited
isRemote bool
Whether this resource is registered as remote.
no setterinherited
isResourceReference bool
Whether this instance represents a resource value returned over RPC.
finalinherited
kmsKeyArn ↔ Output<String?>
ARN of the KMS key used to encrypt environment variables. If not provided when environment variables are in use, AWS Lambda uses a default service key. If provided when environment variables are not in use, the AWS Lambda API does not save this configuration.
latefinal
lastModified ↔ Output<String?>
Date this resource was last modified.
latefinal
layers ↔ Output<List<String>?>
List of Lambda Layer Version ARNs (maximum of 5) to attach to your Lambda Function.
latefinal
loggingConfig ↔ Output<FunctionLoggingConfig?>
Configuration block for advanced logging settings. See below.
latefinal
memorySize ↔ Output<int?>
Amount of memory in MB your Lambda Function can use at runtime. Valid value between 128 MB to 32,768 MB (32 GB), in 1 MB increments. Defaults to 128.
latefinal
name ↔ Output<String?>
Unique name for your Lambda Function.
latefinal
packageType ↔ Output<String?>
Lambda deployment package type. Valid values are Zip and Image. Defaults to Zip.
latefinal
publish ↔ Output<bool?>
Whether to publish creation/change as new Lambda Function Version. Defaults to false.
latefinal
publishTo ↔ Output<String?>
Whether to publish to a alias or version number. Omit for regular version publishing. Option is LATEST_PUBLISHED.
latefinal
qualifiedArn ↔ Output<String?>
ARN identifying your Lambda Function Version (if versioning is enabled via publish = true).
latefinal
qualifiedInvokeArn ↔ Output<String?>
Qualified ARN (ARN with lambda version number) to be used for invoking Lambda Function from API Gateway - to be used in aws.apigateway.Integration's uri.
latefinal
region ↔ Output<String?>
Region where this resource will be managed. Defaults to the Region set in the provider configuration.
latefinal
replacementSecurityGroupIds ↔ Output<List<String>?>
List of security group IDs to assign to the function's VPC configuration prior to destruction. Required if replaceSecurityGroupsOnDestroy is true.
latefinal
replaceSecurityGroupsOnDestroy ↔ Output<bool?>
Whether to replace the security groups on the function's VPC configuration prior to destruction. Default is false.
latefinal
reservedConcurrentExecutions ↔ Output<int?>
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.
latefinal
resourceTransforms List<ResourceTransform>
Inherited/explicit async transforms.
no setterinherited
responseStreamingInvokeArn ↔ Output<String?>
ARN to be used for invoking Lambda Function from API Gateway with response streaming - to be used in aws.apigateway.Integration's uri.
latefinal
role ↔ Output<String?>
ARN of the function's execution role. The role provides the function's identity and access to AWS services and resources.
latefinal
roleInstance ↔ Output<String?>
The IAM role assigned to this Lambda function. Will be undefined if an ARN was provided for the role input property.
latefinal
runtime ↔ Output<String?>
Identifier of the function's runtime. Required if packageType is Zip. See Runtimes for valid values.
latefinal
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
s3Bucket ↔ Output<String?>
S3 bucket location containing the function's deployment package. Conflicts with filename and imageUri. One of filename, imageUri, or s3Bucket must be specified.
latefinal
s3Key ↔ Output<String?>
S3 key of an object containing the function's deployment package. Required if s3Bucket is set.
latefinal
s3ObjectVersion ↔ Output<String?>
Object version containing the function's deployment package. Conflicts with filename and imageUri.
latefinal
signingJobArn ↔ Output<String?>
ARN of the signing job.
latefinal
signingProfileVersionArn ↔ Output<String?>
ARN of the signing profile version.
latefinal
skipDestroy ↔ Output<bool?>
Whether to retain the old version of a previously deployed Lambda Layer. Default is false.
latefinal
snapStart ↔ Output<FunctionSnapStart?>
Configuration block for snap start settings. See below.
latefinal
sourceCodeHash ↔ Output<String?>
User-defined hash of the source code package file. Use this argument to trigger updates when the local function source code changes. This is a synthetic argument tracked only by the AWS provider and does not need to match the hashing algorithm used by Lambda to compute the CodeSha256 response value. Out-of-band changes to the source code will not be captured by this argument. To include out-of-band source code changes as an update trigger, use the codeSha256 argument instead.
latefinal
sourceCodeSize ↔ Output<int?>
Size in bytes of the function .zip file.
latefinal
sourceKmsKeyArn ↔ Output<String?>
ARN of the KMS key used to encrypt the function's .zip deployment package. Conflicts with imageUri.
latefinal
tags ↔ Output<Map<String, String>?>
Key-value map of tags for the Lambda function. If configured with a provider defaultTags configuration block present, tags with matching keys will overwrite those defined at the provider-level.
latefinal
tagsAll ↔ Output<Map<String, String>?>
Map of tags assigned to the resource, including those inherited from the provider defaultTags configuration block.
latefinal
tenancyConfig ↔ Output<FunctionTenancyConfig?>
Configuration block for Tenancy. See below.
latefinal
timeout ↔ Output<int?>
Amount of time your Lambda Function has to run in seconds. Defaults to 3. Valid between 1 and 900.
latefinal
tracingConfig ↔ Output<FunctionTracingConfig?>
Configuration block for X-Ray tracing. See below.
latefinal
transformations List<ResourceTransformation>
Inherited/explicit legacy transformations.
no setterinherited
urn ↔ Output<String>
latefinalinherited
useResourceTimeoutForPropagation ↔ Output<bool?>
Whether to apply resource level timeout values while retrying eventually consistent API operations. By default the provider uses a 5 minute timeout to allow for propagation in the Lambda service. When set to true, this default value is replaced with the configurable resource timeouts. Increased timeout values may be useful in highly active accounts, or regions where propagation delays are inconsistent.
latefinal
version ↔ Output<String?>
Latest published version of your Lambda Function.
latefinal
vpcConfig ↔ Output<FunctionVpcConfig?>
Configuration block for VPC. See below.
latefinal

Methods

failId(Object error) → void
Completes this resource ID with an error when registration fails.
inherited
failOutputs(Object error) → void
Completes all output properties with error.
inherited
failUrn(Object error) → void
Completes this resource URN with an error when registration fails.
inherited
getProvider(String moduleMember) → ProviderResource?
Returns provider for moduleMember's package, if configured.
inherited
getResourceName() String
Returns this resource's logical name.
inherited
getResourceType() String
Returns this resource's Pulumi type token.
inherited
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
registerOutput<T>(String propertyName, {Object? decoder(Object?)?, bool isSecret = false}) → Output<T>
Registers a dynamic output property for this resource.
inherited
resolveId(String? value, {required bool isKnown}) → void
Resolves the provider-assigned ID for this resource.
inherited
resolveOutputs(Struct outputs) → void
Resolves all output properties from a monitor response payload.
inherited
resolveUrn(String value) → void
Resolves this resource's URN once assigned by the engine.
inherited
serializeProperties(Map<String, dynamic> properties) Future<Struct>
Serializes resource properties for RPC transmission.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited