Conditional Branching with workflow_dispatch and workflow_call in GitHub Actions

koseimori

kosei

Posted on March 8, 2024

Conditional Branching with workflow_dispatch and workflow_call in GitHub Actions

Introduction

There's a feature in GitHub Actions for reusing workflows. With workflow reuse, you can call another workflow from a workflow.

https://docs.github.com/en/actions/using-workflows/reusing-workflows

In doing so, there was a need to branch depending on whether the called workflow was called from another workflow, or if the workflow was executed standalone. This article describes how to do that.

How to

In GitHub Actions, you can obtain various information from the context at runtime.

https://docs.github.com/en/actions/learn-github-actions/contexts

Among these, there exists a key named github.event.workflow. This value contains the file path of the workflow.

Depending on how it was called, the called workflow can obtain the following values (in the case where workflowA calls workflowB):

When executing workflowB directly (workflow_dispatch), the value of github.event.workflow
The file path of workflowB (.github/workflows/workflow-b.yaml)
When executed from workflowA (workflow_call), the value of github.event.workflow
The file path of workflowA (.github/workflows/workflow-a.yaml)
With this, you can branch your process or steps.

For example, if you want to execute a step only when workflowB is executed directly, you can add the following condition:

if: github.event.workflow == '.github/workflows/workflow-b.yaml'
Enter fullscreen mode Exit fullscreen mode

There's also a github.event_name, and I tried to see if it could be used for branching as well, but both the direct execution of workflowB and the execution from workflowA resulted in the same value as workflow_dispatch, so it couldn't be used for branching.

About type: environment

In practice, I think you can use the same workflow without branching by defining inputs with the same name as below, but since type: environment exists only for workflow_dispatch, if you are using this, you'll need to add a step to absorb the difference.

on:
  workflow_dispatch:
    inputs:
      input1:
        required: true
        type: string    
  workflow_call:
    inputs:
      input1:
        required: true
        type: string
Enter fullscreen mode Exit fullscreen mode

The value in the environment (environment_name) can be used as is, but as shown above, this difference occurs, so it seems better to avoid it when making a workflow_call.

Summary

There seem to be various methods, but by checking github.event.workflow, we were able to branch based on the method of executing the workflow.

💖 💪 🙅 🚩
koseimori
kosei

Posted on March 8, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related