Eduardo G
Eduardo G

Reputation: 440

Gitlab CI execute SAST jobs only when merging branch to master

Hello I'm trying to figure out how to run SAST jobs only when merging branch into master because they last 5 minutes and they are being run in every push for any branch.

This means that every time someone makes a push to their MR branch the security stage is executed with all SAST jobs.

What I want to achieve is that SAST jobs are executed when the branch is going to be merged to master.

gitlab-ci.yml:

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

stages:
  - security
  - tests

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

sast:
  stage: security

What I tried so far is using:

sast:
  stage: security
  only: 
    - master

But it fails because the included template Jobs/SAST.gitlab-ci.yml already uses rules and rules with only/except can't be used together.

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

Upvotes: 1

Views: 2090

Answers (2)

Mohammad Kamrani
Mohammad Kamrani

Reputation: 51

You can use this configuration:

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

phpcs-security-audit-sast:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event' 
      exists:
        - '**/*.php'

semgrep-sast:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      exists:
         - '**/*.go'
         - '**/*.html'
         - '**/*.js'
         - '**/*.jsx'
         - '**/*.ts'
         - '**/*.tsx'

gosec-sast:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      exists:
        - '**/*.go'

nodejs-scan-sast:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      exists:
        - '**/package.json'

bandit-sast:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      exists:
        - '**/*.py'

flawfinder-sast:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      exists:
        - '**/*.c'
        - '**/*.cpp'

eslint-sast:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      exists:
        - '**/*.html'
        - '**/*.js'
        - '**/*.jsx'
        - '**/*.ts'
        - '**/*.tsx'

spotbugs-sast:
  rules:
    - if: $CI_PIPELINE_SOURCE == 'merge_request_event'
      exists:
        - '**/*.groovy'
        - '**/*.java'
        - '**/*.scala'
        - '**/*.kt'

Upvotes: 2

Lalaluka
Lalaluka

Reputation: 1015

In the sourcecode Jobs/SAST.gitlab-ci.yml does not use except but rules which also are incompatible with only.

But you could also switch to rules syntax:

sast:
  stage: security
  rules:
    - if: "$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH"
      when: always

That should do the trick

Upvotes: 1

Related Questions