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

Hamy
  • 20,662
  • 15
  • 74
  • 102
  • I can think about installing webhook https://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 this – ilia Jul 31 '19 at 12:18
  • I'm thinking i can build a solution using actions - https://docs.gitlab.com/ee/ci/yaml/README.html#environmentaction – Hamy Aug 20 '19 at 23:43
  • I'm looking for exactly the same solution - update with answer if you've found a good method of doing this! – TangoAlee Aug 12 '20 at 01:16
  • @TangoAlee did you ever figure this out? I'm trying to do the same. – David T. Dec 07 '20 at 18:54
  • 1
    @DavidT. Nope - I just have to write a cleanup cronjob in my k8s cluster in order to accomplish it. – TangoAlee Dec 23 '20 at 16:08
  • @TangoAlee 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. – Alexey Pavlunin Jan 15 '21 at 13:35

1 Answers1

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