Trigger GitLab job when merge request is closed
Asked Answered
O

1

6

I'm looking for a way to run a "cleanup" job/pipeline/etc when a GitLab merge request is closed (either merged or not).

The issue is this - we create a feature deployment on our cluster anytime a merge request is opened. Currently, I have no mechanism of detecting when an MR is closed. Over time these old 'feature deployments' accumulate on the cluster.

I could write a manual cleanup script (look at all open features, remove no-longer-existing-ones) from the cluster but that is going to be a bit hairy and error-prone. Was hoping GitLab has a method to use the really easy/nice pipeline+jobs features for this type of cleanup

Orlandoorlanta answered 26/7, 2019 at 17:5 Comment(6)
I can think about installing webhook gitlab.com/help/user/project/integrations/webhooks which will be called on each MR event, handle it and delete deployment. If you are using AWS, you can write lamda function for thisLangsdon
I'm thinking i can build a solution using actions - docs.gitlab.com/ee/ci/yaml/README.html#environmentactionOrlandoorlanta
I'm looking for exactly the same solution - update with answer if you've found a good method of doing this!Bottommost
@Bottommost did you ever figure this out? I'm trying to do the same.Polytonality
@DavidT. Nope - I just have to write a cleanup cronjob in my k8s cluster in order to accomplish it.Bottommost
@Bottommost I'm trying to solve the same problem and couldn't find a better solution than using webhooks. I met on the Internet tips to use Gitlab Environments, but I can't figure out how to use them. The problem with other solutions is that they don't trigger on MR close which is what I need.Carmelitacarmelite
E
0

We use GitLab environments for review apps. Environments can be automatically stopped after x weeks with environment.auto_stop_in. This has the advantage that, also when MR's stay open for months as they might be forgotten, the data will be cleaned up after x weeks (we use 2 weeks).

In the script, you can do whatever you need to clean up things. Like in our case, a helm uninstall.

gitlab-ci.yaml

deploy_review:
  stage: deploy
  script: "./deploy_review.sh"
  environment:
    auto_stop_in: 2 weeks
    name: review/$CI_COMMIT_REF_SLUG
    on_stop: stop_review_app
    deployment_tier: development
  resource_group: deploy-review-$CI_COMMIT_REF_SLUG

stop_review_app:
  stage: after_deploy
  when: manual
  only:
  - branches
  variables:
    GIT_STRATEGY: none
  script: "./stop_review_app.sh"
  environment:
    name: review/$CI_COMMIT_REF_SLUG
    action: stop
Eolande answered 4/11, 2022 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.