如何基于复杂条件(删除特定标签)运行GitHub Actions作业



我有两个可重用的工作流来部署和销毁GCP资源,我根据不同的条件从一个工作流中调用它们。

一个工作流创建基础设施,并在标签preview添加到PR:时触发

on:
pull_request:
types: [opened, reopened, labeled]
jobs:
create-infrastructure:
if: ${{ contains( github.event.pull_request.labels.*.name, 'preview') }}
# Call to a reusable workflow here

当PR关闭或删除特定标签时,我需要触发第二个工作流;我试过这个:

on:
pull_request:
types: [ closed, unlabeled ]
jobs:
destroy_preview:
if: ${{ contains( github.event.pull_request.labels.*.name, 'preview') }}
uses: myrepo/.github/workflows/preview-app-destroy.yml@v0.3.6
with:
project_id: xxx

我不知道如何为特定标签定义unlabeled。如果有人知道那就太好了。

据我所知,pull-request-webhook负载不包含已删除的标签,但您可以获取问题事件列表(也适用于pull-request(,按unlabeled事件进行筛选,然后查看最后一个事件的标签名称。

run步骤中使用GitHub CLI,可能看起来像这样:

name: Preview removed workflow
on:
pull_request:
types:
- unlabeled
jobs:
destroy_preview:
runs-on: ubuntu-20.04
steps:
- name: Check if "preview" was removed
env:
GITHUB_TOKEN: ${{ github.token }}
run: |
pr=${{ github.event.number }}
label=$(gh api "repos/$GITHUB_REPOSITORY/issues/$pr/events" 
--jq 'map(select(.event == "unlabeled"))[-1].label.name')
if [[ $label == 'preview' ]]; then
echo "The 'preview' label has been removed"
fi

在这里,您可以用基础结构命令替换echo


现在,如果您想在移除特定标签时调用可重复使用的工作流,您必须找到一种方法,在调用可重复使用工作流的作业中添加一个条件。

一种选择是制作两个作业,一个用于检查条件并将结果设置为作业输出。另一个作业根据第一个作业进行设置,其if条件检查输出是否设置为true

这看起来像这样(省略了名称和触发器,因为它们与上面相同(:

jobs:
checklabel:
runs-on: ubuntu-20.04
outputs:
waspreview: ${{ steps.check.outputs.preview }}
steps:
- name: Check if "preview" was removed
id: check
env:
GITHUB_TOKEN: ${{ github.token }}
run: |
pr=${{ github.event.number }}
label=$(gh api "repos/$GITHUB_REPOSITORY/issues/$pr/events" 
--jq 'map(select(.event == "unlabeled"))[-1].label.name')
if [[ $label == 'preview' ]]; then
echo "::set-output name=preview::true"
fi
destroy_preview:
needs: checklabel
if: needs.checklabel.outputs.waspreview
uses: myrepo/.github/workflows/preview-app-destroy.yml@v0.3.6
with:
project_id: xxx

最新更新