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.
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With