From c792f8b0b055e7c7486b7ad4e15bdc81a0e5065b Mon Sep 17 00:00:00 2001
From: Bastien Abadie <abadie@teklia.com>
Date: Mon, 28 Mar 2022 15:27:08 +0000
Subject: [PATCH] Do not publish Docker images except on main branch

---
 worker-{{cookiecutter.slug}}/ci/build.sh | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)

diff --git a/worker-{{cookiecutter.slug}}/ci/build.sh b/worker-{{cookiecutter.slug}}/ci/build.sh
index 5c0c9b03..f29f50f2 100755
--- a/worker-{{cookiecutter.slug}}/ci/build.sh
+++ b/worker-{{cookiecutter.slug}}/ci/build.sh
@@ -14,15 +14,19 @@ if [ -z "$VERSION" -o -z "$CI_PROJECT_DIR" -o -z "$CI_REGISTRY_IMAGE" ]; then
 	exit 1
 fi
 
-if [ -n "$CI_REGISTRY" -a -n "$CI_REGISTRY_USER" -a -n "$CI_REGISTRY_PASSWORD" ]; then
-	echo Logging in to container registry…
-	echo $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER --password-stdin $CI_REGISTRY
-fi
-
 IMAGE_TAG="$CI_REGISTRY_IMAGE:$VERSION"
 
 cd $CI_PROJECT_DIR
 docker build -f Dockerfile . -t "$IMAGE_TAG"
-if [ -n "$CI_REGISTRY" ]; then
-	docker push "$IMAGE_TAG"
+
+# Publish the image on the main branch or on a tag
+if [ "$CI_COMMIT_REF_NAME" = "main" -o -n "$CI_COMMIT_TAG" ]; then
+  if [ -n "$CI_REGISTRY" -a -n "$CI_REGISTRY_USER" -a -n "$CI_REGISTRY_PASSWORD" ]; then
+    echo $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER --password-stdin $CI_REGISTRY
+    docker push $IMAGE_TAG
+  else
+    echo "Missing environment variables to log in to the container registry…"
+  fi
+else
+  echo "The build was not published to the repository registry (only for main branch or tags)…"
 fi
-- 
GitLab