'Give permission to invoke lambda from ECS by cdk

When Invoking lambda from ECS,Permission error comes.

botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the Invoke operation: User: arn:aws:sts::678100228XXX:assumed-role/vw-dev-fargate-stack-TaskDefAdminTaskRoleA25A3679-1K9EPRKUW9TNV/21bdeb6c10b14db4b1515986d946959a is not authorized to perform: lambda:InvokeFunction on resource: arn:aws:lambda:ap-northeast-1:678100228XXX:function:vw-dev-lambda because no identity-based policy allows the lambda:InvokeFunction action

So, I want to add the permission to ECS for accessing lambda.

I set ecs in ecs.ts and lambda in lambda.ts

My current idea is to give the permission to ecs in lambda.ts

in my ecs.ts

const ecsAdminService = new ecs.FargateService(this, "AdminService", {
  cluster,
  taskDefinition:taskDefinitionAdmin,
  desiredCount: 2,
  vpcSubnets:  {subnetType: ec2.SubnetType.PUBLIC },
  assignPublicIp: true,
  securityGroups:[adminServiceSg],
  enableExecuteCommand:true,
  serviceName: "sw-ecs-my-dx-tokyo-jxc-91"
});

in my lambda.ts

const myLambda = new lambda.DockerImageFunction(this, "myLambda", {
  functionName: `vw-${targetEnv}-lambda`,
  vpc:vpc,
  vpcSubnets: {subnetType: ec2.SubnetType.PRIVATE_WITH_NAT },
  timeout: cdk.Duration.minutes(1),
  code: lambda.DockerImageCode.fromEcr(myEcrRepo),
  environment:{

  }
});

# I am making here below.
const ecs = "somehow get the ecs here"
myLambda.grantInvoke(ecs) # Something like this.

Am I correct??

I am stuck with two problems.

How can I get the ecs defined in another file?

How can I give the ecs permission to invoke?

Or ,am I basically wrong?

Any help appreciated. thank you very much.



Solution 1:[1]

This is easily done by passing variables between stacks

For example in some-app

// bin/some-app.ts

import * as cdk from 'aws-cdk-lib';
import { SomeEcsStack } from '../lib/ecs';
import { SomeLambdaStack} from '../lib/lambda'

const app = new cdk.App();
const lmb = new SomeLambdaStack(app, 'SomeLambdaStack'); 
new SomeEcsStack(app, 'SomeEcsStack', {
    lambdaFunc: lmb.lambdaFunc
});

Make your lambda function public

// lib/lambda.ts
import { Duration, Stack, StackProps } from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';

export class SomeLambdaStack extends Stack {
  public readonly lambdaFunc: lambda.Function;  // <-- making it available
  
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    const myLambda = new lambda.DockerImageFunction(this, "myLambda", {
      functionName: `vw-${targetEnv}-lambda`,
      vpc:vpc,
      vpcSubnets: {subnetType: ec2.SubnetType.PRIVATE_WITH_NAT },
      timeout: cdk.Duration.minutes(1),
      code: lambda.DockerImageCode.fromEcr(myEcrRepo),
    });

    this.lambdaFunc = myLambda; // <-- making it available
}

Grant the ecs task definition role permissions to invoke

// lib/ecs.ts
import { Duration, Stack, StackProps } from 'aws-cdk-lib';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import { Construct } from 'constructs';

export interface SomeEcsStackProps extends StackProps {
  readonly lambdaFunc: lambda.Function;   // <-- expect lambda to be passed
}
export class SomeEcsStack extends Stack {
  constructor(scope: Construct, id: string, props?: SomeEcsStackProps) {
    super(scope, id, props);

    const ecsAdminService = new ecs.FargateService(this, "AdminService", {
      cluster,
      taskDefinition:taskDefinitionAdmin,
      desiredCount: 2,
      vpcSubnets:  {subnetType: ec2.SubnetType.PUBLIC },
      assignPublicIp: true,
      securityGroups:[adminServiceSg],
      enableExecuteCommand:true,
      serviceName: "sw-ecs-my-dx-tokyo-jxc-91"
    });
    
    props.lambdaFunc.grantInvoke(taskDefinitionAdmin.taskRole)  // <-- Grant permission to task role
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 whitebear