Set env values conditionally

I want to set env variables based on input parameter. However, the variables are not available in steps following the definitions.

    - uses: actions/checkout@v2
    - name: set environment variables
      run: |
        if [[ github.event.inputs.env_name == "dev" ]]; then 
          echo "ENVIRONMENT_NAME=${{ secrets.DEV_ENVIRONMENT_NAME }}" >> $GITHUB_ENV
          echo "KUBE_CONFIG=${{ secrets.DEV_KUBE_CONFIG }}" >> $GITHUB_ENV
          echo "KUBE_CONTEXT=${{ secrets.DEV_KUBE_CONTEXT }}" >> $GITHUB_ENV
        elif [[ github.event.inputs.env_name == "qc" ]]; then 
          echo "ENVIRONMENT_NAME=${{ secrets.QC_ENVIRONMENT_NAME }}" >> $GITHUB_ENV
          echo "KUBE_CONFIG=${{ secrets.QC_KUBE_CONFIG }}" >> $GITHUB_ENV
          echo "KUBE_CONTEXT=${{ secrets.QC_KUBE_CONTEXT }}" >> $GITHUB_ENV

    - name: Print ENV
      run: echo env

Variables set in above steps are not listed. It always fails to access any of the variables defined in the block.
What am I missing ?

Resolved it with following approach:

      ENVIRONMENT_NAME: ${{ secrets[format('{0}_ENVIRONMENT_NAME', github.event.inputs.env_name)] }}
      KUBE_CONFIG: ${{ secrets[format('{0}_KUBE_CONFIG', github.event.inputs.env_name)] }}
      KUBE_CONTEXT: ${{ secrets[format('{0}_KUBE_CONTEXT', github.event.inputs.env_name)] }}

Thanks to examples in Go crazy with GitHub Actions - Sander Knape

1 Like

Your problem in the original attempt is in this code:

if [[ github.event.inputs.env_name == "dev" ]]; then 

(and the same in the elif). You’re comparing the literal string “github.event.inputs.env_name”, not the value of the input, so neither case runs. If you had added an else clause like

  echo "::error::Unrecognized env_name"
  exit 1

it would have been a little more obvious where it was going wrong.

To substitute the value of the input into the script, you need to do like

if [[ ${{ github.event.inputs.env_name }} == "dev" ]]; then 

Although personally I’m always wary of substituting text directly into the bash script, as it seems too easy to accidentally break if the value is ever something unexpected. So I’d prefer to do like

  ENV_NAME: ${{ github.event.inputs.env_name }}
run: |
  if [[ $ENV_NAME == "dev" ]]; then
1 Like