Sunday 17 September 2023

Passing Environment Variables to Reusable Workflows in GitHub Actions

 We have discueed, that we have to use an environment variable to handle input parameter default values, if we are using trigger for workflow on push in the post "Setting Workflow Environment Variable Based on Input Parameter in GitHub Actions - on workflow_dispatch and Use a Default Value on push". If we have to pass on the input paramter value from a workflow to a reusable workflow, it does not work as expected and it is a limitation of reusable workflows  as explained in here. Let's try to understand with an example how to pass an env variable to a reusable workflow.

We can define a reusable workflow as shown below. The trigger should be set as workflow_call to make a workflow reusable in another workflow. We have defined an input varaible for the reusable workflow as shown below.



Then before we attempt to use the reusable workflow above let's try to pass an input variable to workflow and make it work wiith an envronment variable to ensure it is available to use, when we use on push trigger or on workflow_dispatch trigger as described in the post "Setting Workflow Environment Variable Based on Input Parameter in GitHub Actions - on workflow_dispatch and Use a Default Value on push".


When we run the above workflow it shows that ${{ env.apps }} has a value.


Let's try to pass the same to the reusable workflow and see what happens. As you can see below we can refer to the reusable workflow on the same repo as shown below..


However, when we try to pass env variable to the reusable workflow, the workflow shows an error message The workflow is not valid. .github/workflows/all_apps_cicd.yml (Line: 26, Col: 13): Unrecognized named-value: 'env'. Located at position 1 within expression: env.apps. This is due to the limitations described here in GitHub documentation regarding env variables usage in reusable workflows.


To overcome this issue, as a workaround, we have to use env variable in an additional job, which runs prior to all reusable workflows. In that prerequisite job we have to output the env variable value and use that output variable in the reusable workflow call input, as shown below. The reusable workflow call set to be dependent (using needs job) on the prerequisite env_vars job which is exposing the env variable as output variable. Then we can pass the output using needs.env_vars.outputs.apps to the reusable workflow.



The reusable workflow runs after the env_vars job.


With this workaround we can get the env variable passed to the reusable workflow. The full example code used in this post is available in GitHub here.



No comments:

Popular Posts