How to Set Variable Within 'Script' Section of Gitlab-Ci. Yml File
I Am Trying to Set an Environment Variable for My Gitlab Runner Based on the Branch That the Commit Originated From. I Have 4 Kubernetes Clusters: Staging...
I am trying to set an environment variable for my GitLab Runner based on the branch that the commit originated from.
I have 4 kubernetes clusters: staging, integration, production, and qa. Essentially I want to deploy my application to the proper cluster based on the branch I am pushing to.
image: google/cloud-sdk:latest
variables:
DOCKER_HOST: tcp://docker:2375/
DOCKER_DRIVER: overlay2
services:
- docker:dind
before_script:
- docker info
stages:
- publish
publish:
stage: publish
script:
- if [ "$CI_COMMIT_REF_NAME" = "master" ]; then $ENVIRONMENT="production"; else $ENVIRONMENT="$CI_COMMIT_REF_NAME"; fi
- echo $ENVIRONMENT
.
.
.
- kubectl apply -f cfg/${ENVIRONMENT}/web-deployment.yaml
only:
- master
- integration
- qa
- staging
Any time I run my script with a different form of the if statement I get the following error:
/bin/bash: line 83: =integration: command not found
ERROR: Job failed: exit code 1
So from what I can tell the variable is being set, but the script exits. I've seen several SO questions related to this problem, but nothing about how to set a variable and then continue a script. How can I fix this issue?
1 Answer
The comment above helped me figure it out. So I use a VERSION file that right now contains 0.0.0 which I manipulate to create other variables
# determine what branch I am on
- if [ "$CI_COMMIT_REF_NAME" = "master" ]; then ENVIRONMENT="qa"; else ENVIRONMENT="$CI_COMMIT_REF_NAME"; fi
# determine patch number for semver
- PATCH=`git log --pretty=oneline | wc -l | sed -e 's/^[[:space:]]*//'`
- VERSION=`cat VERSION`
# drop trailing 0 from VERSION
- VERSION=${VERSION%?}
# set all env variables
- TAG="${VERSION}${PATCH}"
- IMAGE="${TAG}-${ENVIRONMENT}" # used for Kubernetes
- API_HOST=""
- WEB_HOST=""
# pass enviornment variables to make
- ENVIRONMENT="$ENVIRONMENT" IMAGE="$IMAGE" API_HOST="$API_HOST" WEB_HOST="$WEB_HOST" make
# make has a step that calls sed and replaces text inline in this file to prepare Kubernetes
- kubectl apply -f cfg/web-deployment.yaml
# create a tag in the repo after deployment is done
- curl -X POST --silent --insecure --show-error --fail ""