GitLab CI/CD

CI/CD

简介

CI/CD 简单来说就是可以自动化编译、测试、打包我们的代码。

GitLab CICD的使用

首先需要安装gitlab-runner。

在GitLab 中,runners 是运行 CI/CD 作业的代理。我们的对代码的作业都是在runner上去执行的。我们可以在本地、服务器、等任意一个联网设备去安装我们的gitlab-runner。

Windows 安装gitlab-runner方法

  1. 在我们的本地目录创建 gitlab-runner 目录,并进入目录

  2. 打开PowerShell,下载gitlab-runner.exe

    1. 可通过PowerShell命令下载:输入

    Invoke-WebRequest -Uri "https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-windows-amd64.exe" -OutFile "gitlab-runner.exe"

    1. 或者直接官网下载:https://gitlab-runner-downloads.s3.amazonaws.com/latest/binaries/gitlab-runner-windows-amd64.exe
  3. 下载完之后,重命名文件为gitlab-runner.exe

  4. 注册,使用刚刚下载的exe文件,通过PowerShell命令执行

./gitlab-runner.exe register --url 你的url --registration-token 你的token

url和token在gitlab网站去复制自己账户的
GitLab CI/CD_第1张图片

除了需要填写该runner关联的url和token,还有runner的描述和标签tags,还有runner执行时候的脚本类型,这两个可以填任意填写。我这里tags填的test,下面会用到。

  1. 注册完之后,需使用管理员权限打开PowerShell,并进入到gitlab-runner目录依次执行以下命令:

.\gitlab-runner.exe install.\gitlab-runner.exe start

此后我们在上传代码时,同时上传我们的yml脚本,就能自动执行我们的任务。

yml脚本

在仓库的根目录下创建一个 .gitlab-ci.yml 文件。该文件是您定义 CI/CD 作业的地方。

例如以下脚本:

stages:
    - build
    - test
build-job:
  stage: build
  script:
    - echo "Hello, world!"
  tags:
    - test

test-job1:
  stage: test
  script:
    - echo "This job tests something"
  tags:
    - test
test-job2:
  stage: test
  script:
    - echo "This job tests something, but takes more time than test-job1."
    - echo "After the echo commands complete, it runs the sleep command for 20 seconds"
    - echo "which simulates a test that runs 20 seconds longer than test-job1"
    - sleep 2
  tags:
    - test

该脚本定义了三个作业任务build-job、test-job1、test-job2;

其中

  • stages:使用 stages 来定义包含作业组的阶段。stages 是为流水线全局定义的。上述的脚本表示build阶段会在test阶段之前运行。
  • stage:使用 stage 定义作业在哪个 stage 中运行。同一个 stage 中的作业可以并行执行。比如脚本中的test-job1和test-job2都属于test阶段,可以并行运行。

并行运行的条件:如果作业在不同的 runner 上运行,则它们可以并行运行。如果您只有一个 runner,如果 runner 的 concurrent 设置大于 1,作业可以并行运行。

  • tags:使用 tags 从项目可用的所有 runner 列表中选择一个特定的 runner。比如我们最开始在windows上安装了一个runner,在注册的时候填的tags为test。因此我这里脚本中所有的任务的tags都是test,表示我所有的任务都在我的windows的runner上去运行。

这个tags不填也是可以的,我们的runner可以在官网设置运行没有tags的任务。

GitLab CI/CD_第2张图片
GitLab CI/CD_第3张图片

  • script:使用 script 指定 runner 要执行的命令。上述脚本中都是一些shell指令

更多的关键字可参考官网https://docs.gitlab.cn/jh/ci/yaml/#script

执行结果

将上述脚本放在我们的git项目根目录下

GitLab CI/CD_第4张图片

我们通过git上传代码后,可以在GitLab中查看我们的pipeline,可以看到我们的三个任务执行情况

GitLab CI/CD_第5张图片

你可能感兴趣的:(gitlab,ci/cd,windows)