GitHub Action镜像构建问题:PR仅构建,合并/发布才推送到GHCR
问题原因
GitHub Actions中,环境变量会自动将布尔值转换为字符串类型。你定义的DO_PUSH是布尔表达式,实际存储的是"true"或"false"字符串,而非布尔值。当你用if: env.DO_PUSH == true时,是在比较字符串和布尔值,结果永远不相等,所以触发推送的步骤不会执行;而env.DO_PUSH != true相当于字符串不等于布尔值,结果永远为真,所以"Only build"步骤始终运行。
修复方案
方案1:直接在if条件中使用原表达式(推荐)
去掉DO_PUSH环境变量,直接在需要判断的步骤里使用布尔表达式,避免类型转换问题:
name: Build on: push: branches: ['main'] tags: ['v*'] pull_request: branches: ['main'] jobs: build-and-push: # ... steps: - name: Checkout repository uses: actions/checkout@v3 - name: Log in to GHCR if: github.ref == 'refs/heads/main' || github.event_name == 'release' uses: docker/login-action@v2 # ... - name: Get Docker metadata if: github.ref == 'refs/heads/main' || github.event_name == 'release' id: meta uses: docker/metadata-action@v4 # ... - name: Only build if: github.ref != 'refs/heads/main' && github.event_name != 'release' uses: docker/build-push-action@v4 with: context: . push: false - name: Build and push if: github.ref == 'refs/heads/main' || github.event_name == 'release' uses: docker/build-push-action@v4 with: context: . push: true # ...
方案2:保留环境变量,改用字符串比较
如果坚持使用DO_PUSH环境变量,需要在if条件中比较字符串值:
name: Build on: push: branches: ['main'] tags: ['v*'] pull_request: branches: ['main'] env: # ... DO_PUSH: ${{ github.ref == 'refs/heads/main' || github.event_name == 'release' }} jobs: build-and-push: # ... steps: - name: Checkout repository uses: actions/checkout@v3 - name: Log in to GHCR if: env.DO_PUSH == 'true' uses: docker/login-action@v2 # ... - name: Get Docker metadata if: env.DO_PUSH == 'true' id: meta uses: docker/metadata-action@v4 # ... - name: Only build if: env.DO_PUSH != 'true' uses: docker/build-push-action@v4 with: context: . push: false - name: Build and push if: env.DO_PUSH == 'true' uses: docker/build-push-action@v4 with: context: . push: true # ...
额外提示
注意你的触发规则中,push事件包含了tags: ['v*'],但当前判断条件里只检查了github.event_name == 'release',如果是通过推送标签触发的Action,github.event_name是push而非release,这会导致标签推送时无法触发推送步骤。如果需要支持标签推送时也推送镜像,需要把判断条件调整为:
github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')
或者对应到环境变量的定义:
DO_PUSH: ${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }}
内容的提问来源于stack exchange,提问作者theo
相关产品推荐
相关产品推荐

