在 gitlab-ci.yml 管道中,如何正确使用 only 和 except 关键字?

In gitlab-ci.yml pipeline how can I use only and except keywords properly?

我的项目结构是这样的

├── main_project
│   ├── service1
│   │   ├── [...]
│   ├── service2
│   │   ├── [...]
│   ├── docs
│   │   ├── [...]
│   ├── .gitlab-ci.yml
    └── Makefile

我的.gitlab.ci-yml

 [...]
 service1_build:
  image: image
  stage: build
  script:
    - #doing something
  only:
    changes:
      - /service1/**/*
      - /.gitlab-ci.yml
      - /Makefile
  except:
    changes:
      - /docs/**/*

 service2_build:
  image: image
  stage: build
  script:
    - #doing something
  only:
    changes:
      - /service2/**/*
      - /.gitlab-ci.yml
      - /Makefile
  except:
    changes:
      - /docs/**/*

 test:
  image: image
  stage: test
  needs:
    - service1_build
    - service2_build
  script:
    - #doing something
  except:
    changes:
      - /docs/**/*

 service1_docker:
  image: image
  stage: docker
  needs:
    - test
  script:
    - #doing something
  only:
    refs:
      - master
    changes:
      - /service1/**/*
      - /.gitlab-ci.yml
      - /Makefile
  except:
    changes:
      - /docs/**/*

 service2_docker:
  image: image
  stage: docker
  needs:
    - test
  script:
    - #doing something
  only:
    refs:
      - master
    changes:
      - /service2/**/*
      - /.gitlab-ci.yml
      - /Makefile
  except:
    changes:
      - /docs/**/*
 [...]

我试过了,但不能正常工作。例如,如果我更改 docs 文件夹中的文件,test 作业将由管道执行。

这些是我想应用于每项工作的规则:

像这样适用吗?或者我该如何处理?当我给出路径时,它总是从 gitlab-ci.yml's 文件夹中查找它?

根据您的项目结构,您应该尝试像这样更改 only/except 路径:

only:
    changes:
      - main_project/service1/**/*
      - .gitlab-ci.yml
      - Makefile
  except:
    changes:
      - main_project/docs/**/*

这包括 main_project 目录。

您还应该向测试作业添加一些可选需求,因为如果 service1 上只有更新,测试作业将查看 service2 作业并失败:

test:
  stage: test
  needs:
    - job: service1_build
      optional: true
    - job: service2_build
      optional: true

我使用这些新修复程序进行了一些测试,您的规则运行正常:https://gitlab.com/sandbox_fm/ci-rules

您还应该考虑 moving from only/except to rules 因为:

only and except are not being actively developed. rules is the preferred keyword to control when to add jobs to pipelines.