Run pipeline on gitlab when branch is deleted

Viewed 3929

Is it possible to run a pipeline thanks to Gitlab CI/CD after a branch is deleted.

In fact I want to edit file after that branch is removed.

For example, I have two repositories, R1 and R2.

In R1 I have 2 branches

  • B1
  • B2

I want to edit a file from R2 when B1 (which is a R1's branch) is removed.

I know how to access and edit the file but I don't know how can I set a trigger for removed branch.

2 Answers

You can use environments. Look at Stopping an environment.

GitLab will automatically trigger a stop action when the associated branch is deleted. The stop_review job must be in the same stage as the deploy_review job in order for the environment to automatically stop.

deploy_review:
  stage: deploy
  script:
    - echo "Deploy a review app"
  environment:
    name: review/$CI_COMMIT_REF_NAME
    url: https://$CI_ENVIRONMENT_SLUG.example.com
    on_stop: stop_review
  only:
    - branches
  except:
    - master

stop_review:
  stage: deploy
  variables:
    GIT_STRATEGY: none
  script:
    - echo "Implement editing files from R2 here"
  when: manual
  environment:
    name: review/$CI_COMMIT_REF_NAME
    action: stop

It's not fully what you want, but maybe more useful for you.

It is not possible for the pipeline to know when you deleted a branch either via the UI nor via git branch -r -D. Pipelines run as a commit hook on the gitlab server (when you push), and when you click the Run Pipeline button manually in the UI.

That being said, it is possible to delete a branch from a pipeline job, so while I will leave it up to you to determine how you wish to do that, you can add a job that uses the trigger keyword to trigger a pipeline in R2 after a job in your R1 pipeline deletes the branch.

See the trigger docs: https://docs.gitlab.com/ee/ci/yaml/index.html#trigger and look into multi-project pipelines.

So in R2 you have a pipeline which is setup to edit some file In R1, then you would setup a job that deletes the B1 branch and follow that job with a "trigger job" which runs in R1 and sends a command to the Gitlab API to kick off the pipeline in R2.

Related