Deploying AWS CDK in a CodePipeline and CodeBuild workflow

I am currently attempting to deploy an AWS CDK application on AWS CodePipeline using CodeBuild actions.

While the build and deploy processes run smoothly locally (as expected), encountering an issue when running on CodeBuild where the cdk command fails with:

Cannot find module './index'
Subprocess exited with error 1

Despite its likely trivial nature, I can't seem to pinpoint the exact cause!

The project structure is auto-generated using cdk init --language typescript

<>/cdk$ ls
README.md  app  cdk.context.json  cdk.json  cdk.out  jest.config.js  lib  node_modules  package.json  test  tsconfig.json  yarn.lock

The buildspec.yml for the Build stage consists of:

phases:
  build:
    commands:
      - cd ${CODEBUILD_SRC_DIR}/cdk
      - yarn install
      - yarn build
artifacts:
  base-directory: ${CODEBUILD_SRC_DIR}/cdk
  files:
    - '**/*'

The buildspec.yml for the Deploy stage (where the input directory is the artifact from the Build stage i.e. the cdk directory) looks like:

phases:
  install:
    commands:
      - npm install -g aws-cdk
      - cdk --version

  build:
    commands:
      - cd ${CODEBUILD_SRC_DIR} # this is the cdk directory
      - cdk ls
      - cdk deploy app

During the Deploy stage, the Cannot find module './index' error occurs at the cdk ls step. Since the local build/deploy steps work flawlessly (in a clean checkout), the issue seems related to copying artifacts from the Build to Deploy stages. However, I'm having trouble identifying the exact problem. Any suggestions for troubleshooting?

Answer №1

An issue has been identified with CodeBuild, causing all symlinks to break when the artifact is created =>

The error message "Cannot find module './index'" occurs due to a command in your cdk.json file that uses ts-node. When cdk attempts to run it from node-modules/.bin/ts-node, the symlink is broken.

To address this issue, it is recommended to compress the code yourself during the build process. Here is an example of how you can achieve this:

      - yarn build
      - tar -czf /tmp/mycode.tar.gz .
artifacts:
  files:
    - 'mycode.tar.gz'
  discard-paths: true
  base-directory: '/tmp'

Upon deployment, you can decompress the code using the following steps:

...
      - cd ${CODEBUILD_SRC_DIR} # This refers to the cdk directory
      - tar -zxvf mycode.tar.gz
      - cdk ls
      - cdk deploy app

Answer №2

I encountered a similar problem and managed to fix it by including enable-symlinks: yes in my buildspec.yml file.

artifacts:
  enable-symlinks: yes

Answer №3

Do you currently implement Lambda code in CDK? Have you verified the handler being used and its presence at the specified path?

import * as lambda from '@aws-cdk/aws-lambda';
import * as path from 'path';

const fn = new lambda.Function(this, 'MyFunction', {
  runtime: lambda.Runtime.NODEJS_10_X,
  handler: 'dist/index.handler',  <======= Please ensure index.js file is located within the dist directory
  code: lambda.Code.fromAsset(path.join(__dirname, 'lambda-handler')),
});

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

Guide to implementing ES2022 modules within an extension

