How can I make Gitlab runner merge code into a branch on a successful build

StLia picture StLia · Feb 8, 2017 · Viewed 15.5k times · Source

Well the title is pretty much self-explanatory.

In summary, I want a branch (i.e. dev) to be merged to another branch (i.e. production) IF the build is successful.

Answer

karser picture karser · Nov 14, 2017

I tried @jakub-kania solution but I was always getting id_rsa invalid format. I think that gitlab secret variables are screwed somehow.

I made it working by directly passing the deployment key into ssh-add without creating ssh keys. Here is working solution:

merge to master:
  stage: deploy
  image: alpine
  only:
    - dev-branch
  before_script:
    - apk add --update git openssh-client
    - mkdir ~/.ssh
    - ssh-keyscan -p 2222 <gitlab.domain.com> > ~/.ssh/known_hosts
    - eval `ssh-agent -s`
    - ssh-add <(echo "$GITLAB_DEPLOY_KEY")
    - ssh -T git@<gitlab.domain.com> -p 2222
    - git config --global user.email "$GITLAB_USER_EMAIL"
    - git config --global user.name "$GITLAB_USER_ID"
    - git remote set-url origin ssh://git@<gitlab.domain.com>:2222/path/to/repo.git
  script:    
    - git checkout master
    - git reset --hard origin/master
    - git merge $CI_BUILD_REF
    - git push origin master