GitHub Actions:仅基于最新Release Tag定时重建容器
解决方案
1. 扩展触发条件
在原工作流的on字段中添加定时触发规则,示例为每周日凌晨1点UTC执行(可按需调整 cron 表达式):
on: push: branches: ['main'] tags: - 'v*' schedule: - cron: '0 1 * * 0' # 每周日凌晨1点 UTC 触发
2. 添加"获取最新Tag并切换"步骤
在Checkout repository步骤后新增逻辑,仅在定时触发时自动获取仓库最新的v*格式Tag并切换到该Tag:
- name: Checkout latest tag (only for schedule trigger) if: github.event_name == 'schedule' run: | LATEST_TAG=$(git describe --tags $(git rev-list --tags --max-count=1)) echo "Checking out to latest tag: $LATEST_TAG" git checkout $LATEST_TAG
3. 调整镜像元数据配置
修改docker/metadata-action的标签规则,确保定时触发时能正确生成对应Tag的镜像标签(含完整版本号、主版本.次版本号):
- name: Extract metadata (tags, labels) for Docker id: meta uses: docker/metadata-action@v5 with: tags: | type=ref,event=branch type=ref,event=pr type=semver,pattern={{version}},value=${{ github.ref_name }} type=semver,pattern={{major}}.{{minor}},value=${{ github.ref_name }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
完整修改后的工作流配置
on: push: branches: ['main'] tags: - 'v*' schedule: - cron: '0 1 * * 0' # 每周日凌晨1点 UTC 触发 env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.actor }}/openldap jobs: build-and-push: runs-on: ubuntu-latest permissions: contents: read packages: write steps: - name: Checkout repository uses: actions/checkout@v4 with: fetch-depth: 0 # 必须设置为0才能拉取所有Tag信息 - name: Checkout latest tag (only for schedule trigger) if: github.event_name == 'schedule' run: | LATEST_TAG=$(git describe --tags $(git rev-list --tags --max-count=1)) echo "Checking out to latest tag: $LATEST_TAG" git checkout $LATEST_TAG - name: Set up QEMU id: qemu uses: docker/setup-qemu-action@v3 with: platforms: arm64,amd64 - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Log in to the Container registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Extract metadata (tags, labels) for Docker id: meta uses: docker/metadata-action@v5 with: tags: | type=ref,event=branch type=ref,event=pr type=semver,pattern={{version}},value=${{ github.ref_name }} type=semver,pattern={{major}}.{{minor}},value=${{ github.ref_name }} images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - name: Build and push Docker image uses: docker/build-push-action@v5 with: context: . push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} platforms: linux/arm64,linux/amd64 cache-from: type=gha cache-to: type=gha,mode=max
关键说明
fetch-depth: 0:必须设置,否则默认checkout不会拉取所有Tag信息,导致无法获取最新Tag。- 条件判断
if: github.event_name == 'schedule':确保只有定时触发时才切换到最新Tag,push触发时保持原有逻辑(分支或Tag推送时构建对应版本)。 - 升级所有Action到最新版本:提升兼容性和安全性。
- cron表达式可自定义:比如
0 0 * * *表示每天凌晨触发,可根据更新频率需求调整。
内容的提问来源于stack exchange,提问作者ruckc
相关产品推荐
相关产品推荐

