You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置GitLab CI流水线,确保销毁步骤不受前置任务状态影响?

如何确保GitLab CI中destroy-infra任务无论流水线成败都运行?

我有一个运行集成测试的GitLab CI流水线,配置如下:

default:
  image: ImageFoo


before_script:
  - . ./CI/before_script.sh

stages:
  - code-analyze
  - build
  - infra
  - integration-test
  - tear-down

.base:
  tags:
    - gitlab-runners-220707-195833-small

check-style:
  extends: .base
  stage: code-analyze
  script: ./gradlew styleCheck

build-code:
  extends: .base
  stage: build
  script:
    - ./gradlew clean
    - ./gradlew build -x detekt
  artifacts:
    paths:
      - $CI_PROJECT_DIR/fooA/build/libs/fooA.jar
      - $CI_PROJECT_DIR/fooB/build/libs/fooB.jar
      - $CI_PROJECT_DIR/fooC/build/libs/fooC.jar

build-infra:
  extends: .base
  stage: infra
  script:
    -  . ./terraform/test_apply.sh -w foo
  artifacts:
    reports:
      dotenv: $CI_PROJECT_DIR/build.env
  needs:
    - job: build-code
      artifacts: true

run-integration-test:
  extends: .base
  stage: integration-test
  script:
    - . ./CI/.variables
    - ./gradlew integrationTest -D$A -D$B -D$C
  needs:
    - job: build-infra
      artifacts: true

destroy-infra:
    extends: .base
    stage: tear-down
    script:
      - . ./terraform/test_destroy.sh -w foo

当前存在以下失败场景,我需要执行destroy-infra任务:

  • build-infra失败
  • run-integration-test失败

解决方案

要让destroy-infra任务在流水线任何情况下(包括前面任务失败、流水线中断)都执行,通过以下GitLab CI特性组合实现:

  1. 核心配置:添加when: always
    给destroy-infra任务加上when: always,它会忽略前面任务的执行状态,强制触发该任务。这是实现“无论成败都运行”的基础。

  2. 优化触发条件:结合needs与optional: true
    为了避免因更早的任务失败(比如build-code失败导致build-infra未执行)而让destroy-infra被跳过,添加needs配置并设置optional: true,确保即使依赖的任务没运行,销毁任务仍能执行:

    destroy-infra:
        extends: .base
        stage: tear-down
        script:
          - . ./terraform/test_destroy.sh -w foo
        when: always
        needs:
          - job: build-infra
            optional: true  # 允许build-infra未执行的情况
            artifacts: false # 若不需要build-infra的产物,可设为false
    
  3. 处理手动中断场景
    when: always同样支持流水线被手动停止的场景,只要runner正常工作,销毁任务会自动触发。

  4. 精细控制(可选)
    如果需要仅在特定状态下执行(同时覆盖成功和失败),也可以用rules配置,但直接用when: always更简洁:

    destroy-infra:
        extends: .base
        stage: tear-down
        script:
          - . ./terraform/test_destroy.sh -w foo
        rules:
          - if: '$CI_PIPELINE_STATUS == "failed"'
            when: always
          - if: '$CI_PIPELINE_STATUS == "success"'
            when: always
    

内容的提问来源于stack exchange,提问作者CyberPunk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:17:10