Dynamically set environment var based on branch name

I want to use the same config.yml file for both my “staging” and “production” builds + deploys. In Github, our “main” branch is for staging, and our “production” branch is for production. I need some way to set an ENV var that can be used in my config.yml file to represent either “staging” or “production” based on the branch being built.

I know I can set this on jobs that I control, but I also use Orb pre-built jobs like pushing a docker image to Amazon:

  - aws-ecr/build-and-push-image:
      requires:
        - build
      tag: staging-rails

I want to be able to replace that “tag” statement above with something like this:

tag: ${MY_BUILD_ENV}-rails

and have logic that sets the env var like this:

if $CIRLCE_BRANCH == "production" then
  $MY_BUILD_ENV = "production"
else
  $MY_BUILD_ENV = "staging"
end

Is there any way to do this sort of dynamic ENV setting, and be able to use it both for my own jobs that I define, as well as in pre-defined Orb jobs? Basically trying to set a global env that I can use anywhere in config.yml.

Any help would be appreciated!

Hi @key88sf ,

You should be able to use pre-steps within the aws-ecr/build-and-push-image job declaration.
This way, you can add your step(s) to set the MY_BUILD_ENV env var value to $BASH_ENV.

See Reusable Config Reference Guide - CircleCI

Aha, this looks like what I need. Will try it out, thanks!

1 Like

awesome!
let us know if that works! :slight_smile:

Yes, this worked great. Thank you.

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.