日常运维中,有遇到需要校验YAML是否有问题的场景(例如从数据库的内容渲染出来的yaml配置文件)
import yaml
def main():
try:
with open("demo1.yaml", "r") as f:
config = yaml.load(f, Loader=yaml.SafeLoader)
print("YAML格式正确")
except Exception as e:
print(str(e))
print("YAML格式错误")
if __name__ == '__main__':
main()
但是这种有局限性,只能检测格式是否存在问题(对齐问题,是否多了空格之类的),不能对里面的内容进行检测(例如重复项)
例如下面这种demo.yaml
rule1:
- name: node
- instance: 192.168.31.181:9100
rule2:
name: mysql
instance: 192.168.31.181:9104
instance: 192.168.31.181:9104
可以看到 instance: 192.168.31.181:9104 重复出现,但是使用pyyaml这个模块无法检测出来。
官方文档 https://yamllint.readthedocs.io/en/stable/quickstart.html
1 安装
pip3 install yamllint
2 自定义配置文件 yamllint.config 内容如下
yaml-files:
- '*.yaml'
- '*.yml'
extends: relaxed
rules:
anchors: enable
braces: enable
brackets: enable
colons: false
commas: false
comments: false
comments-indentation: false
document-end: disable
document-start: false
empty-lines: false
empty-values: disable
float-values: disable
hyphens: enable
indentation: enable
key-duplicates: enable
key-ordering: disable
new-line-at-end-of-file: enable
new-lines: enable
octal-values: disable
quoted-strings: disable
truthy:
level: warning
trailing-spaces: false
line-length:
max: 2048
3 执行检测
yamllint -c yamllint.config demo.yaml
例如下面是检测alertmanager.yml的结果
4、其它
1) yamllint.config 的内容,可以根据自己情况去修改(我这里disable掉了很多非要紧的检测,如果要求要可以设置为enable)
2) 一般关注error即可,warning的不影响使用,改不改自己决定
3) 规则文件 https://yamllint.readthedocs.io/en/stable/rules.html
具体见官方文档 https://yaml.readthedocs.io/en/latest/
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有