Search code examples
githubenvironment-variablesgithub-actions

How do I dynamically set an environment variable in a composite action step?


In a composite action, I've tried many different ways of setting environment variables. The only way I've found to do it is to use env inside a step itself:

runs:
  using: "composite"
  steps:
    - name: "A step"
      env:
        BRANCH_REF: "${{ github.ref }}"
      run: echo "The branch is $BRANCH_REF"
      shell: bash

Unfortunately, I need to set this variable dynamically. In a regular action, I would have done something like:

    env:
      FOO: "${{ secrets.FOO }}"
    #...
    - run: echo "FOO=${{ github.event.inputs.foo }}" >> $GITHUB_ENV
      if: ${{ github.event.inputs.foo != '' }}

Since I can't do that, I've tried a bunch of other ways that all haven't worked. This was my latest attempt, which also doesn't work:

    - name: "A step"
      run: |
        if ${{ github.event.inputs.foo != '' }}
        then
          echo "Set from manual input: ${{ github.event.inputs.foo }}"
          echo "FOO=${{ github.event.inputs.foo }}" >> $GITHUB_ENV
        else
          echo "Use FOO workflow secret input: ${{ inputs.FOO }}"
          echo "FOO=${{ inputs.FOO }}" >> $GITHUB_ENV
        fi
        echo "foo is $FOO"
      shell: bash

The output I get in the GitHub console is:

Run if true
  if true
  then
    echo "Set from manual input: My foo is a good foo"
    echo "FOO=My foo is a good foo" >> $GITHUB_ENV
  else
    echo "Use FOO secret: ***"
    echo "FOO=***" >> $GITHUB_ENV
  fi
  echo "foo is $FOO"
  shell: /usr/bin/bash --noprofile --norc -e -o pipefail {0}
Set from manual input: My foo is a good foo

foo is 

On that final output line, I get foo is , so it seems the environment variable $FOO is not getting set.

How can I dynamically set the environment variable in my composite action?


Solution

  • The issue you're hitting is that calling echo "FOO=${{ github.event.inputs.foo }}" >> $GITHUB_ENV in a GitHub Action script steps does not set that variable within the current step's script, if you expand the env header for the next step you should see your dynamically-set environment variable feeding into that step

    What I usually do is something like this:

    FOO="${{ github.event.inputs.foo }}"
    echo "FOO=${FOO}" >> $GITHUB_ENV
    

    So you set a variable called FOO in the current step's script (making it available on subsequent lines in the same step) AND exports it for future steps