I've got a Github workflow for a CI build that looks like this:
- name: Checkout meta-repo
uses: actions/checkout@v4
with:
ssh-key: ${{ secrets.CI_BUILD_PRIVATE_SSH_KEY }}
repository: meta-repo
ref: ${{ github.event.client_payload.ref || 'dev' }}
path: meta-repo
The github.event.client_payload.ref
comes from enabling repository_dispatch - if that's not defined then we default to the dev
branch. But this means when we build the main
branch for this repo we use the dev
branch from meta-repo which is incorrect. What I want to do is say:
github.event.client_payload.ref
is defined then checkout that.main
then checkout main
.dev
.I can't see a way of doing this. There's an if
command but that seems to be for conditionally running entire steps. Is that the only way to achieve this?
According to GitHub Actions Operators:
GitHub offers ternary operator like behaviour that you can use in expressions. By using a ternary operator in this way, you can dynamically set the value of an environment variable based on a condition, without having to write separate if-else blocks for each possible option.
Example:
env: MY_ENV_VAR: ${{ github.ref == 'refs/heads/main' && 'value_for_main_branch' || 'value_for_other_branches' }}
So, you can use the ternary expression
${{ expression && true-case || false-case }}
and chain it according to your use case.
Here's an example:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ github.event.client_payload.ref && github.event.client_payload.ref || (github.ref_name == 'main' && 'main' || 'dev') }}
A long expression may span onto multiple lines:
- name: Checkout
uses: actions/checkout@v4
with:
ref: >-
${{ github.event.client_payload.ref && github.event.client_payload.ref
|| (github.ref_name == 'main' && 'main' || 'dev') }}
For YAML's folding and stripping with >-
, See https://yaml-multiline.info/ for more details and interactive examples.