DEV Community

Ryo Kuroyanagi
Ryo Kuroyanagi

Posted on • Updated on

How to set env parameters conditionally in GitHub Actions⚙

Sometimes we want to set environment variables conditionally in GitHub Actions. For instance, setting build parameters of web server depending on setup like staging, acceptance and release. Here, I show an easy way to set environment variables conditionally depending on what git tag is created on a repo in GitHub Actions workflow.

Let's assume that we want to build Docker images and push them to a Docker registry. The trigger to run workflow is git tags. release-XXX tags are for release env and staging-XXX tags are for staging respectively. In actual cases, the tags can be like release-v1.0.1.

on:
  push:
    tags:
      - release-*
      - staging-*
Enter fullscreen mode Exit fullscreen mode

Let's go to env setting steps. I would like to use different Docker image tags for release and staging and set a full Docker image name as an env variable respectively. We can use if grammar to judge if the env is release or staging and echo "VAR=XXX" >> $GITHUB_ENV sentence to set environment variables throughout a job. startsWith is a built-in function which can be used in if.

jobs:
  build:
    name: Build Docker Image
    runs-on: ubuntu-latest
    steps:
      # Pulls my code
      - uses: actions/checkout@v2
      # This step is run when the tag is release-XXX
      - name: Sets env vars for release
        run: |
          echo "DOCKER_IMAGE_NAME=my.docker.repo/awesome-image:release" >> $GITHUB_ENV
        if: startsWith(github.ref, 'refs/tags/release-')

      # This step is run when the tag is staging-XXX
      - name: Sets env vars for staging
        run: |
          echo "DOCKER_IMAGE_NAME=my.docker.repo/awesome-image:staging" >> $GITHUB_ENV
        if: startsWith(github.ref, 'refs/tags/staging-')
Enter fullscreen mode Exit fullscreen mode

Variables are used with env.XXX expression, that is env.DOCKER_IMAGE_NAME in my example. Use ${{ <expression> }} to use the variables.

- name: Build Image
  run: docker build -t ${{env.DOCKER_IMAGE_NAME}} .
Enter fullscreen mode Exit fullscreen mode

That's it. Pretty easy and it's very clean code. By replacing startsWith with endsWith, you can use a tag rule like XXX-staging. If the condition to decide env is very complicated, you may want to write a dedicated step with shell script and set output parameters to detect environment and use the output in if grammar in steps to set env variables.

However, I recommend not to use complicated rule because it makes it hard to manage environments.

Hope you like it! See you :)

Discussion (0)