Thursday 14 September 2023

Setting Workflow Environment Variable Based on Input Parameter in GitHub Actions - on workflow_dispatch and Use a Default Value on push

 GitHub actions workflows support input ponly on manual trigger workflow_dispatch. What if we need to use default value in other triggers such as on push and use input parameter in case of manual trigger workflow_dispatch? Let's explore our options with an example.

Consider we want to pass list of app names we want to build and deploy in the pipeline as an input parameter. If we want to omit app we should be able to do so while triggering the workflow manually. If pipeline is triggered automatically all apps listed in paramter as default value should be deployed.

We can define input parameter for the pipeline as shwon below. Why below app list defined as a json array syntax? We can discuss the reason in another post. For now lets try to assume the value of all apps should be listed this way.

Then if we try to print this input in our workflow job as shown below it should print the default value.

So what happens if we trigger workflow manually? We can change the default value of the apps parameter.. Notice we have changed invoice-api to order-api (Actual requirement is listing all apps and when we trigger removing names of app we want to omit building and deploying).

In the workflow run we can see the change to input parameter is effective and it can be obtained with  ${{ inputs.apps }}

If we trigger without changing the input parameter value the defualt value is available with 
${{ inputs.apps }}

All looks good above, so what's the problem?

Let's see what happens when the workflow run on a push. We can see on push we do not have a value for the expression  ${{ inputs.apps }}

How to make it work for both push and workflow_dispatch?

We  can use an environment variable at the workflow level and assign it via an expression. Only ceveat is we have to specify the default value for the parameter twice.  GitHub workflow supports bit weired syntax to assign a variable with a condistion, via expression as documented here.

   myvar: ${{ condition && true?value || false?value }}

For the above issue we can create a env variable apps as shown below. We check if the trigger is push then we assign the default value. If it is triggered manually we assign the input parameter value to ensure any changes to input paramter value is taken into consideration. The full workflow code is available in GitHub here.

Now, when change is pushed and workflow is run for on push event, the env variable app containes the defalut value, even though the input apps value is empty.

When we trigger the workflow manually with a change to input it is available to env variable apps. Therefore we can now rely on the env variable to obtain the value for all steps of the workflow.'

No comments:

Popular Posts