I have a file which installs some tools which we need. After installation of tools, my sh script is validating the installation and if any tool isn't found then it should fail. I am using this approach in my gitlab-ci file.
The sh script works fine and exit out but when i use it in docker run , docker doesn't exit out with error.
test.sh:
echo "Validating Docker Installation"
which docker
if [ $? -eq 0 ]
then
docker --version | grep "Docker Version"
if [ $? -eq 0 ]
then
echo "Docker installed successfully"
else
echo $?
exit 1
fi
else
echo "Docker didnt installed"
exit 1
fi
gitlab-ci.yml(Test job)
test_job:
stage: test
script:
- docker pull $DOCKER_REGISTRY/$DOCKER_REPO:$BUILD_VERSION
- docker run --rm $DOCKER_REGISTRY/$DOCKER_REPO:$BUILD_VERSION sh ./test.sh
CodePudding user response:
I've tried this on mine and you need to run docker --version | grep "Docker version"
with a lower case 'v'
on Docker version 20.10.5, build 55c4c88
CodePudding user response:
GitLab's jobs will fail any time a job exits with a non-0 status code from the last command. So really, the question you're asking here is "How do I make docker run
return the status code of the script run within the container?" The answer is that you can't - you have to query the status code of the script once the container is done running, then use "exit" to raise that same status code. If you run exit 0
, the job will succeed. If you run exit 1
, it will fail. To put that together with your example, you get the below example, using the docker inspect
command to pull the exit code of the run container, which I've now named test
so we can easily pull the exit code in the next command.
Now, if your container returns a non-0 exit code, the next command will essentially echo that exit code, causing your job to pass or fail based on the status of the run container.
test_job:
stage: test
script:
- docker pull $DOCKER_REGISTRY/$DOCKER_REPO:$BUILD_VERSION
- docker run --name test --rm $DOCKER_REGISTRY/$DOCKER_REPO:$BUILD_VERSION sh ./test.sh
- exit $(docker inspect test --format='{{.State.ExitCode}}')