You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅当提交信息含指定文本时通过GitHub Actions构建Docker镜像

实现仅当提交消息包含特定文本时触发GitHub Actions构建Docker镜像

要实现这个需求,你可以通过两种方式修改现有的GitHub Actions配置,下面是具体方案:

方式一:修改Workflow触发规则,仅符合条件时启动Workflow

直接在on字段中添加条件,让整个Workflow只在提交消息包含指定文本时才触发,避免不必要的Workflow启动,节省资源:

name: Docker Image CI

on:
  push:
    branches: [ "master" ]
    # 仅当提交消息包含"build image"时触发push事件的Workflow
    if: contains(github.event.head_commit.message, 'build image')
  pull_request:
    branches: [ "master" ]
    # 如果需要PR也遵循此规则,可以添加以下条件(检查PR标题或描述)
    # if: contains(github.event.pull_request.title, 'build image') || contains(github.event.pull_request.body, 'build image')

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v3
    - name: Docker Login
      env:
        DOCKER_USER: ${{secrets.DOCKER_USERNAME}}
        DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}}
      run: docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
    - name: Build the Docker image
      run: docker build . --file Dockerfile --tag ${{secrets.DOCKER_USERNAME}}/assignment:latest
    
    - name: Push Image to Docker Hub
      run: docker push ${{secrets.DOCKER_USERNAME}}/assignment

方式二:保持Workflow触发规则不变,仅符合条件时执行构建Job

这种方式下,Workflow仍会正常启动,但只有提交消息符合条件时,才会执行构建和推送的Job,适合需要在不符合条件时执行其他步骤的场景:

name: Docker Image CI

on:
  push:
    branches: [ "master" ]
  pull_request:
    branches: [ "master" ]

jobs:
  build:
    runs-on: ubuntu-latest
    # 仅当提交消息包含"build image"时执行此Job
    if: contains(github.event.head_commit.message, 'build image')
    steps:
    - uses: actions/checkout@v3
    - name: Docker Login
      env:
        DOCKER_USER: ${{secrets.DOCKER_USERNAME}}
        DOCKER_PASSWORD: ${{secrets.DOCKER_PASSWORD}}
      run: docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
    - name: Build the Docker image
      run: docker build . --file Dockerfile --tag ${{secrets.DOCKER_USERNAME}}/assignment:latest
    
    - name: Push Image to Docker Hub
      run: docker push ${{secrets.DOCKER_USERNAME}}/assignment

额外注意事项

  • 大小写敏感:默认的contains函数是大小写敏感的,如果需要忽略大小写,可以用toLower函数转换后再检查,示例:
    if: contains(toLower(github.event.head_commit.message), 'build image')
    
  • PR事件适配:如果是Pull Request事件,提交消息对应的字段是github.event.pull_request.title(PR标题)和github.event.pull_request.body(PR描述),可以根据需求调整条件。

内容的提问来源于stack exchange,提问作者Suyash Nalawade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:51:36