Job runs without waiting for other stages

Apologies in advance, I’m still getting to grips with the structure of gitlab cicd files!

We have a pipeline, with a job at the end to “undeploy”. Generally, this is a manually triggered job. But we have the option to set an environment variable, which allows the job to run without intervention. Unfortunately I can’t get this to work quite how I’d like it to, and I’m baffled!

I’ve included our gitlab-ci file below. The problem stage is undeploy, when we set $TF_AUTO_UNDEPLOY = “true”, the job starts immediately on triggering the pipeline, it doesn’t wait until, what I’d consider to be the previous step, deploy, completes.

We have an identical clause in the deploy stage ($TF_AUTO_DEPLOY = “true”), if we set this to true, this DOES wait for the previous stage (build), until it executes.

I’m sure I’ve done something stupid, but I can’t see it!

Note, the include file contains hidden definitions, containing the script commands, I can’t really include it here as it contains some internal stuff, there are no rule/workflow definitions in there.

Thanks,
Paul

stages:
  - build
  - test
  - deploy
  - undeploy

include:
  local: '/templates/.simple-terraform-template.yml'

build:tform:
  extends: .build:terraform
  stage: build

ftlint:tform:
  extends: .tflint:terraform
  stage: test

deploy:tform:
  extends: .deploy:terraform
  environment:
      name: $CI_COMMIT_REF_NAME
  dependencies:
    - build:tform
  stage: deploy
  rules:
    - if: $TF_AUTO_DEPLOY == "true" && $CI_PIPELINE_SOURCE != "merge_request_event"
      when: on_success
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: never
    - when: manual

undeploy:tform:
  extends: .undeploy:terraform
  stage: undeploy
  environment:
    name: $CI_COMMIT_REF_NAME
  dependencies:
    - deploy:tform
  allow_failure: true
  rules:
    - if: $TF_AUTO_UNDEPLOY == "true" && $CI_PIPELINE_SOURCE != "merge_request_event"
      when: on_success
    - if: $CI_PIPELINE_SOURCE == "merge_request_event"
      when: never
    - when: manual