一、安装模块
pip install pyyaml
二、host.yaml文件
k8s:
- role: node1
ip: 192.168.1.2
hostname: k8s-node1
- role: node2
ip: 192.168.1.3
hostname: k8s-node2
DB:
ip: 192.168.1.10
port: 3306
三、read_yaml.py
import yaml
import os
script_path = os.path.dirname(os.path.realpath(__file__))
yaml_path = os.path.join(script_path, "host.yaml")
cfg = open(yaml_path, 'r').read()
host_info = yaml.load(cfg,Loader=yaml.FullLoader)
print("node1的IP地址:%s" % host_info.get('k8s')[0].get('ip'))
print("DB的端口:%s" % host_info.get('DB').get('port'))
四、执行结果
![Python读取Yaml文件 Python读取Yaml文件](https://ctyun-collect-0531.gdoss.xstore.ctyun.cn/files/2022/10/09/5128e7b05d094889b3872f428b055a17.png)