仅使用GitHub Actions在特定分支上运行作业 [英] Only run job on specific branch with GitHub Actions

查看:172
本文介绍了仅使用GitHub Actions在特定分支上运行作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是GitHub Actions的新手,我有2个工作-一个运行我的测试,另一个将我的项目部署到服务器上.

I'm relatively new to GitHub Actions and I have 2 jobs–one that runs my tests, and one that deploys my project onto a server.

很显然,我希望测试可以在每个分支上运行,但是只有在将某些内容推送到主服务器上时,才应该进行部署.

Obviously I want the tests to run on every branch, but deploying should only happen when something gets pushed to master.

我正在努力寻找一种在特定分支上运行作业的方法.我知道只在特定分支上运行整个工作流是可能的,但这意味着我将拥有一个测试"工作流和一个部署"工作流.

I'm struggling to find a way to run a job on a specific branch. I know it's possible to only run entire workflows on a specific branch, however that would mean I would have a "test" workflow and a "deploy" workflow.

这听起来像是一种解决方案,但是它们可以并行运行.在理想的情况下,测试将首先运行,并且只有在测试成功的情况下,部署工作才能开始.使用2个单独的工作流时不是这种情况.

This sounds like a solution, however they would run parallel. In an ideal world, the tests would run first, and only if they succeed, then the deploy job would start. This isn't the case when using 2 separate workflows.

我将如何实现这一目标?是否可以在特定分支上运行职位?

How would I be able to achieve this? Is it possible to run jobs on a specific branch?

推荐答案

在最近的更新中,您现在可以将if条件语句置于job级别.请参阅此处的文档. https://docs.github.com/en /actions/reference/workflow-syntax-for-github-actions#jobsjob_idif

In a recent update you can now put if conditionals at job level. See the documentation here. https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idif

我测试了此工作流程,该工作流程在每次推送时都运行作业test,但仅在master分支上运行deploy.

I tested this workflow which runs the job test on every push, but only runs deploy on the master branch.

name: my workflow
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Execute tests
        run: exit 0
  deploy:
    runs-on: ubuntu-latest
    needs: test
    if: github.ref == 'refs/heads/master'
    steps:
      - name: Deploy app
        run: exit 0

下面是我的原始答案,如果您希望拥有单独的工作流程,还可以使用另一种解决方案.

What follows is my original answer, and an alternative solution if you prefer to have separate workflows.

第一个工作流针对除master之外的每个分支运行.在此工作流程中,您仅运行测试.

The first workflow runs for every branch except master. In this workflow you run tests only.

on:
  push:
    branches:
      - '*'
      - '!master'

第二个工作流程仅在master上运行,并且如果测试成功通过,则可以运行您的测试并进行部署.

The second workflow runs for just master and runs both your tests and deploys if the tests were successfully passed.

on:
  push:
    branches:
      - master

这篇关于仅使用GitHub Actions在特定分支上运行作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