1+1=10

扬长避短 vs 取长补短

GitLab CI从0到1笔记(基于Python)

从简单的python程序开始,了解一下Gitlab CI。

准备git仓库

仓库中放置一个python文件 : test_1.py

该文件需要满足pytest基本要求,即

  • 文件以 test_开头,或者以 _test.py结尾
  • 文件内待测函数以 test_ 开头
import pytest

def test_hello():
    print('Hello Actions!')

例子一

创建CI文件

仓库根目录中 .gitlab-ci.yml

内容很简单:

image: python:latest

test:
  script:
    - pip install pytest
    - pytest

如果要用python虚拟环境,可以:

image: python:latest

before_script:
  - python --version ; pip --version  # For debugging
  - python -m venv venv
  - source venv/bin/activate

test:
  script:
    - pip install pytest
    - pytest

将其推送到gitlab远端仓库,即可自动执行。

不过这个东西只在Linux跑,怎么支持Windows?

例子二

与GitHub中的workflows不同,根目录下只有一个.gitlab-ci.yml文件,如果需要在Windows下执行Runner怎么弄?

修改根目录中的 .gitlab-ci.yml 文件,创建两个job:

test_linux:
  image: python:latest
  script:
    - pip install pytest
    - pytest

test_win32:
  tags:
    - windows
  script:
    - choco install python --yes --version 3.11.0
    - $env:Path = "C:\Python311\;C:\Python311\Scripts\;" + $env:Path
    - python -m pip install --upgrade pip
    - pip install pytest
    - pytest

结果如下:

gitlab-ci-result

注意:Windows下的速度很慢,因为不像在Linux下可以用docker,它需要虚拟机,而且里面没有python,需要先安装。不过:

  • Windows runner 的命令环境是 PowerShell。
  • 在 GitLab Windows shared runner 內,预装Chocolatey,可用于安装必要的程序。
  • Windows runner 不是 Docker 容器,无法在 .gitlab-ci.yml 使用 imageservices

.gitlab-ci.yml

GitLab CI的Pipeline由 若干个 stage 构成,每个stage中可包含若干个job。每个job的runner都是独立的,彼此之间没有共享资源。

gitlab-pipeline

一个具体的例子

default:
  tags:
  - windows

stages:
  - build
  - test

before_script:
 - Set-Variable -Name "time" -Value (date -Format "%H:%m")
 - echo ${time}
 - echo "started by ${GITLAB_USER_NAME}"

build:
  stage: build
  script:
  - echo "running scripts in the build job"

test:
  stage: test
  script:
  - echo "running scripts in the test job"
  • default设定的是默认值,其他job都可以覆盖它。

  • Runner的选择需要通过tags来指定。

  • 各个stage的先后顺序通过stages设置。

  • 每个Job的脚本执行前,需要执行相同的指令。可以放置到before_script中。

参考

  • https://docs.gitlab.com/ee/ci/
  • https://docs.gitlab.com/ee/ci/yaml/
  • https://about.gitlab.com/blog/2020/01/21/windows-shared-runner-beta/

Comments