在GitLab CI中使用AWS SAM构建Node.js Lambda报错求助
解决AWS SAM CLI构建Node.js函数时找不到npm的问题
问题原因
你使用的python:3.11镜像默认不包含Node.js环境,通过pip安装的nodejs-bin并非官方标准Node.js发行版,无法正确配置环境变量,导致AWS SAM CLI无法定位到npm二进制文件。
解决方案
方案1:通过apt安装官方Node.js 18.x(推荐)
修改GitLab CI配置的before_script,添加Node.js官方源并安装对应版本:
build_aws_sam: image: python:3.11 stage: build before_script: # 安装依赖工具并添加NodeSource源 - apt-get update && apt-get install -y curl gnupg - curl -fsSL https://deb.nodesource.com/setup_18.x | bash - # 安装Node.js和npm - apt-get install -y nodejs # 安装AWS工具 - pip3 install awscli --upgrade - pip3 install aws-sam-cli --upgrade script: - sam build --config-env "dev"
方案2:通过nvm安装Node.js 18.x(灵活切换版本)
如果需要灵活管理Node.js版本,可使用nvm安装:
build_aws_sam: image: python:3.11 stage: build before_script: # 安装curl工具 - apt-get update && apt-get install -y curl # 安装nvm - curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash # 加载nvm环境变量 - export NVM_DIR="$HOME/.nvm" - [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # 安装并使用Node.js 18.x - nvm install 18 - nvm use 18 # 安装AWS工具 - pip3 install awscli --upgrade - pip3 install aws-sam-cli --upgrade script: - sam build --config-env "dev"
额外检查
报错中提到package.json file not found,请确保你的函数代码目录/builds/xxxx-aws/xxxx-application/serverless/src/populateDynamo下存在package.json文件,否则SAM无法安装函数依赖(即使构建能继续,运行时可能因缺少依赖报错)。
内容的提问来源于stack exchange,提问作者Stéphane GRILLON
相关产品推荐
相关产品推荐

