redirecting from stderror seems to stop my gitlab-ci script

12/23/2019

I'm having some issues when running a script in my Gitlab CI pipeline.

I'm deploying my services into a Kubernetes cluster, and for this task, I'm trying to see if a particular PersistentVolumeClaim exists.

It took a long time to find out that I need to write from stderr in case the pvc was not found, just to be able to store that error in a variable. I'm sure there must be better ways to achieve the same thing I'm trying to do so I'm open to those suggestions as well.

echo "Checking if given pvc it's still around..."
PVC=$(kubectl get pvc $PVC_TO_RESTORE 2>&1)
echo "redirect from stderror is not the problem"
if echo $PVC | grep -q 'Error from server (NotFound): persistentvolumeclaims'; then
  echo "$PVC_TO_RESTORE seems to have been deleted beforehand. Continuing..."
else
  echo "$PVC_TO_RESTORE must be deleted before restoring!"
  exit 1
fi

The second echo is never printed on console, and my pipeline fails as the following image enter image description here

What's going on in here?

-- Sebastialonso
continuous-integration
gitlab-ci
kubernetes
stderr

1 Answer

12/24/2019

It took a long time to find out that I need to write from stderr in case the pvc was not found

As far as I know, kubectl will exit non-zero when it cannot do what you asked, but in your case you want to exit if it does exist:

if kubectl get -o name pvc $PVC_TO_RESTORE; then
  echo "$PVC_TO_RESTORE must be deleted before restoring!"
  exit 1
fi
echo "$PVC_TO_RESTORE seems to have been deleted beforehand. Continuing..."

I suspect the redirection is consuming some valuable error message, which is another good reason not to use the "echo | grep" pattern.

You can optionally redirect just stdout if having the name in the CI logs bothers you:

if kubectl get -o name ... >/dev/null; then
fi
-- mdaniel
Source: StackOverflow