Did you ever had the need to sync your git repository hosted on a Gitlab CE instance to another git repository (doesn’t have to be gitlab)? Here’s a short how to by just using the features offered by Gitlab CE.
The approach described below uses a GitLab CI job that is triggered on every push, clones the code in a docker container and then pushes the code to the remote repository.
Please be careful: The keys for the communication with the remote git repository are stored in the repository. But usually the project team also has access to the remote repository.
Set up keys for remote
In order to be able to push code to the remote repository we store the SSH keys in the local repo and use them then from within the container to push the code.
The keys are generated in a subdirecctory in the git repository:
ssh-keygen -b 2048 -t rsa -f id_rsa -q -N ""
In order for the docker container to trust the foreign git server you add the host to the known_hosts file
ssh-keyscan -t rsa1,rsa,dsa GIT_SERVER > known_hosts
After that just add the keys folder with the gerenated files to your git repository.
Set up GitLab CI job
.gitlab-ci.yaml you have to add a job that is able to push the code to the remote server. The used job is using a docker image based on Alpine Linux. The necessary tools (bash, git, openssh) are then installed.
For the build the keys that were generated in the step before are copied to the system SSH folders (~/.ssh). Then the necessary remote host is added and the push can be performed.
The complete example is shown below:
- apk add --no-cache bash git openssh
- mkdir ~/.ssh && cp keys/id_rsa ~/.ssh/ && cp keys/id_rsa.pub ~/.ssh/ && chmod 700 ~/.ssh && chmod 600 ~/.ssh/id_rsa && cp keys/known_hosts ~/.ssh
- git remote add mirror git@GIT_SERVER:PROJECT.git
- git push mirror master
Now you have a simple mirroring of your git repo that works with the standard GitLab CE features.
Show all posts by Daniel Weisser