How to extend environment variables in github actions with existing ones?

Viewed 1920

A step in a job requires the setting of an environment variable. is something like the code example below possible to achieve with github actions?

Example:

- name: Do Something
  env:
      NEW_VAR: $EXISTING_VAR/subdir
      
  run: |
      echo $NEW_VAR
       

I know, that i can directly use the environment variable, but it would be nice to construct new env vars by concatenating old ones.

There is also ${{ env.EXISTING_VAR }}, but it looks like that this expression is not evaluated.

2 Answers

There is another way to set env vars.

Try something like that:

- name: Set env to qa
  run: |
    echo "::set-env name=ENVIRONMENT::qa"

Although this works for me too:

ECS_DOCKER_COMPOSE: "docker-compose-$ENVIRONMENT.yml"

I guess that GitHub actions not work with "/".

Have you tried without slash?

Update 2022

The syntax has changed: ::set-env has been deprecated and is replaced with environment files. This means that you can set the new env variable within run in one step and use it in a subsequent step. The syntax would be:

...
- name: Set env variable
  run: |
    echo "NEW_VAR=${{ env.EXISTING_VAR }}/subdir/${{ env.OTHER_EXISTING_VAR }}" >> $GITHUB_ENV
- name: Use env variable
  run: |
    echo ${{ env.NEW_VAR }}
...

One caveat is that I was unable to set and use a new environment variable within the same step. Here is a non-working example of what I mean

...
- name: Set env variable
  run: |
    echo "VAR_FROM_THE_SAME_STEP=${{ env.EXISTING_VAR }}" >> $GITHUB_ENV
    echo "NEW_VAR=${{ env.EXISTING_VAR }}/subdir/${{ env.VAR_FROM_THE_SAME_STEP }}" >> $GITHUB_ENV
...

Resolving ${{ env.VAR_FROM_THE_SAME_STEP }} will not work in this case, you would need to do it in a subsequent step, which is of course no big deal in most cases.

Related