githubcontinuous-integrationgithub-actionscontinuous-deployment

How to pass environment variables to a reusable workflow in Github Actions


In the GitHub actions console I have an environment created for my workflow. This environment has certain variables like account_number etc. I want to pass this value into the resuable workflow.

name: Deploying Lambda

on:
  pull_request:
    types: [closed]
    branches:
      - 'dev'

jobs:

 unit-tests-execution:
 # job details here

 my-job:
   needs: unit-tests-execution
   uses: myorg/myrepo/.github/workflows/reusable.yml@v1.0.0
   with:
     ACCOUNT: <assign the variable account_number from the DEV environment here>

How to assign the variable account_number saved in the DEV environment created in the Github console to the reusable workflow input variable ACCOUNT?

If I do this below I get an error saying environment: can't be used with uses:

 my-job:
   needs: unit-tests-execution
   environment: DEV
   uses: myorg/myrepo/.github/workflows/reusable.yml@v1.0.0
   with:
     ACCOUNT: ${{ vars.account_number}}

I don't want to set the environment in the reusable.yml workflow because that workflow will be used for different accounts and should have just the account number passed in.


Solution

  • Variables don't propagate into the called workflows, but you can use workflow inputs and pass the values in using with.

    I have created and tested this minimal example illustrating the technique:

    .github/workflows/reusable.yml:

    name: Worflow with input
    on:
      workflow_call:
        inputs:
          my-arg:
            required: true
            type: string
    
    jobs:
      print_input:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - name: display my arg
            run: echo ${{ inputs.my-arg }}
    

    .github/workflows/reuser.yml:

    name: reuser
    on:
      - push
    jobs:
      reuser:
        uses: ./.github/workflows/reusable.yml
        with:
          my-arg: top level reuser
    

    My sources are the GitHub Actions manual: