Bitbucket Pipeline部署SAM Node.js项目报错:无法解析npm路径
解决Bitbucket Pipeline中AWS SAM Build找不到npm的问题
问题根源
你的Deploy步骤使用的amazon/aws-cli基础镜像默认未安装Node.js环境,而sam build处理Node.js runtime的Lambda函数时,需要调用npm解析依赖项,因此触发了路径解析失败的错误。
解决方案
方案一:在Deploy步骤安装Node.js
直接在Deploy步骤的脚本中添加Node.js 20.x的安装命令,确保SAM能找到npm:
修改bitbucket-pipelines.yml的Deploy步骤:
- step: name: Deploy to Dev oidc: true deployment: Development image: amazon/aws-cli script: - export AWS_WEB_IDENTITY_TOKEN_FILE=$(pwd)/web-identity-token - echo $BITBUCKET_STEP_OIDC_TOKEN > $(pwd)/web-identity-token # 安装Node.js 20.x - curl -fsSL https://rpm.nodesource.com/setup_20.x | bash - - yum install -y nodejs - node --version - npm --version - if [[ ! -f "sam-installation/dist/sam" ]]; then echo "SAM CLI not found. Installing..."; yum install -y unzip; curl -Lo aws-sam-cli-linux-x86_64.zip https://github.com/aws/aws-sam-cli/releases/latest/download/aws-sam-cli-linux-x86_64.zip; unzip -q -o aws-sam-cli-linux-x86_64.zip -d sam-installation; ./sam-installation/install; fi - export PATH=$PATH:$(pwd)/sam-installation/dist/ - sam --version - sam build -t template.yml - sam package --output-template-file packaged.yaml --s3-bucket $S3_CLOUDFORMATION_BUCKET - sam deploy --template-file packaged.yaml --stack-name betsy-core --capabilities CAPABILITY_IAM --no-fail-on-empty-changeset --s3-bucket $S3_CLOUDFORMATION_BUCKET
方案二:将SAM Build移到Build步骤(推荐)
利用Build步骤已有的Node.js环境,改用AWS官方的SAM构建镜像(内置Node.js和SAM CLI),避免重复安装依赖,提升CI/CD效率:
修改后的bitbucket-pipelines.yml:
pipelines: branches: dev: - step: name: Build & SAM Package image: public.ecr.aws/sam/build-nodejs20.x script: - npm install - npm run build - sam build -t template.yml - sam package --output-template-file packaged.yaml --s3-bucket $S3_CLOUDFORMATION_BUCKET artifacts: - packaged.yaml - step: name: Deploy to Dev oidc: true deployment: Development image: amazon/aws-cli script: - export AWS_WEB_IDENTITY_TOKEN_FILE=$(pwd)/web-identity-token - echo $BITBUCKET_STEP_OIDC_TOKEN > $(pwd)/web-identity-token - sam deploy --template-file packaged.yaml --stack-name betsy-core --capabilities CAPABILITY_IAM --no-fail-on-empty-changeset --s3-bucket $S3_CLOUDFORMATION_BUCKET
注:
public.ecr.aws/sam/build-nodejs20.x是AWS官方提供的镜像,已预装Node.js 20.x、SAM CLI及相关依赖,无需手动配置。
方案三:跳过SAM Build(适用于已完成本地构建的场景)
如果你的Build步骤已经生成了完整的可执行代码(dist目录)和依赖,可以在Deploy步骤使用sam build --skip-build跳过构建步骤,直接使用已有的构建产物:
sam build --skip-build -t template.yml
需确保SAM模板中的CodeUri和Handler路径与已构建的产物匹配。
内容的提问来源于stack exchange,提问作者Sergio2405
相关产品推荐
相关产品推荐

