迁移应用场景
1.迁移部分项目到新的仓库地址
2.迁移组以及子组下所有的项目
3.迁移所有gitlab组
要求
1.基本要求
a 新的git地址和老的git地址都有对应的权限token
b 脚本服务器和老的git服务器以及新的git服务器网络通的(ssh方式拉取代码)
c 配置ssh拉取代码(新旧gitlab,可选择https方式)
0.配置ssh方式拉取代码
步骤一:生成SSH密钥
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" //换成自己的邮箱
- 生成成功后,你将在终端或Git Bash中看到一条消息,其中包含公钥的位置,默认为~/.ssh/id_rsa.pub。
步骤二:将SSH公钥添加到GitLab账户
- 复制SSH公钥的内容。你可以使用以下命令将其打印到终端或Git Bash中:
- cat ~/.ssh/id_rsa.pub
1.获取项目token
配置添加token(有读写api的相关权限)
将token进行记录
2.迁移组
选择要迁移的组
setting----->General---->Advanced------->Export group (导出组文件)
再按创健组的顺序在新的进行导入即可
3.迁移组下所有项目(包括子组下的所有项目)
通过python脚本迁移所有仓库代码
注: 请将对应的token修改,git地址修改
import requests
import os
import subprocess
ACCESS_TOKEN = "*****************" //迁移token老的git地址token
GITLAB_API_URL = "https://*.*.*.*/api/v4" //gitlab api地址
def clone_repo(ssh_url, path):
if not os.path.exists(path):
os.makedirs(path)
print(ssh_url,path)
subprocess.call(["git", "clone", "--mirror", ssh_url, path])
def push_repo(ssh_url, path):
new_repo_url = ssh_url.replace("gitlab.fosun.com", "gitlab.assistfc.com")
os.chdir(path)
subprocess.call(["git", "remote", "set-url", "--push", "origin", new_repo_url])
subprocess.call(["git", "push", "--mirror"])
print("push --mirror new_repo_url %s"%new_repo_url)
def get_subgroups_and_projects(group_id, base_path):
projects = []
groups_to_check = [(group_id, base_path)]
while groups_to_check:
current_group_id, current_path = groups_to_check.pop(0)
subgroup_response = requests.get(
f"{GITLAB_API_URL}/groups/{current_group_id}/subgroups",
headers={"PRIVATE-TOKEN": ACCESS_TOKEN}
)
if subgroup_response.status_code == 200:
subgroups = subgroup_response.json()
for subgroup in subgroups:
subgroup_path = os.path.join(current_path, subgroup['path'])
groups_to_check.append((subgroup['id'], subgroup_path))
project_response = requests.get(
f"{GITLAB_API_URL}/groups/{current_group_id}/projects",
headers={"PRIVATE-TOKEN": ACCESS_TOKEN}
)
if project_response.status_code == 200:
print("project",project_response)
for project in project_response.json():
print("project info",project)
print("project['path']",project['path'])
project_path = os.path.join(current_path, project['path'])
print("project_path",project_path)
clone_repo(project['ssh_url_to_repo'], project_path)
push_repo(project['ssh_url_to_repo'], project_path)
projects.append(project)
return projects
group_id = *** //迁移的组id注意修改
base_path = "/tmp/test" //代码存放目录
projects = get_subgroups_and_projects(group_id, base_path)
执行脚本进行脚本迁移(完成)