Execute a script before the branch is deleted in GitLab-CI

Viewed 2676

GitLab-CI executes the stop-environment script in dynamic environments after the branch has been deleted. This effectively forces you to put all the teardown logic into the .gitlab-ci.yml instead of a script that .gitlab-ci.yml just calls.

Does anyone know a workaround for this? I have a shell script that removes the deployment. This script is part of the repository and can also be called locally (i.e. not onli in an CI environment). I want GitLab-CI to call this script when removing a dynamic environment but it's obviously not there anymore when the branch has been deleted. I also cannot put this script to the artifacts as it is generated before the build by a configure script and contains secrets. It would be great if one could execute the teardown script before the branch is deleted.

Here's a relevant excerpt from the .gitlab-ci.yml

deploy_dynamic_staging:
    stage: deploy
    variables:
        SERVICE_NAME: foo-service-$CI_BUILD_REF_SLUG
    script:
        - ./configure
        - make deploy.staging
    environment:
        name: staging/$CI_BUILD_REF_SLUG
        on_stop: stop_dynamic_staging
    except:
        - master

stop_dynamic_staging:
    stage: deploy
    variables:
        GIT_STRATEGY: none
    script:
        - make teardown # <- this fails
    when: manual
    environment:
        name: staging/$CI_BUILD_REF_SLUG
        action: stop
2 Answers

Probably not ideal, but you can curl the script using the gitlab API before running it:

curl  \
    -X GET https://gitlab.example. com/raw/master/script.sh\
    -H 'PRIVATE-TOKEN: ${GITLAB_TOKEN}' > script.sh

GitLab-CI executes the stop-environment script in dynamic environments after the branch has been deleted.

That includes:

An on_stop action, if defined, is executed.

With GitLab 15.1 (June 2022), you can skip that on_top action:

Force stop an environment

In 15.1, we added a force option to the stop environment API call.

This allows you to delete an active environment without running the specified on_stop jobs in cases where running these defined actions is not desired.

See Documentation and Issue.

Related