Cannot use environment variables in workflow condition

Hello

Currently we are in the process of enhancing our pipelines and we would like to apply the following scenario:

  • store an environment variable in the project or in a context. Example: STAGING_BRANCH
  • be able to use it in config.yml to decide if a workflow should start or not
    equal: [$STAGING_BRANCH, << pipeline.git.branch >>]

The previous does not work as expected in the last step where we use the env variable in the condition.
Any attempt to store the env variable in a pipeline parameter and use it within the condition also fails.

Is there any way to achieve this ?

Environment variables are expanded at runtime as opposed to compile-time. Because of that, the config.yml would actually evaluate the exact string $STAGING_BRANCH as opposed to the value it contains.

With that said, have you looked into the newly released feature Dynamic Config via Setup Workflows? With this feature, you could create a preliminary workflow that would apply the environment variable and then call your main config.

setup: true
version: 2.1
orbs:
  continuation: circleci/continuation@0.1.3
workflows:
  setup:
    jobs:
      - continuation/continue:
          configuration_path: ".circleci/main.yml"
          parameters: /home/circleci/test.json
          pre-steps:
            - run:
                command: |
                  export TEST_ENV="hello world"
                  echo '{ "staging-branch": "'$STAGING_BRANCH'" }' >> /home/circleci/test.json

In this example, we move the original .circleci/config.yml to .circleci/main.yml and then create a new .circleci/config.yml with the above. In the main.yml, we can then use the following conditional:

equal: [<< pipeline.parameters.staging-branch >>, << pipeline.git.branch >>]

Remember, you’ll also need to declare the parameter in the new main.yml.

parameters:
  staging-branch:
    type: string
1 Like