如何基于非受控第三方仓库触发自有仓库的部署?
第三方仓库更新自动触发CI构建配置方案
GitHub Actions 配置
方案1:第三方仓库支持Webhook(推荐)
- 在第三方仓库的Webhook设置页面,添加触发URL:
https://api.github.com/repos/[你的用户名]/[你的仓库名]/dispatches - 请求方法选
POST,内容类型设为application/json,请求体固定为:{ "event_type": "third_party_updated" } - 在你的项目仓库中,创建
.github/workflows/third-party-trigger.yml文件,内容如下:name: 第三方仓库更新触发构建 on: repository_dispatch: types: [third_party_updated] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 # 替换成你的实际构建步骤 - name: 安装依赖 run: npm install - name: 执行构建 run: npm run build
方案2:第三方仓库不支持Webhook(定时检查)
如果第三方仓库没法设置Webhook,就用定时任务每天检查它的最新提交哈希,和本地存储的对比,不一致就触发构建:
name: 定时检查第三方仓库更新 on: schedule: - cron: '0 0 * * *' # 每天UTC零点执行,可自行调整时间 jobs: check-and-build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: 获取第三方仓库最新哈希 id: fetch_hash run: | THIRD_PARTY_HASH=$(git ls-remote https://github.com/[第三方用户名]/[第三方仓库名].git HEAD | awk '{print $1}') echo "third_party_hash=$THIRD_PARTY_HASH" >> $GITHUB_OUTPUT - name: 读取本地存储的哈希 id: stored_hash run: | STORED_HASH=$(cat .third_party_hash 2>/dev/null || echo "") echo "stored_hash=$STORED_HASH" >> $GITHUB_OUTPUT - name: 哈希不一致则更新并构建 if: steps.fetch_hash.outputs.third_party_hash != steps.stored_hash.outputs.stored_hash run: | # 更新本地存储的哈希并提交 echo ${{ steps.fetch_hash.outputs.third_party_hash }} > .third_party_hash git config user.name "GitHub Actions" git config user.email "actions@github.com" git add .third_party_hash git commit -m "更新第三方仓库哈希" git push # 执行构建步骤 npm install npm run build
CircleCI 配置
方案1:Webhook触发Pipeline
- 在CircleCI的项目设置里找到「Trigger a Pipeline via Webhook」,复制对应的Webhook URL
- 到第三方仓库的Webhook设置中添加这个URL,请求方法选
POST,触发事件勾选仓库更新相关的(比如push) - 在项目根目录的
.circleci/config.yml中添加如下配置:version: 2.1 workflows: 第三方更新触发构建: jobs: - build triggers: - webhook: event: third_party_updated # 和Webhook请求体中的event字段对应 filters: branches: only: main # 只触发主分支的构建 jobs: build: docker: - image: cimg/node:20.10.0 # 替换成你的项目所需镜像 steps: - checkout - run: npm install - run: npm run build
方案2:定时检查更新
如果第三方仓库不支持Webhook,用定时任务对比哈希触发构建:
version: 2.1 jobs: 检查第三方仓库更新: docker: - image: cimg/git:2.43.0 steps: - checkout - run: name: 获取第三方仓库最新哈希 command: | THIRD_PARTY_HASH=$(git ls-remote https://github.com/[第三方用户名]/[第三方仓库名].git HEAD | awk '{print $1}') echo "export THIRD_PARTY_HASH=$THIRD_PARTY_HASH" >> $BASH_ENV - run: name: 对比哈希并触发构建 command: | STORED_HASH=$(cat .third_party_hash 2>/dev/null || echo "") if [ "$THIRD_PARTY_HASH" != "$STORED_HASH" ]; then # 更新本地哈希并提交 echo $THIRD_PARTY_HASH > .third_party_hash git config user.name "CircleCI" git config user.email "circleci@circleci.com" git add .third_party_hash git commit -m "更新第三方仓库哈希" git push origin main # 执行构建步骤 npm install npm run build fi workflows: 每日检查更新: jobs: - 检查第三方仓库更新 triggers: - schedule: cron: "0 0 * * *" # 每天UTC零点执行,可调整 filters: branches: only: main
内容的提问来源于stack exchange,提问作者Tomasz Gałkowski
相关产品推荐
相关产品推荐

