Home > Mobile >  How to import and call a lambda function with aws-lambda in aws cdk?
How to import and call a lambda function with aws-lambda in aws cdk?

Time:06-20

I am creating an S3 stack using cdk and wanted to give already existing graphQL stack it's permission.My code looks like as follows.

File1 : Graphqlstack.ts

const graphqlHandler = new lambda.Function(this, "graphqlHandler", {
  runtime: lambda.Runtime.GO_1_X,
  functionName: `${STAGE}-graphql`,
  code: lambda.Code.fromAsset(Path.join("..", "bin")),
  handler: "graphql",
  tracing: Tracing.ACTIVE,
  timeout: Duration.seconds(60),
  memorySize: 512,
  vpc: vpc,
  vpcSubnets: {
    subnets: vpc.privateSubnets,
  },
  securityGroups: [vpcSecurityGroup],
});

and this method is exported in the class in which above method resides

new CfnOutput(this, "graphql", {
  value: graphqlHandler.functionName,
  exportName: `${STAGE}-graphql`,
});

File2 : S3Stack.ts

import { App, Duration, Fn, Stack, StackProps } from "aws-cdk-lib";
import * as cdk from "aws-cdk-lib";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as lambda from "aws-cdk-lib/aws-lambda";
const { STAGE } = process.env;

export class S3Stack extends Stack {
  constructor(scope: App, id: string, props: StackProps) {
    super(scope, id, props);
    const s3Bucket = new s3.Bucket(this, `${STAGE}TestFiles`, {
      bucketName: `${STAGE}-test-files`,
      publicReadAccess: true,
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      autoDeleteObjects: true,
      encryption: s3.BucketEncryption.S3_MANAGED,
      versioned: false,
    });

    const graph = Fn.importValue(`${STAGE}-graphql`);
    const graphLambda = lambda.functionName(graph);
    s3Bucket.grantWrite(graphLambda);
  }
}

Just after import,the place where I am calling my Lambda function using lambda.It gives error Property 'functionName' does not exist on type. Did you mean 'FunctionBase'?

Looking around documentation and available articles on how to call imported Method in correct way,but could not found the solution.

CodePudding user response:

The aws-cdk-lib/aws-lambda package doesn't export a function called functionName which is what you are trying to use.

I think you probably meant to use fromFunctionName

const graph = Fn.importValue(`${STAGE}-graphql`);
const graphLambda = lambda.Function.fromFunctionName(this, `${STAGE}-graphql`, graph);
s3Bucket.grantWrite(graphLambda);
  • Related