Ansible YAML缩进配置:外层列表0偏移,子列表2偏移
解决Python yaml.dump保留Ansible YAML缩进规则的问题
要让Python导出的YAML符合Ansible的缩进要求(外层任务列表0偏移,when子列表2偏移),需要调整YAML库的缩进配置,以下是两种可行方案:
方案一:使用PyYAML配置精细缩进参数
PyYAML通过调整indent、block_seq_indent等参数可以实现需求,同时要关闭键排序避免破坏Ansible任务结构:
import yaml # 示例Ansible任务数据 ansible_tasks = [ { "name": "Ensure nginx is installed", "apt": {"name": "nginx", "state": "present"}, "when": [ "ansible_os_family == 'Debian'", "nginx_not_installed | bool" ] } ] # 配置dump参数 output_yaml = yaml.dump( ansible_tasks, indent=2, # 映射类型(如apt、when字段下的内容)的缩进 block_seq_indent=0,# 外层序列(任务列表)的项缩进设为0 default_flow_style=False, # 强制使用块格式而非流格式 sort_keys=False, # 不自动排序键,保留原有字段顺序 allow_unicode=True ) # 打印或写入文件 print(output_yaml) with open('tasks.yml', 'w') as f: f.write(output_yaml)
方案二:使用ruamel.yaml(更可靠的格式保留)
如果PyYAML的配置仍无法满足需求,推荐使用ruamel.yaml——它专为保留YAML原有格式设计,缩进控制更精细:
- 先安装库:
pip install ruamel.yaml
- 编写代码:
from ruamel.yaml import YAML # 初始化YAML实例并配置缩进 yaml = YAML() yaml.indent( mapping=2, # 映射类型的缩进(如apt下的键值对) sequence=2, # 序列类型的项缩进(如when下的子列表) offset=0 # 外层序列(任务列表)的偏移设为0 ) yaml.sort_keys = False # 保留字段原有顺序 # 示例任务数据 ansible_tasks = [ { "name": "Ensure nginx is installed", "apt": {"name": "nginx", "state": "present"}, "when": [ "ansible_os_family == 'Debian'", "nginx_not_installed | bool" ] } ] # 导出到文件 with open('tasks.yml', 'w') as f: yaml.dump(ansible_tasks, f)
两种方案导出的YAML都会符合你的要求:外层任务列表的- name为0偏移,when字段下的子列表项为2偏移。
内容的提问来源于stack exchange,提问作者Zafer Balkan
相关产品推荐
相关产品推荐

