Automated Github to Gitlab Backup

A paranoid guy always is ready for a doomsday scenario so let’s prepare for a doomsday scenario. Backing up git from github to gitlab

GitLab setup

  1. Go to GitLab an an account is not created, create it
  2. On the home page go to Account icon > Preferences > Access > Personal access tokens and you’ll see a page like this

GitLab PAT page

  1. Create a legacy token

Legacy token

  1. It’ll look something like this

Legacy token page

  1. Select only read_repository and write_repository here

Legacy token scopes

  1. Now the Personal access tokens will be active throughout the repo

GitHub setup

Unlike the Gitlab setup we’re gonna go this in the scope of per repo. So only the repository you wanna backup gets backed up others stay the same

  1. Go to any repo you wanna backup and go to (Repo) Settings > Secrets and Variables > Actions > Repository secrets
  2. Create a New repository secret called as GITLAB_TOKEN

GitHub settings

  1. After the secret is active paste the following yaml script under .github/workflows and lets name this script mirror-to-gitlab.yml.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
name: Mirror GitHub to GitLab

on:
  workflow_dispatch:

# Minimum permissions required
permissions:
  contents: read

# Prevent simultaneous mirror operations
concurrency:
  group: github-to-gitlab-mirror
  cancel-in-progress: false

jobs:
  mirror:
    name: Mirror main branch
    runs-on: ubuntu-latest

    # Only repository owner, and only when main is selected
    if: >
      github.actor == github.repository_owner &&
      github.ref == 'refs/heads/main'

    steps:
      - name: Clone GitHub main branch
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITHUB_REPOSITORY: ${{ github.repository }}
        run: |
          git clone \
            --single-branch \
            --branch main \
            "https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPOSITORY}.git" \
            source

      - name: Configure Git
        run: |
          git config --global user.name "GitHub Mirror"
          git config --global user.email "github-mirror@users.noreply.github.com"

      - name: Push main branch to GitLab
        env:
          GITLAB_TOKEN: ${{ secrets.GITLAB_TOKEN }}
        run: |
          git -C source push \
            --force \
            "https://oauth2:${GITLAB_TOKEN}@gitlab.com/<username>/<project/repo>" \
            main:main

      - name: Mirror result
        run: echo "Successfully mirrored GitHub main to GitLab main."
  1. Modify username to your own username and project/repo to your own project/repo url
  2. The current workflow allows backup via a manual workflow dispatch and only allows the repo owner in github to deploy their own workflow so unauthorized user can’t use it.