A Git mirror is a complete copy of a Git repository. It’s a type of Git repository that is a mirror image of another repository, often used for backup, collaboration, or deployment purposes.
Some key aspects of a Git mirror:
Characteristics
- Read-only or read-write: A Git mirror can be either read-only, where updates are pushed from the original repository, or read-write, where updates can be pushed to both the mirror and the original repository.
- Complete copy: A Git mirror contains all the branches, tags, and commits of the original repository.
- Independent: A Git mirror is a separate Git repository, with its own Git directory and configuration.
Use cases
- Backup and disaster recovery: A Git mirror can serve as a backup of the original repository, ensuring that the codebase is preserved in case of a disaster.
- Collaboration and deployment: A Git mirror can be used to collaborate with external teams or to deploy code to a production environment.
Commands
- Git clone with –mirror: The
git clonecommand with the--mirroroption can be used to create a Git mirror. - Git push with –mirror: The
git pushcommand with the--mirroroption can be used to update a Git mirror. - Git remote with –mirror: The
git remotecommand with the--mirroroption can be used to add a Git mirror as a remote repository.
How to setup
1) Configure the Git credentials using the Credentials Manager of Jenkins
2) Configure the credentials on your Jenkins job:
Build Triggers
- Check: Poll SCM
- Schedule: H * * * *
Build Environment
- Check: Delete workspace before build starts
- Check: Use secret text(s) or file(s)
- Bindings
- Username and password (separated)
- Username Variable: GIT_USERNAME
- Password Variable: GIT_PAT
- Credentials
- Select: Specific credentials
- Select the Jenkins credentials for the Git repo.
- Select: Specific credentials
- Username and password (separated)
- Bindings
3) Add this as the Execute shell step:
#!/bin/bash
# Set the GIT_ASKPASS environment variable
export GIT_ASKPASS=true
# Use the bound credentials
echo "GIT_USERNAME: $GIT_USERNAME"
# Extract the UserID if the username is an email
GIT_USERID=$(echo "$GIT_USERNAME" | cut -d "@" -f 1)
echo "GIT_USERID: $GIT_USERID"
# Use the credentials
"Running Git Mirror of the repo ..."
git -c credential.helper="" clone --mirror "https://${GIT_USERID}:${GIT_PAT}@github.com/sample-repo.git"
echo "Done"
4) Save the output of the Jenkins job as an artifact.
How to access this Git Mirror
$ cd "/var/lib/jenkins/workspace/<your-jenkins-job-name>/sample-repo.git"
$ git config --global --add safe.directory . # Incase you get any warnings
$ git daemon --base-path=. --export-all --reuseaddr --verbose --port=9000
This will start a Git Server and serve the git repo via the git protocol.
Now you can clone the repo using this command:
git clone git://<your-jenkins-server>:9000/sample-repo.git