Skip to content

Instantly share code, notes, and snippets.

@Chadys
Created May 23, 2023 16:35
Show Gist options
  • Save Chadys/c0bf9cb15b43c0afcc8b93001743556a to your computer and use it in GitHub Desktop.
Save Chadys/c0bf9cb15b43c0afcc8b93001743556a to your computer and use it in GitHub Desktop.
Gitlab-CI job to push code to another git forge via SSH
# the following variables must be defined in "Settings > CI/CD > Variables"
# EXTERNAL_DEPLOY_HOST = github.com
# EXTERNAL_DEPLOY_REPO = [email protected]:USERNAME/REPONAME.git
# SSH_PRIVATE_KEY = content of your SSH private key file /!\ Store as type "File" and not "Variable"
sync-repo:
stage: deploy
before_script:
# fix "Permissions 0666 are too open, private key ignored" error
- chmod 400 $SSH_PRIVATE_KEY
# Install ssh-agent if not already installed
- 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client -y )'
# Run ssh-agent (inside the build environment)
- eval $(ssh-agent -s)
# Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
- ssh-add $SSH_PRIVATE_KEY
# Create the SSH directory and give it the right permissions
- mkdir -p ~/.ssh
- chmod 700 ~/.ssh
# Fix Host key verification failed
- touch ~/.ssh/known_hosts
- ssh-keyscan $EXTERNAL_DEPLOY_HOST >> ~/.ssh/known_hosts
- chmod 644 ~/.ssh/known_hosts
# git
- git config --global user.email "[email protected]"
- git config --global user.name "${CI_PROJECT_TITLE}-bot"
# gitlab-runner runs on a detached HEAD, checkout current branch
- git checkout -b $CI_COMMIT_BRANCH
# set remote push URL
- git remote set-url --push origin "${EXTERNAL_DEPLOY_REPO}"
script:
# push changes to originating branch
- git push --tags origin ${CI_COMMIT_BRANCH}:${CI_COMMIT_BRANCH}
environment:
name: deploy/$CI_COMMIT_REF_SLUG
action: start
rules:
- if: '($CI_PIPELINE_SOURCE == "push" || $CI_PIPELINE_SOURCE == "web") && ($CI_COMMIT_BRANCH == "production"' || $CI_COMMIT_BRANCH == "staging"')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment