🐙
【完全版】GitHub ActionsでGitLabリポジトリを自動同期する方法
はじめに
GitHubとGitLabを併用している場合、手動で両方にPushするのは面倒ですよね。
この記事では、GitHub Actionsを使ってGitLabリポジトリへ自動同期(ミラーリング)する方法を紹介します。
1つのYAMLファイルを追加するだけで、GitHub → GitLab への同期が自動化できます。
概要
🎯 ゴール
- GitHubでPushした内容を自動的にGitLabにも反映する
- Secretsを使って安全にトークンを管理する
- 繰り返し実行してもエラーが出ない構成にする
📦 前提条件
- GitHubリポジトリを持っている
- GitLabで対象リポジトリを作成済み(空でもOK)
- GitHub Actionsを利用可能な権限を持っている
① GitLabでアクセストークンを発行する
- GitLab右上の 「ユーザーアイコン → Edit profile」 を開く
- 左メニューの Access Tokens を選択
- 下記の設定でトークンを発行します:
| 設定項目 | 値 |
|---|---|
| Token name | github-sync |
| Scopes | ✅ write_repository
|
| Expiration date | 任意(無期限でもOK) |
発行後、トークン文字列(例:glpat-xxxxxxxxxxxxx)をコピーして控えておきます。
② GitHub Secretsに登録する
GitHubリポジトリで次の操作を行います:
- Settings → Secrets and variables → Actions → New repository secret
- 以下の2つのシークレットを登録:
| Name | Value |
|---|---|
GITLAB_TOKEN |
発行したGitLabのPersonal Access Token |
GITLAB_REPO |
https://gitlab.com/<ユーザー名>/<リポジトリ名>.git |
③ GitHub Actionsのワークフローを作成
.github/workflows/sync-to-gitlab.yml というファイルを新規作成し、以下を貼り付けます。
name: Sync to GitLab
on:
push:
branches: [ main ]
jobs:
sync:
runs-on: ubuntu-latest
steps:
- name: Checkout source
uses: actions/checkout@v4
- name: Set up Git
run: |
git config --global user.name "github-actions"
git config --global user.email "actions@github.com"
- name: Push to GitLab
env:
GITLAB_TOKEN: ${{ secrets.GITLAB_TOKEN }}
GITLAB_REPO: ${{ secrets.GITLAB_REPO }}
run: |
git remote remove gitlab 2>/dev/null || true
git remote add gitlab "${GITLAB_REPO}"
git fetch gitlab || true
git push -f "https://oauth2:${GITLAB_TOKEN}@${GITLAB_REPO#https://}" main
応用:全ブランチを同期する場合
main だけでなく、全ブランチやタグもミラーリングしたい場合は以下のように変更します。
on:
push:
branches: ["*"]
tags: ["*"]
jobs:
sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Push all branches and tags to GitLab
env:
GITLAB_TOKEN: ${{ secrets.GITLAB_TOKEN }}
GITLAB_REPO: ${{ secrets.GITLAB_REPO }}
run: |
git remote remove gitlab 2>/dev/null || true
git remote add gitlab "${GITLAB_REPO}"
git push --mirror "https://oauth2:${GITLAB_TOKEN}@${GITLAB_REPO#https://}"
🚨トラブルシューティング
authentication failed
- トークンの権限不足
- -> write_repository スコープを追加して再発行
repository not found
- GitLabリポジトリURLの誤り
remote gitlab already exists
- リモートが重複
- -> git remote remove gitlab を追加(上記コードで解決)
invalid refspec
- コマンド末尾に全角スペース
- -> main の後に余計なスペースがないか確認
まとめ
GitHub Actionsを使えば、GitLabとの二重管理を自動化でき、ミスや手間を大幅に減らせます。
一度設定してしまえば、以後のPushはGitHubだけでOK!
Discussion