GitLab not propagating exit codes properly in jobs

Viewed 162

I created a job in .gitlab-ci.yml for basically empty javascript project built with pnpm. The job manifest is:

deploy_npm:
  image: node:16.14.0-bullseye-slim
  stage: deploy
  before_script:
    - npm install -g pnpm@6.32.2
    - pnpm build
  script:
    - pnpm publish
    - echo $?

The problem is that when I'm not creating .npmrc file with correct auth token, and I get Unauthorized error, the job status is still succeeded because exit status is 0. If I'd run the same command in local environment, then the exit status would be 1.

npm notice Publishing to ****************
npm ERR! code E401
npm ERR! 401 Unauthorized - PUT *******************
npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2022-07-08T13_22_44_392Z-debug-0.log
$ echo $?
0
Cleaning up project directory and file based variables
00:01
Job succeeded

The same thing happens for example with FATAL_ERROR in Vite builds (when runner is out of memory), so my assumption is that GitLab has issues with propagating exit codes. Is there any way to fix that? I've tried setting feature flags like FF_ENABLE_BASH_EXIT_CODE_CHECK or FF_USE_NEW_BASH_EVAL_STRATEGY but they didn't help.

1 Answers

You should be careful with using $? directly in your script in gitlab ci, as this will of course show the last error code, but also return a new error equal to 0, which can alter job behavior base on feature flags configuration.

You can try to use a workaround below (both to debug and force exit code value) - it saves exit code to variable, shows its value, and forcibly runs exit with it.

deploy_npm:
  image: node:16.14.0-bullseye-slim
  stage: deploy
  before_script:
    - npm install -g pnpm@6.32.2
    - pnpm build
  script:
    - set +e
    - pnpm publish && exit_code=$? || exit_code=$?
    - set -e
    - echo "command finished with $exit_code"
    - exit $exit_code
Related