Yaml todo
Schema
常见的 yaml 文件的 schema 通常不需要专门指定, 代码编辑器及插件会自动设置.
若需要手动指定, 则可以在 yaml 文件中, 在注释中使用特定的格式来指定 schema.
yaml
## 格式
# yaml-language-server: $schema=URLyaml
## 举例
# yaml-language-server: $schema=https://json.schemastore.org/github-action.jsonAnchor
在YAML中, 可以使用 "anchor" 来标记某个节点, 然后在文档的其他位置通过 * 符号来引用这个锚点, 以避免重复输入相同的内容. 这可以提高文件的可读性和维护性.
yaml
doc-tests:
<<: *job_configuration
script:
- cargo test --doc
unit-tests:
<<: *job_configuration
script:
- cargo test --lib
# `&` 字符后面才是 anchor 的名称.
.job_template: &job_configuration
image: rust
rules:
- if: $ENABLE_TEST == "true"yaml
doc-tests:
image: rust
rules:
- if: $ENABLE_TEST == "true"
script:
- cargo test --doc
unit-tests:
image: rust
rules:
- if: $ENABLE_TEST == "true"
script:
- cargo test --lib也可以通过这种方式使用:
yaml
job:
script:
- *some-script-before
- echo "Execute something else, for this job only"
.some-script-before: &some-script-before
- echo "Execute this script first"
- echo "Execute this script second"yaml
job:
script:
- echo "Execute this script first"
- echo "Execute this script second"
- echo "Execute something else, for this job only"换行
INFO
这里我们仅讨论 "给字段赋值时的换行规则".
请参考 StackOverflow 的这条回答.
有些时候我们在给字段赋值时, 可能会因为单行字符数过多而考虑换行.
此时 无需 在行尾使用 \ 等符号, 直接换行即可, yaml parser 会自动将多行拼接成一行.
yaml
# 通过多行赋值
build-job:
script:
- docker build .
-t $IMAGE_NAME_TAG
--platform linux/amd64
--quiet
# 效果等同于单行
build-job:
script:
- docker build . -t $IMAGE_NAME_TAG --platform linux/amd64 --quiet但有些时候我们希望能让 yaml parser 不要自动拼接成单行, 此时可以借助 | 字符实现.
yaml
services:
gitlab:
image: gitlab/gitlab-ee:latest
container_name: gitlab
hostname: gitlab
restart: always
environment:
GITLAB_OMNIBUS_CONFIG: |
gitlab_rails['gitlab_default_projects_features_snippets'] = false
gitlab_rails['gitlab_default_projects_features_container_registry'] = false
prometheus_monitoring['enable'] = false受到 | 字符影响的字符串, 可以被近似理解为 raw string.
不过在 yaml 中, | 所影响的字符串依然会 "正常替换环境变量".
TIP
| 字符还可以用于避免特殊符号带来的问题.
例如 : 在 yaml 中比较特殊, 如果希望在某个字符串中使用 :, 则可以借助 |.