一、最基本的语法
- job :流水线中额作业
- script:执行的shell命令
- before_script:执行script之前执行
- after_script:在执行script之后执行
- stages:声明步骤,决定了流水线顺序
- stage:指明当前作业属于哪个步骤
- variables: 定义变量
二、实例演示
在代码仓创建.gitlab-ci.yml文件,内容如下:
before_script:
- echo "script in global before script..."
after_script:
- echo "script in global after script..."
variables:
USERNAME: redrose2100
PASSWORD: admin123
stages:
- build
- test
- release
- deploy
setup:
stage: .pre
script:
- echo "script in pre..."
teardown:
stage: .post
script:
- echo "script in post..."
build:
stage: build
before_script:
- echo "before script in build..."
- echo $USERNAME
- echo $PASSWORD
script:
- echo "script in build..."
after_script:
- echo "after script in build..."
test:
stage: test
before_script:
- echo "before script in test..."
script:
- echo "script in test..."
release:
stage: release
script:
- echo "script in release..."
after_script:
- echo "after in release..."
deploy:
stage: deploy
script:
- echo "script in deploy..."
然后提交代码仓,可以得到如下流水线执行结果:
三、流水线详细解读
3.1 stages声明执行步骤
不管.gitlab-ci.yml文件中各个作业代码的顺序如何,在执行流水线的时候是按照stages声明的顺序执行,如下stages声明的步骤
stages:
- build
- test
- release
- deploy
流水线中顺序与上述声明一致
3.2 stage声明当前作业所属的步骤
如下:stage后面声明当前作业属于build步骤,作业名子可以随便定义,但是stage后的步骤名必须在上面stages中声明的,否则会报错
build: # 这里可以随便定义
stage: build # 这里必须在上面stages中有声明
before_script:
- echo "before script in build..."
- echo $USERNAME
- echo $PASSWORD
script:
- echo "script in build..."
after_script:
- echo "after script in build..."
3.3 .pre和.post定义前置步骤和后置步骤
如下:stage使用.pre或.post声明,.pre表示此作业在左右作业执行之前执行,.post表示此作业在所有作业执行完成之后再执行
setup:
stage: .pre
script:
- echo "script in pre..."
teardown:
stage: .post
script:
- echo "script in post..."
执行的结果如下:
3.4 before_script在script执行之前执行,after_script在script执行之后执行
如下:
build:
stage: build
before_script:
- echo "before script in build..."
- echo $USERNAME
- echo $PASSWORD
script:
- echo "script in build..."
after_script:
- echo "after script in build..."
查看流水线如下
3.5 作业中的before_script和after_script比全局的优先级高
这里是指如果作业中有before_script或者after_script,则执行作业中的before_script和after_script,如果作业中没有,则会执行全局的before_script和after_script
如下:test作业中只有before_script,没有after_script
test:
stage: test
before_script:
- echo "before script in test..."
script:
- echo "script in test..."
查看流水线中执行结果,即执行了当前作业中的before_script,然后执行了全局的after_script
3.6 variables定义的变量在作业中均可使用
如下定义变量
variables:
USERNAME: redrose2100
PASSWORD: admin123
如下,在build作业中打印变量
3.7 script即执行shell命令
script即作业的核心内容,主要是通过命令行的方式调用,一般情况下runner为linux,因此这里的script的就是执行shell命令了,因此可以根据实际情况满足各种场景的需求
如下build作业,script中只是打印命令,实际场景中比如编译软件包,安装软件包,部署服务等等均可以做到
build:
stage: build
before_script:
- echo "before script in build..."
- echo $USERNAME
- echo $PASSWORD
script:
- echo "script in build..."
after_script:
- echo "after script in build..."
build作业的执行结果:
至此,GitlabCICD的主体骨架已经具备了