是否有一种方法来限制一个动作可以在哪个分支上运行?



手动运行github操作时,我可以选择要对哪个分支运行它。对于某些行动来说,这似乎不是一个好主意。特别是沿着DeployToProduction的行操作-我只希望它针对main分支运行。

是否有任何方法将其限制为仅针对main运行-同时仍然使动作手动触发?

我有一个手动触发动作的例子,可能看起来像这样:

---
name: DeployToStaging
on:
workflow_dispatch:
jobs: 
...

我有同样的问题,我用一个条件解决了它:

if: github.ref == 'refs/heads/master'
steps:
...

通过这种方式,用户可以看到当选择不同的分支时该操作被跳过。

https://github.community/t/limit-branch-for-workflow-dispatch/122099/4

使用if条件检查此问题而无需硬编码分支名称的两种替代方法包括:

# Only run for the default branch
if: github.ref_name == github.event.repository.default_branch
# Older syntax for GitHub Enterprise Server where ref_name isn't available
if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch)

:

# Only run for protected branches
if: github.ref_protected == true

如果分支不是master,您可以添加类似于以下设置的步骤来退出工作流:

jobs:
YOUR_JOB:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Exit if the branch is not master
run: |
if [[ "${{ github.ref }}" != "refs/heads/master" ]]; then
echo "Branch is not master, exiting."
exit 0
fi

最新更新