Search code examples
github-actions

Passing repository environment variables to reusable workflow in Github actions


I have defined few env vars in repository DEV/QA/PROD and have set of variables i.e. a,b,c that I want to pass to the resuable workflow. How to achieve that?

I have tried like below but the variable values are not accessible in the called workflow.

According to GitHub Actions docs:

To reuse variables in multiple workflows, set them at the organization, repository, or environment levels and reference them using the vars context. For more information see "Variables" and "Contexts."

but it doesn't seem to work.

jobs:
  call-workflow-passing-data:
    uses: octo-org/example-repo/.github/workflows/reusable-workflow.yml@main
    with:
      config-path: .github/labeler.yml
      deploy-a: ${{ vars.a}}
      deploy-b: ${{ vars.b }}
    secrets:
      envPAT: ${{ secrets.envPAT }}

In the target workflow, when I use ${{ inputs.deploy-a }} it doesn't give any value.

Any help would be appreciated.


Solution

  • I had this issue myself, and was really struggling to find the cause of this.

    What I discovered was that there was no way to set the environment for the workflow calling the reusable workflow. That means that if you have defined your environment variables for each environment (dev, production, etc), the variables will not be available by using the vars scope.

    My solution was to send environment as parameter to the reusable workflow and the extract the variables using vars there. Not as pretty as I would have liked, but it works.

    From my reusable workflow:

    on:
      workflow_call:
        inputs:
          environment:
            type: string
            required: true
    env:
      deploy-a: ${{ vars.a }}
      deploy-b: ${{ vars.b }}
    jobs:
      do-something:
        environment: ${{ inputs.environment }}
    

    Then you can use ${{ env.deploy-a }} in the remainder of the workflow.