CI/CD variables are a type of environment variable. You can use them to:
You can use predefined CI/CD variables or define custom:
说人话就是:
环境变量是一个动态命名的值,它可以影响正在运行的进程在操作系统上的行为方式。
环境变量是进程在其中运行的环境的一部分. 例如,正在运行的进程可以查询TEMP环境变量的值以发现合适的位置来存储临时文件,或者为可以在不同脚本中重用的数据库定义URL 。
变量对于在 GitLab CI / CD 中自定义作业很有用,使用变量时,不必对值进行硬编码。
我们可以预定义变量在.gitlab-ci.yml中且无需声明,更相当于一种内置变量
test_variable:
stage: test
script:
- echo "$CI_JOB_STAGE"
You can create custom CI/CD variables:
You can override variable values manually for a specific pipeline, or have them prefilled in manual pipelines.
There are two types of variables: File or Variable.
Variable names are limited by the shell the runner uses to execute scripts. Each shell has its own set of reserved variable names.
Make sure each variable is defined for the scope you want to use it in.
By default, pipelines from forked projects can’t access CI/CD variables in the parent project. If you run a merge request pipeline in the parent project for a merge request from a fork, all variables become available to the pipeline.
大意就是:
你可以手动覆盖某个流水线的变量值,或者在手动管道中预先填充它们。
variables:
TEST_VAR: "All jobs can use this variable's value"
job1:
variables:
TEST_VAR_JOB: "Only job1 can use this variable's value"
script:
- echo "$TEST_VAR" and "$TEST_VAR_JOB"
To add or update variables in the project settings:
Go to your project’s Settings > CI/CD and expand the Variables section.
Select the Add Variable button and fill in the details:
i - Key: Must be one line, with no spaces, using only letters, numbers, or _.
ii - Value: No limitations.
iii - Type: File or Variable.
iv - Environment scope: Optional. All, or specific environments.
v - Protect variable Optional. If selected, the variable is only available in pipelines that run on protected branches or tags.
vi - Mask variable Optional. If selected, the variable’s Value is masked in job logs. The variable fails to save if the value does not meet the masking requirements.
基于gitlab自身提供的api接口
GET /projects/:id/variables
如:
curl --header "PRIVATE-TOKEN: kJZ9Ahxs39-xhsptT1bn" "http://192.168.137.14/api/v4/projects/7/variables"
由于我的项目没有变量,所以为空。
POST /projects/:id/variables
如:
curl --request POST --header "PRIVATE-TOKEN: kJZ9Ahxs39-xhsptT1bn" \
"https://192.168.137.14/api/v4/projects/7/variables" --form "key=name" --form "value=wangkx"
GET /projects/:id/variables/:key
如:
curl --header "PRIVATE-TOKEN: kJZ9Ahxs39-xhsptT1bn" "http://192.168.137.14/api/v4/projects/7/variables/name"
PUT /projects/:id/variables/:key
如:
curl --request PUT --header "PRIVATE-TOKEN: kJZ9Ahxs39-xhsptT1bn" "http://192.168.137.14/api/v4/projects/7/variables/name" --form "value=wangkaixuan"
DELETE /projects/:id/variables/:key
如:
curl --header "PRIVATE-TOKEN: kJZ9Ahxs39-xhsptT1bn" "http://192.168.137.14/api/v4/projects/7/variables/name"
不再赘述,通“使用变量的方式”中的“3”。