mrvnklm
mrvnklm

Reputation: 1828

Trigger Github Action only on new tags?

Is there a possibility to trigger a GitHub action only if a new version (which comes with a new tag) is pushed? I don't want run them on every push into master, but I also want to avoid creating a release branch.

Upvotes: 120

Views: 110230

Answers (4)

Sylhare
Sylhare

Reputation: 7059

To have the workflow run only for tags on the main branch (to prevent tags pushed on branches triggering it). You would need to use the if keyword as well such as:

name: CI
on:
  push:
    tags:
      - v*

jobs:
  build:
    if: ${{ github.ref == 'refs/heads/main' }}
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      # ... your other steps

That way this CI workflow will get trigger if a commit with a tag matching v* (like v1.0 or set it to * for any tag) on the main branch.

It uses the GitHub actions context. Here we check that its github.ref matches the main branch reference refs/heads/main, if true the job will be executed else it will be skipped.

Note: A tag in a branch that's then merged to main won't trigger this workflow.

It's only triggered on tag pushed directly to main.

Upvotes: 0

riQQ
riQQ

Reputation: 12723

Use the following syntax:

on:
  push:
    # Pattern matched against refs/tags
    tags:        
      - '*'           # Push events to every tag not containing /

For hierarchical tags:

on:
  push:
    # Pattern matched against refs/tags
    tags:        
      - '**'           # Push events to every tag including hierarchical tags like v1.0/beta

https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#patterns-to-match-branches-and-tags

Upvotes: 163

Yong
Yong

Reputation: 974

The goal is to trigger a workflow when a tag is pushed, e.g. doing something like:

git tag v1.0.0
git push origin v1.0.0

In the workflow file: e.g. ci.yml

name: CI
on:
  push:
    tags:
      - 'v[0-9]+.[0-9]+.[0-9]+'

This will run if someone pushes a semantic versioned tag to the GitHub repo.

One mistake I made was when migrating from Travis CI to GitHub Actions is that I incorrectly used

'^v[0-9]+\.[0-9]+\.[0-9]+'

as the pattern, which is WRONG. So check your pattern syntax if the workflow is not being triggered.

Upvotes: 59

candccoder
candccoder

Reputation: 803

I got it to work with

on:
  push:
    tags:
      - '*'

I found out that if the tag was previously created (locally) before the workflow was created, no matter how many times I deleted and re-pushed the tag, it would not trigger until I deleted the tag locally and recreated it. The action does not seem to work for tags created before the workflow.

Upvotes: 30

Related Questions