将GitHub Action重构为并行运行后任务失败是什么原因?
问题根因
GitHub Actions 中每个job默认运行在完全独立的全新虚拟机实例上,needs语法仅用于控制job的执行先后顺序,不会共享前序job的文件系统、安装的软件、启动的服务等资源。你在setup job内完成的拉取代码、安装依赖、启动数据库操作,对后续依赖setup的job完全不可见,所以后续job执行npm命令时找不到package.json文件,直接抛出enoent错误。
解决方案
你可以在每个需要执行代码相关操作的job中补充公共前置步骤,同时搭配依赖缓存降低重复安装的耗时,需要用到PostgreSQL的job单独配置数据库服务即可,修改后的配置参考如下:
name: CI on: push env: DATABASE_URL: "postgresql://postgres:postgres@localhost:5432/postgres" NEXT_PUBLIC_API_HOST: "http://localhost:3000" NEXTAUTH_URL: "http://localhost:3000" NODE_ENV: "test" PORT: "3000" # 定义node_modules缓存规则,避免重复安装依赖 cache_deps: &cache_deps - name: Cache node_modules uses: actions/cache@v3 id: node_modules_cache with: path: node_modules key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }} restore-keys: | ${{ runner.os }}-node- jobs: # 可保留setup做预校验,也可直接删除,按需选择 setup: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - <<: *cache_deps - name: Install dependencies if: steps.node_modules_cache.outputs.cache-hit != 'true' run: npm i type_check: runs-on: ubuntu-latest needs: setup steps: - uses: actions/checkout@v4 - <<: *cache_deps - name: Install dependencies if: steps.node_modules_cache.outputs.cache-hit != 'true' run: npm i - name: Check types run: npm run typecheck lint: runs-on: ubuntu-latest needs: setup steps: - uses: actions/checkout@v4 - <<: *cache_deps - name: Install dependencies if: steps.node_modules_cache.outputs.cache-hit != 'true' run: npm i - name: Run lint run: npm run lint unit_tests: runs-on: ubuntu-latest needs: setup steps: - uses: actions/checkout@v4 - <<: *cache_deps - name: Install dependencies if: steps.node_modules_cache.outputs.cache-hit != 'true' run: npm i - name: Run unit tests run: npm test integration_tests: runs-on: ubuntu-latest needs: setup steps: - uses: actions/checkout@v4 - name: Set up test database uses: harmon758/postgresql-action@v1 with: postgresql version: "11" postgresql db: "postgres" postgresql user: "postgres" postgresql password: "postgres" - <<: *cache_deps - name: Install dependencies if: steps.node_modules_cache.outputs.cache-hit != 'true' run: npm i - name: Apply database schema run: npm run db:push - name: Seed database run: npm run db:seed - name: Build app run: npm run build - name: Integration tests uses: cypress-io/github-action@v2 with: start: npm start wait-on: http://localhost:3000/ - name: Upload screenshots uses: actions/upload-artifact@v4 if: failure() with: name: cypress-screenshots path: cypress/screenshots - name: Upload videos uses: actions/upload-artifact@v4 if: failure() with: name: cypress-videos path: cypress/videos
上述配置用YAML锚点复用了缓存逻辑,依赖仅会在首次没有命中缓存时安装一次,后续所有job都会复用缓存的node_modules,不会额外增加耗时。
内容的提问来源于stack exchange,提问作者parasomnist
相关产品推荐
相关产品推荐

