I was able to have my gitlab environment automatically stopped when merging and deleting a branch, per the documentation. However, I am unable to find a good explanation (in the documentation or otherwise) for how this happens, despite the fact that the stop_review
in the example job has when: manual
deploy_review:
stage: deploy
script:
- echo "Deploy a review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
url: https://$CI_ENVIRONMENT_SLUG.example.com
on_stop: stop_review
stop_review:
stage: deploy
script:
- echo "Remove review app"
environment:
name: review/$CI_COMMIT_REF_SLUG
action: stop
when: manual
Given all the other testing I've done with gitlab pipelines, I would have expected stopping the environment to require manually pressing the stop button on the job. I am pleased that this is giving me the result I want it to, but automatically stopping the environment seems to contradict what the when: manual
would normally do, so I find this very unintuitive.
Can anyone please give an explanation as to how this works?
Really, this is an implementation detail. But basically, when the branch is deleted, GitLab cleans up any associated environments on your behalf. In this case, that results in GitLab running the pending manual job to stop the environment, just as if you had hit the 'stop' button in the environments page yourself or ran the manual job in the pipeline.
The job declared as the on_stop
action typically must declare when: manual
, otherwise the job would run automatically and stop the environment right away! In this case, the "manual" action that triggers the job can include deleting the branch.
When an environment is created, GitLab associates that environment record with several pieces of information, which can include the branch and the job declared as the on_stop
action for the environment. When a branch is deleted, an action is triggered to cleanup (stop) any associated environments.
The specifics are implementation details, but as of the time of this writing, you can see in the implementation that when a branch is updated, several actions are triggered, including stop_environments
when a branch is deleted. This executes the associated StopService method which ultimately leads to the stop service playing your jobs with the associated on_stop
action.