After making changes in my extension code to test various module types, I decided to modify my tsconfig.json file as follows: { "compilerOptions": { "declaration": true, "module": "ES2022", ...

Issue with useEffect() not receiving prop

Currently diving into the world of React and still in the learning process. I recently integrated a useEffect() hook in my code: import { fetchDetails } from "../../ApiServices/Details"; export interface RemoveModalProps { id: number; i ...

Setting up eslint for your new react project---Would you like any further

I am currently working on a TypeScript-based React application. To start off, I used the following command to create my React app with TypeScript template: npx create-react-app test-app --template typescript It's worth noting that eslint comes pre-co ...

Tips for resolving the 'JSX is not defined no-undef' error post TypeScript 4.4.2 update

Upon upgrading to TypeScript 4.4.2 from TypeScript 3.8.2, I have encountered numerous errors such as error 'x' is not defined no-undef. For instance, one of the errors is error 'JSX' is not defined no-undef. Upon closer inspection, most ...

Utilizing Angular's ngx-bootstrap date range picker for a customized date range filtering system

Currently, I am incorporating ngx-bootstrap's datepicker functionality and utilizing the date range picker. This feature allows users to choose a start and end date. After selecting these dates, my goal is to filter the array(content) based on whethe ...

Why is it advantageous to use Observable as the type for Angular 5 component variables?

Being a beginner in Angular 6, I have been exploring the process of http mentioned in this link: https://angular.io/tutorial/toh-pt6#create-herosearchcomponent One thing that caught my attention was that the heroes array type is set to Observable in the ...

Bring in numerous variables into a Gatsby component using TypeScript and GraphQL Typegen

import { graphql } from 'gatsby'; const Footer = ({phone}: { phone?: Queries.FooterFragment['phone'];}): JSX.Element => { return <footer>{phone}</footer>; }; export default Footer export const query = graphql` fragm ...

Ngrx effects are not compatible with earlier versions of TypeScript, causing issues with functionality

Seeking assistance with my Ionic 3 App utilizing ngrx/store and ngrx/effects. However, upon attempting to run the app, I consistently encounter the following error: TypeScript Error A computed property name in a type literal must directly refer to a bui ...

What is the significance of the colon before the params list in Typescript?

Consider the following code snippet: import React, { FC } from "react"; type GreetingProps = { name: string; } const Greeting:FC<GreetingProps> = ({ name }) => { // name is string! return <h1>Hello {name}</h1> }; Wha ...

There was an error in parsing the module: an unexpected token was encountered during the rendering

Recently, I've been working on configuring React with Typescript (for type checking), Babel for code transpilation, Jest for testing, ESLint for code checking, and a few other tools. You can find all the necessary files in the repository linked below. ...

Transform Material UI Typography to css-in-js with styled-components

Can Material UI elements be converted to styled-components? <Container component="main" maxWidth="XS"> <Typography component="h1" variant="h5"> Sign in </Typography> I attempted this for typography but noticed that t ...

What could be causing the TypeScript exhaustive switch check to malfunction?

How come the default case in the switch statement below does not result in an exhaustive check where 'item' is correctly identified as of type 'never'? enum Type { First, Second } interface ObjectWithType { type: Type; } c ...

If the input matches any of the strings from the web request output, then return true

Can you help me modify this code to detect if the IP address (as a string) stored in the variable const ip_address is present in the output retrieved from the URL specified in const request? function getBlocklist() { const baseurl = "https://raw ...

Troubleshooting connectivity issues between Entities in microORM and Next.js

While trying to run my Next.js application in typescript, I encountered the following error: Error - ReferenceError: Cannot access 'Member' before initialization After consulting the documentation at https://mikro-orm.io/docs/relationships#relat ...

Retrieve information prior to CanActivation being invoked

As I develop a web application utilizing REST to retrieve data (using Spring Boot), the server employs cookies for authenticating logged-in users. Upon user signing in, I store their information in the AuthenticationHolderService service (located in root ...

What advantages does subscribe() offer compared to map() in Angular?

I recently started exploring observables in angular2 and found myself puzzled over the decision to use map() instead of subscribe(). Let's say I am fetching data from a webApi, like so: this.http.get('http://172.17.40.41:8089/api/Master/GetAll ...

The Angular 4 HTTP patch method is encountering difficulties when called in code but functions properly when tested using Post

My attempts to make a patch and post call to the server are failing as it never reaches the server. Interestingly, the same request works flawlessly in Postman, so I suspect there might be an issue with my code. Both my post and patch methods are essentia ...

The issue is that TypeScript is indicating that the type 'string | string[]' cannot be assigned to the type 'string'

I recently upgraded to Angular 16 and encountered an issue with an @Input() property of type string | string[]. Prior to the upgrade, everything was functioning correctly, but now I am experiencing errors. I am uncertain about where I may have gone wrong i ...

The ReferenceError occurs exclusively during the execution of tests

I keep encountering a dull stacktrace after executing my test. I've experimented with solutions like using fakeTimers, require('iconv-lite')..., etc, based on these queries: Encoding not recognized in jest.js ReferenceError: You are trying ...

Managing state within SolidJS components using Immer's "produce" for nested state handling

I've been working on a SolidJS application where I store a large JSON object with nested objects. For undo and redo actions, I'm using Immer to generate patches. Although technically I'm storing a class with multiple layers of nesting, Immer ...