如何在我的 gitlab-ci.yml 中包含 script.py?

Kha*_*oud 6 include gitlab gitlab-ci

我正在为我的项目实现 gitlab-ci.yml 。在此 yml 文件中,我需要执行 script.py 文件。这个 script.py 位于不同的项目上,是否有办法包含这个 python 脚本而不将其上传到我的项目?

就像是:

include: 'https://gitlab.com/khalilazennoud3/<project-name>/-/blob/main/script.py
Run Code Online (Sandbox Code Playgroud)

Ada*_*all 9

无法“包含”不是管道定义模板的文件,但您仍然可以获取该文件。我的方法是在前一阶段添加第二个管道作业来克隆其他存储库,然后将您需要的文件作为工件上传。然后,在您需要该文件的作业中,它将提供可用的工件。

这是一个仅包含这两个作业的示例管道:

stages:
  - "Setup other Project Files" # or whatever
  - Build

Grab Python Script from Other Repo:
  stage: "Setup other Project Files"
  image: gitscm/git
  variables:
    GIT_STRATEGY: none
  script:
    - git clone git@gitlab.example.com:user/project.git
  artifacts:
    paths:
      - path/to/script.py.
    when: on_success # since if the clone fails, there's nothing to upload
    expire_in: 1 week # or whatever makes sense

Build Job:
  stage: Build
  image: python
  dependencies: ['Grab Python Script from Other Repo']
  script:
    - ls -la # this will show `script.py` from the first step along with the contents of "this" project where the pipeline is running
    - ./do_something_with_the_file.sh
Run Code Online (Sandbox Code Playgroud)

让我们逐行查看这些内容。对于第一份工作:

  1. 我们使用 Git 镜像,因为我们需要的是git
  2. GIT_STRATEGY: none变量告诉 Gitlab Runner 不要克隆/获取管道正在运行的项目。如果工作正在执行诸如向 Slack 发送通知、访问另一个 API 等操作,那么这非常有用。
  3. 对于脚本,我们所做的就是克隆其他项目,以便我们可以将文件作为工件上传。

对于第二份工作:

  1. 正常使用您用于此作业的任何图像
  2. 关键字dependencies控制该特定作业 1) 需要和 2) 下载先前阶段的哪些工件。默认情况下,会下载所有作业的所有可用工件。这个关键字控制着这一点,因为我们只需要文件script.py
  3. 在脚本中,我们只需确保该文件存在,无论如何,这只是一个临时的事情,然后您可以根据需要使用它。