eof
eof

Reputation: 557

Using AwsCustomResource for a large number of resources?

I need a component for creating a large number of CodeCommit users. CloudFormation doesn't support adding a public SSH key for an IAM user, so I have to create my own. CDK comes with AwsCustomResource, which does the heavy lifting of creating the Lambda that handles the required CloudFormation events. In other words, my code would be something like:

import { User } from 'aws-cdk-lib/aws-iam';
import { AwsCustomResource } from 'aws-cdk-lib/custom-resources';
import { Construct } from 'constructs';

export interface CodeCommitUserProps {
  userName: string;
  emailAddress: string;
  sshPublicKey: string;
}

export class CodeCommitUser extends Construct {
  constructor(scope: Construct, id: string, props: CodeCommitUserProps) {
    super(scope, id);
      
    const user = new User(this, 'codecommit-' + props.userName, {
      userName: 'codecommit-' + props.userName,
      path: '/git/users'
    });
  }

  const custom = new AwsCustomResource(this, ... );
}

Now if I call new CodeCommitUser(...) a few hundred times, I would assume that there will be one CloudFormation event Lambda per user, even if all of them are identical. Is there a way to reuse the Lambdas created by AwsCustomResource if I need multiple copies of the custom resource?

Upvotes: 1

Views: 1242

Answers (2)

fedonev
fedonev

Reputation: 25679

I would assume that there will be one CloudFormation event Lambda per user, even if all of them are identical.

Actually, no. CDK creates a single lambda function, no matter how many times CodeCommitUser is instantiated. How does CDK manage this? Under the hood, CDK uses a SingletonFunction for the AWSCustomResource provider (see the github source). Singleton Functions are guaranteed to be added to the stack "once and only once, irrespective of how many times the construct is declared to be part of the stack"

Is there a way to reuse the Lambdas created by AwsCustomResource if I need multiple copies of the custom resource?

Again, reuse happens automagically. You can prove this to yourself by cdk synth-ing the stack with multiple CodeCommitUsers defined. Then look in the cdk.out directory for the outputted CloudFormation template. The template have only one AWS::Lambda::Function resource defined (assuming your app doesn't use lambdas elsewhere).

Upvotes: 2

Tim Schill
Tim Schill

Reputation: 101

You can create your custom resource lambda and deploy it in a separate template. Then you can call on it from what ever template you want. You can call this resource as many times you want from a single template. You can either send a list of users in one go, or create a resource for each user (probably not ideal if you talking hundreds).

Upvotes: 0

Related Questions