Issue with CDK pipeline: Unable to configure lambda layer across various stages in the pipeline stack

When trying to set multiple stages with the same stack in a CDK pipeline, I encountered an error during bootstrapping of my CDK project:

C:\dev\aws-cdk\node_modules\aws-cdk-lib\aws-lambda\lib\code.ts:185
      throw new Error(`Asset is already associated with another stack '${cdk.Stack.of(this.asset).stackName}'. ` +
            ^
Error: Asset is already associated with another stack 'msm-customer'. Create a new Code instance for every stack.
    at AssetCode.bind (C:\dev\aws-cdk\node_modules\aws-cdk-lib\aws-lambda\lib\code.ts:185:13)
    at new LayerVersion (C:\dev\aws-cdk\node_modules\aws-cdk-lib\aws-lambda\lib\layers.ts:124:29)
    at new CustomerStack (C:\dev\aws-cdk\lib\CustomerStack.ts:22:17)

Upon investigating the code, I discovered that the issue was caused by the layer declaration in the "CustomerStack" file. If I either comment out the layer section or only keep one stage in the pipeline, the bootstrap command executes successfully.

Pipelinestack.ts

 // Creates a CodeCommit repository called 'CodeRepo'
        const repo = new codecommit.Repository(this, 'CodeRepo', {
            repositoryName: "CodeRepo"
        });

        const pipeline = new CodePipeline(this, 'Pipeline-dev', {
            pipelineName: 'Pipeline-dev',
            synth: new CodeBuildStep('SynthStep-dev', {
                //role: role,
                input: CodePipelineSource.codeCommit(repo, 'master'),
                installCommands: [
                    'npm install -g aws-cdk'
                ],
                commands: [
                    'npm ci',
                    'npm run build',
                    'npx cdk synth'
                ],
                
            })
        });

        pipeline.addStage(new PipelineStage(this, 'dev'));
        pipeline.addStage(new PipelineStage(this, 'uat'));
        pipeline.addStage(new PipelineStage(this, 'prod'));

PipelineStage.ts

export class PipelineStage extends Stage {
    constructor(scope: Construct, id: string, props?: StageProps) {
        super(scope, id, props);

        new CustomerStack(this, 'msm-customer-' + id, {
            stackName: 'msm-customer'
            env: {
                account: process.env.ACCOUNT,
                region: process.env.REGION,
            },
        });
    }
}

CustomerStack.ts

import { Duration, Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import 'dotenv/config';

export class CustomerStack extends Stack {
    constructor(scope: Construct, id: string, props?: StackProps) {
        super(scope, id, props);

        //define existing role
        const role = iam.Role.fromRoleArn(this, 'Role',
            `arn:aws:iam::${Stack.of(this).account}:role/` + process.env.IAM_ROLE,
            { mutable: false },
        );

        //define layer
        const layer = new lambda.LayerVersion(this, 'msm-layer', {
            code: lambda.Code.fromAsset('resources/layer/customer'),
            description: 'Frontend common resources',
            compatibleRuntimes: [lambda.Runtime.NODEJS_14_X],
            removalPolicy: cdk.RemovalPolicy.DESTROY
        });

        const lambdaDefault = new lambda.Function(this, 'default', {
            runtime: lambda.Runtime.NODEJS_14_X,
            code: lambda.Code.fromAsset('resources/lambda/customer/default'),
            handler: 'index.handler',
            role: role,
            timeout: Duration.seconds(20),
            memorySize: 256,
            layers: [layer],
            allowPublicSubnet: true,
            vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC }
        });

        //rest of the code
    }
}

Answer №1

When creating three stacks with the same name (msm-customer), it is important to note that deploying all three to the same environment (account/region) will not work.

To address this issue, consider the following options:

  1. Avoid specifying stackName and allow CloudFormation to generate unique values for you automatically.
  2. Use unique values by specifying something like 'msm-customer-' + id.
  3. If possible, deploy the stacks to different environments.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Include a new module in the declarations NgModule utilizing ts-morph

Currently, I am utilizing the ts-morph library and my objective is to add a new component to the declarations: This is my initial setup: @NgModule({ declarations: [], imports: [], providers: [], }) Here is what I am aiming for: @NgModule({ declarations: [ ...

Why does the final value appear when passing an incrementing counter as a prop to multiple React Components created in a loop?

I am currently unraveling the concept of closures in JavaScript. Within this code snippet, I am cycling through the values of the 'items' array using a foreach loop. I have defined a let variable named "count" outside the scope of the loop. Afte ...

Update 2020: The data pathway ".builders['app-shell']" must include the mandatory property 'class'

Having exhausted all options in various forums, including StackOverflow, without success. Tried and failed: npm uninstall @angular-devkit/build-angular npm cache clean -f npm install @angular-devkit/build-angular Deleted the node_modules folder and ...

Why is it that a static variable cannot be accessed using the `this` keyword in a static method when the static method is called in any route's controller in NODEJS?

Is it possible to access static variables in a static method using the 'this' keyword? The answer is yes, but there seems to be an issue when passing that static method in any route. The 'this' keyword refers to the class, yet its value ...

Can we verify the availability of an Angular library during runtime?

I am in the process of creating a custom Angular library, let's name it libA, which has the capability to utilize another Angular library, named libB, for an optional feature. Essentially, if the Angular application does not include libB, then the fea ...

Expand the font manually

Is there a way to define a type that represents the widened version of another type? Consider the following scenario: function times<A extends number, B extends number>(a: A, b: B): A & B; The intention behind this times function is to preserv ...

Leverage JSON files for pagination in NextJS

I am currently developing a science website where the post URLs are stored in a static JSON file. ScienceTopics.json- [ { "Subject": "Mathematics", "chapters": "mathematics", "contentList": [ ...

I encountered an issue stating "The state contains a value that is not serializable," specifically related to data retrieved from a Calendar component

Encountering an error in the app stating that a non-serializable value has been detected in the state, particularly related to the date format from the Calendar component in PrimeReact. Researching the issue suggests that the problem lies in the property h ...

Setting up a bi-directional binding to an empty or new object that is a valid reference

What is the proper way to set up binding to a class object with all properties valid but empty? Success...If the component is defined like this: export class BioComponent implements OnInit { bio : Bio = { id : 1, FirstName : "", LastName : ""}; con ...

Executing observables consecutively in Angular without delay

Here are the service calls that I have available: productService.GetAllProducts() productService.DeleteProduct() productService.GetCategories() productService.DeleteCategory() In pseudo code, I need to perform the following steps in my component: ...

The back button in the Chrome browser fails to trigger a page refresh within an Angular application

The code snippet above was used in an attempt to refresh the page when the back button is pressed, but it only works inconsistently in Chrome. The issue seems to be that despite correctly detecting the back button press, the page does not always refresh ...

Issue with validating the date picker when updating user information

Trying to manage user accounts through a dialog form for adding and updating operations, where the type of operation is determined by a variable injected from the main component. Encountered an issue while launching the update process - the date picker tri ...

Having trouble with Primeicons not displaying correctly in the tree component

Take a look at my code: https://github.com/d1rtyW0lf/aqp-regroupement Here are the styles I'm using: "styles": [ "node_modules/primeicons/primeicons.css", "node_modules/primeng/resources/primeng.min.css", "node_modules/primeng/resour ...

The AWS Lambda function encountered an error while attempting to load the 'Argon2PasswordHasher' algorithm library

When deploying my backend application with Zappa, I can successfully login to the /admin page while running locally on OSX 10.14.2. However, when I try to deploy on AWS Lambda, the endpoint works fine but /admin/ returns the error message: Couldn't ...

Leveraging TypeScript with Angular components

Situation: On my website, I have a section called the "main page" where all available books are displayed. The "main page" is represented by the blue box in the image provided and serves as a key component on my site. Additionally, there is a separate co ...

Learn how to calculate and showcase time discrepancies in minutes using Angular2

I am currently working on an Angular app that displays orders using the *ngFor directive. Each order has a datetime field indicating the date it was created. My goal is to implement a timer that shows how long a customer has been waiting for their order ...

How to Validate Ionic 2 Radio Button Selections with TypeScript

Imagine having a list like the one shown below: <ion-list radio-group [(ngModel)]="autoManufacturers"> <ion-list-header> Auto Manufacturers </ion-list-header> <ion-item> <ion-label>Cord</ion-label> &l ...

Retrieve objects from an array that contain a certain specified key

I am trying to extract the objects from All_reports that contain the key: comentarioAdmin. Currently, I am retrieving all reports from All_reports, but I only want the reports that have the key comentarioAdmin. Thank you! getReports() { this.Service.g ...

Developing in TypeScript with styled-components allows for seamless integration between

New to TypeScript and seeking guidance. I currently have a component utilizing styled-components that I want to transition to TypeScript. import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-comp ...

How to retrieve a component's property within an Angular2 provider?

As a beginner in OOP, I am currently experimenting with Ionic 2, Angular 2, and TypeScript. In my home.html file, I have an input field connected to the username property in home.ts as shown below: export class HomePage { public username: string; public n ...