考虑以下测试手册:
---
- name: Playbook
hosts: localhost
become: false
gather_facts: false
vars:
modes:
- ReadWriteOnce
tasks:
- name: Template output
ansible.builtin.debug:
msg: "{{ lookup('ansible.builtin.template', 'template.j2') }}"
及相关
template.js
Jinja2 模板:
storage:
accessModes:
{{ modes | to_nice_yaml | indent(4) }}
resources:
requests:
storage: 5Gi
输出为:
ok: [localhost] =>
msg: |-
storage:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 50Gi
我的目标是删除
ReadWriteOnce
列表元素后面的空行,同时保留上面显示的确切 yaml 结构。我尝试在模板中设置换行符抑制,在 -
之后使用 indent(4)
:
storage:
accessModes:
{{ modes | to_nice_yaml | indent(4) -}}
resources:
requests:
storage: 5Gi
不幸的是,这会产生意外的 yaml 格式,请注意
resources
:
ok: [localhost] =>
msg: |-
storage:
accessModes:
- ReadWriteOnce
resources: <-- resources are shifted to left, by two spaces
requests:
storage: 5Gi
我想知道这个问题的正确解决方法是什么?谢谢您的建议。
仅使用模板创建结构
shell> cat template.j2
storage:
accessModes: {{ modes }}
resources:
requests:
storage: 5Gi
模板查找插件的输出是一个字符串。将其转换为 YAML。例如,
result: "{{ lookup('template', 'template.j2') | from_yaml }}"
然后要求过滤器to_nice_yaml格式化输出
- debug:
msg: |
{{ result | to_nice_yaml(indent=4) }}
给予
msg: |-
storage:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
您必须要求 Ansible 回调来编写 YAML。例如,
shell> ANSIBLE_CALLBACK_RESULT_FORMAT=yaml ansible-playbook pb.yml
备注:
python yaml.dump 错误缩进。
shell> cat pb.yml
- hosts: localhost
gather_facts: false
vars:
modes: [ReadWriteOnce]
tasks:
- debug:
msg: |
{{ result | type_debug }}
{{ result | to_nice_yaml(indent=4) }}
{{ result | to_nice_yaml | indent(4, true) }}
{{ result | to_nice_yaml(indent=4) | indent(4) }}
vars:
result: "{{ lookup('template', 'template.j2') | from_yaml }}"
# result: "{{ lookup('template', 'template.j2') }}"