How can I redirect std error to std out in GitLab runner

Viewed 1733

I'm working on GitLab CI/CD and I'm aware of how to redirect std error to std out in normal cases. It is to use 2>&1 or >/dev/null 2>&1.

Sometimes, I need some commands that throw errors but the errors are not critical. For an example, When I deploy my docker app, I want to stop my old container if it exists and ignore the error which will occur if the container doesn't exist. In such case, I want to just ignore the std error and keep processes to deploy. When I use AWS CodeDeploy, error redirecting by 2>&1 did work but in GitLab CI/CD, it doesn't work.

The following images are the errors which cancle CI/CD processes. Without the command stopping containers which doesn't exist, there is no error and deployment does work.

Question.

How can I redirect std error to std out or ignore the errors and keep deployment in GitLab CI/CD?

enter image description here

enter image description here

1 Answers

From the error it's throwing, the problem isn't with stdout or stderr at all, and your redirection is working properly. The problem is that docker stop is exiting with a non-0 exit code. In *nix systems, every command exits with a numeric code (like exit 0 or exit 1 or exit 986405). The value of the exit code doesn't really matter here, just that it is non-0: an error. Gitlab CI checks the exit code after every command (each line in the before_script, script, and after_script sections) and if any of them are non-0, the job in the pipeline fails. If the job isn't marked with allow_failure: true then the whole pipeline fails.

Try changing that command to this instead:

...
script:
  - pwd
  - docker stop ng >/dev/null 2>&1 || NO_CONTAINER=1 
  - #continues as normal

With this, if the command docker stop ng... fails, we're setting a variable $NO_CONTAINER to the value of 1 which should always end with an exit code of 0, letting the job continue as usual. This doesn't matter at all, and we won't use it, we just need the OR to catch the failure and continue. If the container does exist and it stops correctly, the initial exit code would be 0, so the || never comes into play.

Hope this helps.

Related