I'm trying to write a GitLab CI/CD pipeline that
Runs a deployment job only if
$CI_EVENT == "security_updates"main branchrun button at the Environments in the GitLab UIRuns a stop job only if
stop button at the Environments in the GitLab UIThe following configuration does nearly what I want:
# other jobs and pipeline triggers...
deploy:
stage: deploy
environment:
name: prod
url: https://***.***.com/
on_stop: stop
rules:
- if: $CI_PIPELINE_SOURCE == "schedule" && $CI_EVENT == "security_updates"
- if: $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == "main"
when: on_success
- if: $CI_COMMIT_BRANCH == "main"
when: manual
script:
- docker compose up --build -d
stop:
stage: deploy
environment:
name: prod
action: stop
when: manual
script:
- docker compose down
The issue is that the stop job is being scheduled for Merge Requests builds. Setting a rule for it specifying it should run only at the main branch solves the issue, except that it breaks the GitLab UI requirements.
stop:
stage: deploy
environment:
name: prod
action: stop
rules:
- if: $CI_COMMIT_BRANCH == "main"
when: manual
script:
- docker compose down
After some research, I found many similar threads (Stop environment shows a note about not having an effect on any existing deployment, Gitlab doesn’t recognize stop action for environment, Stop environment shows a note about not having an effect on any existing deployment), but none of them seems to address exactly my issue.
Any ideas on how to fix this?
Add following condition
rules:
# Prevent stop job from running on merge request builds
- if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
when: never
# Allow manual run in the GitLab UI for the main branch only
- if: '$CI_COMMIT_BRANCH == "main"'
when: manual
By adding these conditions:
This configuration meets both requirements without breaking the UI behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With