Git push from inside a gitlab-runner

We did this by adding a before_script task where we install SSH & Git and set the Git credentials.

The var SSH_PRIVATE_KEY_TOOLKIT in the example below is a Deploy Key generated in Gitlab by going to Settings > Repository > Deploy Keys, Make sure to enable write access by editing the deploy key after enabling it.

 before_script:
    - apt-get update -y && apt-get install -yqqf openssh-client git unzip sshpass rsync --fix-missing
    - 'which ssh-agent || ( apt-get update -y && apt-get install openssh-client git -y )'
    - eval $(ssh-agent -s)
    - echo "$SSH_PRIVATE_KEY_TOOLKIT" | tr -d '\r' | ssh-add - > /dev/null

    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh

    - ssh-keyscan $GITLAB_URL >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts

    - git config --global user.email "our@email.com"
    - git config --global user.name "Gitlab Runner"

Then in your script you can do this:

  script:
    # Pull repo
    - echo "Pulling external repo into build"
    - ssh git@$GITLAB_URL
    - git clone git@$GITLAB_URL:$EXTERNAL_REPO_URL filelocation/we/expect/the/files
    
    # Do something after pulling your repo
    
    # Push repo changes into current repo
    - git remote rm origin && git remote add origin "git@$GITLAB_URL:${CI_PROJECT_PATH}.git"
    - git add filelocation/we/expect/the/files another/location/can/be/defined
    - git commit -m "Commit message here :)" || echo "No changes, nothing to commit!"
    - git push origin HEAD:$CI_COMMIT_REF_NAME

Hope this helps you out.

4 Likes