Run a pipeline job while the branch is deleted.

Summary

Our team used gitlab terraform images and gitlab ci runner to deploy k8s on azure. We would like to remove remote azure resource when branch was deleted. I had used ci environment on_stop job to implement this flow, but it seem failed when the pipeline job (terraform destroy) is trigger by environment on_stop.

CI pipeline job:

apply:
  stage: deploy
  environment:
    action: start
    on_stop: when_branch_delete
  script:
    - gitlab-terraform apply
    
when_branch_delete:
  stage: deploy
  environment:
    action: stop
  script:
    - gitlab-terraform destroy
  when: manual

Error log:

fatal: couldn't find remote ref refs/heads/branch_deleted_test

What is the current behavior?

The pipeline job couldn't fetch ref data when the branch was deleted (then environment on_stop trigger the when_branch_delete job).

What is the expected behavior?

I think the pipeline job that need to trigger before the branch is deleted, not after branch has been deleted.

Question

How can I implement the pipeline job in gitlab-ci yaml while the branch deletion is trigger?

Thank you.

Edited by Mark Chiu