需含gcloud与yarn的Cloud Build构建器,解决NX Monorepo增量部署问题
解决NX Monorepo Cloud Build部署时yarn与gcloud环境冲突问题
问题根源:gcr.io/cloud-builders/gcloud镜像仅包含Google Cloud SDK工具,没有预装Node.js和yarn,因此执行yarn nx affected -t deploy时会提示bash: yarn: No such file or directory。以下是三种可行的解决办法:
方案一:在Node镜像中安装gcloud SDK
直接在已包含yarn的Node镜像内安装gcloud组件,无需切换镜像:
steps: - name: node:16-bullseye entrypoint: yarn args: ["install", "--frozen-lockfile"] - name: node:16-bullseye entrypoint: yarn args: ["nx", "affected", "-t", "build"] - name: node:16-bullseye entrypoint: bash args: - -c - | # 安装gcloud SDK依赖 echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg add - apt-get update && apt-get install -y google-cloud-sdk # 执行NX变更应用部署 yarn nx affected -t deploy
优缺点:无需额外维护镜像,但每次构建都要重新安装gcloud,会增加构建时长。
方案二:拆分步骤,分别用对应镜像执行
先在Node镜像中获取变更应用列表,再用gcloud镜像逐个部署:
steps: - name: node:16-bullseye entrypoint: yarn args: ["install", "--frozen-lockfile"] - name: node:16-bullseye entrypoint: bash args: - -c - | yarn nx affected -t build # 导出变更应用列表到文件 yarn nx affected:apps --plain > affected-apps.txt - name: "gcr.io/cloud-builders/gcloud" entrypoint: bash args: - -c - | # 循环读取应用列表并部署 while read app; do cp "apps/$app/app.yaml" "dist/apps/$app" gcloud app deploy "dist/apps/$app/app.yaml" done < affected-apps.txt
优缺点:利用各镜像的优势,构建速度更快,但需要自行处理应用列表的读取和路径匹配逻辑。
方案三:构建包含Node、yarn和gcloud的自定义镜像
一次性打包好所需环境的镜像,后续构建直接复用:
- 创建
Dockerfile:
FROM node:16-bullseye # 安装gcloud SDK RUN echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | tee -a /etc/apt/sources.list.d/google-cloud-sdk.list RUN curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key --keyring /usr/share/keyrings/cloud.google.gpg add - RUN apt-get update && apt-get install -y google-cloud-sdk # 确保yarn可用 RUN npm install -g yarn
- 构建并推送镜像到GCR:
gcloud builds submit --tag gcr.io/你的项目ID/node-gcloud-yarn:16 .
- 修改
cloudbuild.yaml使用自定义镜像:
steps: - name: gcr.io/你的项目ID/node-gcloud-yarn:16 entrypoint: yarn args: ["install", "--frozen-lockfile"] - name: gcr.io/你的项目ID/node-gcloud-yarn:16 entrypoint: yarn args: ["nx", "affected", "-t", "build"] - name: gcr.io/你的项目ID/node-gcloud-yarn:16 entrypoint: yarn args: ["nx", "affected", "-t", "deploy"]
优缺点:构建步骤简洁,后续速度快,但需要维护自定义镜像,更新依赖时需重新构建。
注:所有方案中,Cloud Build会自动挂载默认服务账号凭据,无需额外配置gcloud认证。
内容的提问来源于stack exchange,提问作者sev
相关产品推荐
相关产品推荐

