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

如何仅在分支合并至master时执行GitLab CI的SAST任务

解决GitLab CI中仅合并到master时执行SAST任务的问题

需求说明

希望仅在分支合并到master分支时执行SAST任务,该任务耗时5分钟,当前每次推送任意分支(包括MR分支)都会触发安全阶段的所有SAST任务。

当前gitlab-ci.yml配置

include:
  - template: Jobs/SAST.gitlab-ci.yml

stages:
  - security
  - tests

my_tests:
  stage: tests
  script:
    - echo Running tests ...

sast:
  stage: security

尝试的错误配置

曾尝试添加only关键字限制执行分支,但执行失败:

sast:
  stage: security
  only: 
    - master

报错信息

jobs:sast config key may not be used with rules: only

解决方案

由于引入的Jobs/SAST.gitlab-ci.yml模板已使用rules关键字,GitLab CI不允许同一个job同时混用rules与only/except,因此需要用rules替代only来定义执行条件。

修改后的sast job配置如下:

sast:
  stage: security
  rules:
    # 直接推送到master分支时执行
    - if: '$CI_COMMIT_BRANCH == "master"'
    # 合并请求目标分支为master时执行
    - if: '$CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"'

这样配置后,SAST任务只会在直接推送到master分支或合并请求目标分支为master时触发,满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:35:22