Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling prod deployment with GitLab CI/CD

I'm trying to write a GitLab CI/CD pipeline that

  1. Runs a deployment job only if

    • a schedule pipeline starts with the env variable $CI_EVENT == "security_updates"
    • any push reaches the main branch
    • a user hits the run button at the Environments in the GitLab UI
  2. Runs a stop job only if

    • a user hits the stop button at the Environments in the GitLab UI

The 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?

like image 468
Gigi Avatar asked Oct 30 '25 00:10

Gigi


1 Answers

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:

  • The stop job will not be scheduled or run for merge request builds.
  • The stop job will still appear as a manual option in the GitLab UI environment for the main branch.

This configuration meets both requirements without breaking the UI behavior.

like image 103
RahulK Avatar answered Oct 31 '25 19:10

RahulK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!