can someone guide me on how to add an existing lambda layer to a gen 2 amplify function? I couldn't find any reference to do this in their documentation, but I have found some external references that has helped:
To clarify, I have an existing lambda layer from a different project that I want to reuse and is already deployed on the console. Now, I just want to attach it to an amplify gen 2 function in backend.ts
. However, the examples above are using either a local path to a layer or classes, which I don't think is applicable in my situation. I can't use a local path as the layer code is in a different repo, and I don't know how to use classes in conjunction with AWS amplify's backend code.
Here is how my attempt to add a lambda layer looks like:
import { defineBackend } from '@aws-amplify/backend'
import { auth } from './auth/resource'
import { data } from './data/resource'
import { myFunc} from './functions/MyFunc/resource'
import * as lambda from 'aws-cdk-lib/aws-lambda'
import { Stack } from 'aws-cdk-lib'
const backend = defineBackend({
auth,
data,
myFunc,
})
const myFuncLambda = backend.myFunc.resources.lambda as lambda.Function
const layerVersion = lambda.LayerVersion.fromLayerVersionArn(
Stack.of(myFuncLambda),
'myFuncLayer',
'arn:aws:lambda:{AWS::REGION}:{AWS::ACCOUNTID}:layer:{AWS::LAYERNAME}:{AWS::LAYERVERSION}'
)
myFuncLambda.addLayers(layerVersion)
Edit: For further clarification, the code I provided does not work when deploying to amplify. I get this error message when I try to deploy:
NodeJSFunctionConstructInitializationError: Failed to instantiate nodejs function construct
This is how added lambda layer in my Amplify Gen2 App.
import { defineBackend } from '@aws-amplify/backend';
import { auth } from './auth/resource';
import { data } from './data/resource';
import { storage } from './storage/resource';
import { generateThumbnail } from './functions/generate-thmbnail/resource';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import 'dotenv/config'
var sharpLambdaLayerArn = process.env.SHARP_LAMBDA_LAYER_ARN;
var ffmpegLambdaLayerArn = process.env.FFMPEG_LAMBDA_LAYER_ARN;
if (!sharpLambdaLayerArn || !ffmpegLambdaLayerArn) {
throw new Error('Missing required environment variables');
}
const backend = defineBackend({
auth,
data,
storage,
generateThumbnail
});
// Add the Sharp Layer to the generateThumbnail function
const generateThumbnailLambda = backend.generateThumbnail.resources.lambda as lambda.Function
const sharpLambdaLayer = lambda.LayerVersion.fromLayerVersionArn(generateThumbnailLambda, "SharpLayer", sharpLambdaLayerArn)
generateThumbnailLambda.addLayers(sharpLambdaLayer)