Setting a variable to the contents of a file in Gitlab CI/CD

Categories: Gitlab CI/CD

I have recently been spending some time overhauling my projects' deployment processes, and wanted to simplify how images are determined without having to set versions in multiple locations. Keep it DRY, right!

When working locally, I'm using Vite as a build tool to compile all of my front-end CSS and JS assets. For this process, the version of Node that's used is set in an .nvmrc file that's committed to each repo.

I need to run this same job in each my deployment pipelines, which uses an official Node image to run the same commands:

npm install && vite build

However, I wanted to make sure that the Node image being used matched the same version I am running locally, which I was easily able to do by setting a variable in my .gitlab-ci.yml file:

 NODE_IMAGE: node:16.19.0

The downside is that now I'm maintaining that Node version in two different places, so if I update it for the one I have to remember to update it for the other. In my search for a solution I happened upon a Stackoverflow post for how to set a variable via a bash command, which in turn led me to a Gitlab issue to enable this feature.

After speaking with a colleague (and good mentor and friend), I took another look at accomplishing this in a completely separate job that runs during a prior stage to where the variable is actually needed.

So now, in a prepare stage that runs before any of the others I can grab the contents of that .nvmrc file and (along with the node: prefix) set its value to a variable in the script step, which is then saved to an .env file that's passed along to later jobs using artifacts:reports:dotenv.

 stage: prepare
 when: always
 expire_in: 1 week
 dotenv: vars.env
 - echo "NODE_IMAGE=node:$(cat .nvmrc)" > vars.env

Now that I have that value, I can easily use it when setting the image keyword of the actual build step in that later stage:

"build: js":
 image: $NODE_IMAGE
 stage: build

I'd love to know if this helps anyone else having the same issue, so leave a message below!

comments powered by Disqus