Using Environment Variables inside a conditional

Is there a possible way to use an environment variable inside a conditional like this? (code below doesn’t work)

 when:
   condition:
     equal: [ $<< parameters.condition_needed>>, "true" ]

I have found the several same questions that was posted years ago but none gave a working solution such as this
and also a feature request here

Hi @stevensim226 - Welcome to the CircleCI community!

It is indeed possible to use parameters in a conditional statement. The correct syntax for the example you shared would be:

- when:
    condition:
      equal: [ true, << parameters.condition_needed >> ]

But in the case of a boolean parameter I would suggest a much simpler syntax:

- when:
    condition: << parameters.condition_needed >>

You can find out more about conditional steps in our documentation.

Hello @yannCI
The problem is that let’s say <<parameters.condition_needed>> is "CONDITION_ONE"
then I have an environment variable $CONDITION_ONE: true

I have an Environment variable (as said in title) whose name is obtained from a parameter. Not just a parameter alone

Hi @stevensim226,

This can be done using the env_var_name parameter type.

You would need to declare a parameter in your job based on the environment variable:

parameters:
  condition_needed:
    default: CONDITION_ONE
    type: env_var_name

Then you’ll be able to use that parameter inside the when step:

- when:
    condition:
      equal: [ true, "${<< parameters.condition_needed >>}" ]

(Edits: Environment variables always have the type string, so you’ll need to use the above syntax + syntax for env_var_name parameters interpolation)

Hi @stevensim226,

I just realized that I referenced another parameter than the env_var_name one in the logic statement of my test run, and therefore wrongly believed the env_var_name parameter could be used in a when step.

Because when statements are evaluated when the configuration is compiled prior to running, and environment variables are determined at runtime, the method I suggested won’t work as is.

However, you can get around this limitation by using pipeline parameters with dynamic config. I would also recommend the “Intro to Dynamic Config via Setup Workflows” Support Solution posted by one of my colleagues.