StLia
StLia

Reputation: 1072

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

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.

Upvotes: 16

Views: 27086

Answers (3)

karser
karser

Reputation: 1683

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

Upvotes: 14

Jakub Kania
Jakub Kania

Reputation: 16467

The easiest solution is to make a Merge Request and click the "Merge When Pipeline Succeeds" button, this will merge the branch after the build. This is the one I would recommend.

Below is the working solution that I do not recommend for an automatic merge. It requires you to create a deploy key with write access and save the private key as a project variable GITLAB_DEPLOY KEY, also do ssh-keyscan on the server and save it to GITLAB_PUBLIC_KEY variable.

mergetomaster:
  stage: deploy
  image: alpine
  only:
   - dev
  script:
   - apk add --update git openssh-client
   - mkdir ~/.ssh
   - echo $GITLAB_DEPLOY_KEY > ~/.ssh/id_rsa
   - chmod 400 ~/.ssh/id_rsa
   - echo $GITLAB_PUBLIC_KEY > ~/.ssh/known_hosts
   // Steal the identity of person that triggered the build
   - git config --global user.email "$GITLAB_USER_EMAIL"
   - git config --global user.name "$GITLAB_USER_ID"
   - git remote set-url origin <ssh-repository-url>
   - git checkout master
   - git reset --hard origin/master
   - git merge $CI_BUILD_REF
   - git push origin master

Upvotes: 11

Fairy
Fairy

Reputation: 3770

There is no easy way to do this as of GitLab version 8.15. The only way to do this is to leverage the API and webhooks.

This is the basic gist of what you have to do:

1.Create a webhook which hooks push events.

2.Check if the push belongs to the branch you want to do the merging on.

3.Create a merge request and immediately accept it with the option "merge_when_build_succeeds": true.

This way it will merge the the branch, should the build succeed. Not really the most comfortable thing to setup but it should work.

Upvotes: 3

Related Questions