Configure Conditional Execution
Applicable Scenarios: When you need to control whether a job or step is executed based on conditions such as branch, Tag, event type, and previous step status.
Prerequisites
- Understand the
atomgitcontext. - Understand the expression syntax
${{ }}.
Quick Example
name: conditional-workflow
on:
push:
branches:
- main
- develop
jobs:
build:
runs-on: [ubuntu-latest, x64, small]
steps:
- uses: checkout
- name: Run only on main
if: ${{ atomgit.ref == 'refs/heads/main' }}
run: echo "main branch"
- name: Run always
if: ${{ always }}
run: echo "always runs"
deploy:
if: ${{ atomgit.ref == 'refs/heads/main' }}
runs-on: [ubuntu-latest, x64, small]
needs: build
steps:
- run: echo "deploy to production"
Configuration Explanation
if Expression
The if condition uses ${{ }} expression syntax:
# if at job level
jobs:
deploy:
if: ${{ atomgit.ref == 'refs/heads/main' }}
runs-on: [ubuntu-latest, x64, small]
steps:
- run: echo "deploy"
# if at step level
steps:
- name: Run on main
if: ${{ atomgit.ref == 'refs/heads/main' }}
run: echo "main branch"
Status Functions
Status functions are used to check the execution status of previous steps or jobs:
| Function | Meaning | Conditions for Returning True |
|---|---|---|
success | All previous steps succeeded | All previous steps succeed (default behavior) |
failed | At least one previous step failed | At least one previous step fails |
cancelled | Workflow was cancelled | Workflow was cancelled |
always | Regardless of status | Returns true for any status |
Usage example:
steps:
- name: Build
run: ./build.sh
- name: Notify on success
if: ${{ success }}
run: echo "build succeeded"
- name: Notify on failure
if: ${{ failed }}
run: echo "build failed"
- name: Cleanup
if: ${{ always }}
run: ./cleanup.sh
Important:
if: ${{ always }}forces the step to execute, even if the previous steps fail or the workflow is cancelled. It is suitable for scenarios like resource cleanup and sending notifications.
Conditional Expression Operators
| Operator | Description | Example |
|---|---|---|
== | Equal to | ${{ atomgit.ref == 'refs/heads/main' }} |
!= | Not equal to | ${{ inputs.event_name != 'schedule' }} |
> / >= / < / <= | Comparison | ${{ inputs.count > 10 }} |
! | Logical NOT | ${{ !cancelled }} |
&& | Logical AND | ${{ success && atomgit.ref == 'refs/heads/main' }} |
|| | Logical OR | ${{ failed || cancelled }} |
String Functions
| Function | Description | Example |
|---|---|---|
contains(str, substr) | Contains substring | ${{ contains(atomgit.ref, 'main') }} |
startsWith(str, prefix) | Starts with prefix | ${{ startsWith(atomgit.ref, 'refs/tags/') }} |
endsWith(str, suffix) | Ends with suffix | ${{ endsWith(atomgit.ref, '.0') }} |
format(template, ...) | Formatting | ${{ format('Hello {0}', atomgit.actor) }} |