Reference dynamic environment variable in run environment section

Hi,
I’m having troubles referencing dynamically created env variable from run command environment section.
I’ve found a few posts addressing this issue but neither of solutions provided there actually work and I thought it would be a good idea after all to sum it up in one single post here.

Below is an example of what I’m trying to archive.

version: 2
jobs:
  build:
    docker:
      - image: buildpack-deps:jessie
    working_directory: ~/project
    steps:
      - checkout
      - run: |
        bar_var="foo-bar"
        echo 'export FOO_ENV_VAR="${bar_var}"' >> $BASH_ENV
      - run:
          command: |
            echo $FOO_ENV_VAR
            ./script.py read_env_variables_here
          environment:
            REF_ENV_1: $FOO_ENV_VAR
            REF_ENV_2: $(echo $FOO_ENV_VAR)
            REF_ENV_3: $(eval echo ${FOO_ENV_VAR})

Python script that gets executed is not getting neither of three env variables.

Does anyone have an idea if that’s me doing smth wrong or it’s a bug or a feature that is not supported.

Thanks.

environment: runs before any commands, so the envs are not going to exist when you run ./script.py read_env_variables_here

It would better to put them in the UI, is there a reason you are trying to do it this way? There may be examples of being able to do it this way on the forums, I would need to look.

That would be a dynamically calculated variable so no way we can pass it via UI.
Just to make sure cause I skipped that part echo $FOO_ENV_VAR is ready the property just fine.
So as a workaround we can pass it as a script parameter but syntax wise yaml reads easier when it is in the list under environment:

I think this is related to how we parse and compile the config before we create the job. I would stick with the workaround for now.

I solved it with Bash (without eval), it’s ugly, but it works. Using it here - unfor19/terraform-monorepo

The trick is to use declare -n which means “create a pointer”.

  1. Store secret name (dynamic) in a temporary variable - AWS_ACCESS_KEY_ID_SECRET_NAME
  2. Set the environment variable by using the reference variable

Here’s how:

jobs:
  terraform-apply:
    machine: true
    steps:
      - checkout
      - run:
          name: terraform-apply
          command: |
            declare -n AWS_ACCESS_KEY_ID_SECRET_NAME=aws_access_key_id_${CIRCLE_BRANCH}
            declare -n AWS_SECRET_ACCESS_KEY_SECRET_NAME=aws_secret_access_key_${CIRCLE_BRANCH}
            export AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID_SECRET_NAME}
            export AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY_SECRET_NAME}
            docker run --rm -w="/code" -e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e CIRCLE_BRANCH -v "${HOME}"/project/:/code/ unfor19/terraform-alpine:0.12.28 /code/scripts/tf-apply-circleci.sh