Docker Build and Push from Upstream Tag #18
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Docker Build and Push from Upstream Tag | |
on: | |
schedule: | |
- cron: '0 0 * * 0' # 每周天检查一次上游仓库(可自定义) | |
workflow_dispatch: | |
jobs: | |
check-if-buildable: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Check tag exist | |
run: | | |
# 获取上游仓库的最新 tags | |
upstream_tags=$(curl -s -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/nicoboss/nsz/tags) | |
# 提取最新的 tag 名称 | |
latest_tag_name=$(echo "$upstream_tags" | jq -r '.[0].name // empty') | |
echo "Latest upstream tag: $latest_tag_name" | |
# 如果没有获取到 tag,则退出 | |
[ -z "$latest_tag_name" ] && exit 1 | |
# 定义镜像名称和要检查的 tag | |
image_name="zhengyongtao/nsz" | |
tag_to_check="$latest_tag_name" | |
# 构造 Docker Hub API URL | |
api_url="https://registry.hub.docker.com/v2/repositories/${image_name}/tags/${tag_to_check}" | |
# 使用 curl 查询镜像 tag 的详细信息 | |
http_status=$(curl -s -o /dev/null -w "%{http_code}\n" "${api_url}") | |
if [[ "$http_status" == "404" ]]; then | |
echo "The tag ${tag_to_check} does not exist for the image ${image_name}." | |
echo "skip_flag=false" >> $GITHUB_OUTPUT | |
else | |
echo "The tag ${tag_to_check} exists for the image ${image_name}." | |
echo "skip_flag=true" >> $GITHUB_OUTPUT | |
fi | |
# 将 tag 名称存储到 GITHUB_OUTPUT | |
echo "upstream_tag=$latest_tag_name" >> $GITHUB_OUTPUT | |
id: check_tag_exist | |
outputs: | |
skip_flag: ${{ steps.check_tag_exist.outputs.skip_flag }} | |
upstream_tag: ${{ steps.check_tag_exist.outputs.upstream_tag }} | |
build-and-push: | |
runs-on: ubuntu-latest | |
needs: check-if-buildable | |
if : ${{ needs.check-if-buildable.outputs.skip_flag != 'true' }} | |
steps: | |
- name: Checkout code at upstream tag | |
uses: actions/checkout@v4 | |
with: | |
repository: 'zhengyongtao/nsz-docker' # 指定仓库 | |
ref: main # 指定分支 | |
- name: Set up QEMU | |
uses: docker/setup-qemu-action@v3 | |
- name: Set up Docker Buildx | |
uses: docker/setup-buildx-action@v3 | |
- name: Login to Docker Hub | |
uses: docker/login-action@v3 | |
with: | |
username: ${{ secrets.DOCKERHUB_USERNAME }} | |
password: ${{ secrets.DOCKERHUB_TOKEN }} | |
- name: Build and push Docker image | |
id: docker_build | |
uses: docker/build-push-action@v5 | |
with: | |
context: . | |
file: ./Dockerfile | |
platforms: linux/amd64,linux/arm64/v8 # 根据需要调整目标架构 | |
push: true | |
build-args: | | |
UPSTREAM_TAG=${{ needs.check-if-buildable.outputs.upstream_tag }} | |
tags: | | |
zhengyongtao/nsz:${{ needs.check-if-buildable.outputs.upstream_tag }} | |
zhengyongtao/nsz:latest | |
- name: Image digest | |
run: echo ${{ steps.docker_build.outputs.digest }} | |