前言

Azure DevOps 官方有 GitHub 插件,可以在两边仓库完成有限的交互。如果需要更复杂的交互,则需要使用 PAT。

正文

我需要 Azure DevOps -> GitHub 的单向同步功能,每次 CI 自动推送 Azure DevOps 仓库的更新到 GitHub 仓库。这种交互是 GitHub for Azure DevOps 插件暂时不支持的。商店中有几款插件可以做到同步仓库,但是用插件总是会有小问题。

这里介绍使用原生 git command 的方法进行同步,只需要两行命令:

  1. 克隆 Azure 仓库到 CI 本地。这步是为了规避在 push 时的 shallow update not allowe 问题。
  2. 将克隆的 Azure 仓库推到 GitHub。
1
2
git clone --mirror $(Build.Repository.Uri) $(Build.Repository.Name)
git -C $(Build.Repository.Name) push --mirror https://$(GITHUB_PAT)@$(GITHUB_REPO)

具体步骤:

  1. 创建变量组
Variable group name Name Value
git-global-confgis USERNAME username
EMAIL [email protected]
tokens GITHUB_PAT ****
  1. 创建管道变量,注意不要有 https://
Name Value
GITHUB_REPO github.com/username/repo.git
  1. 编辑 azure-pipelines.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
trigger:
- main

variables:
- group: git-global-configs
- group: tokens

pool:
vmImage: ubuntu-latest

steps:
- script: |
git config --global user.email "$(EMAIL)"
git config --global user.name "$(USERNAME)"
git clone --mirror $(Build.Repository.Uri) $(Build.Repository.Name)
git -C $(Build.Repository.Name) push --mirror https://$(GITHUB_PAT)@$(GITHUB_REPO)
displayName: 'Sync with GitHub repo'