我有以下ansible任务
---
- name: Add inventory hosts to hosts file
template: src=hosts.j2 dest=/etc/hosts owner=root group=root mode=0644
with_dict: hosts
和jinja模板看起来像这样
{% for host in hosts %}
{{ host }}{% for domain in item.value.domains %} {{ host }}.{{ domain }}{% endfor %}{% if item.value.alias is defined %}{% for domain in item.value.domains %} {{ item.value.alias }}.{{ domain }}{% endfor %}{% endif %}
{% endfor %}
主机dict的地方是
主机:
'server1':
domains:
- 'com'
- 'net'
alias: 'opendj'
'server2':
domains:
- 'org'
alias: 'metadata'
我得到了
server1 server1.org metadata.org
server2 server2.org metadata.org
我应该怎样做才能达到正确的状态,即
server1 server1.com server1.net opendj.com opendj.net
server2 server2.org metadata.org
由于
答案 0 :(得分:2)
看起来它会做你想做的事情:
{% for host in hosts %}
{{ host }} {% for d in hosts[host]['domains'] %} {{ host }}.{{ d }}{% endfor %} {% for d in hosts[host]['domains'] %} {{ hosts[host]['alias'] }}.{{ d }}{% endfor %}
{% endfor %}
或者,如果你想要一个稍微漂亮的版本:
{% for host in hosts %}
{{ host -}}
{% for d in hosts[host]['domains'] %} {{ host }}.{{ d }}{% endfor -%}
{% for d in hosts[host]['domains'] %} {{ hosts[host]['alias'] }}.{{ d }}{% endfor %}
{% endfor %}
-
和{{ host -}}
语句末尾的{% endfor -%}
将取消在其他位置发生的跟踪换行符。
如果您只想在定义alias
时打印出别名:
{% for host in hosts %}
{{ host -}}
{% for d in hosts[host]['domains'] %} {{ host }}.{{ d }}{% endfor -%}
{% if hosts[host]['alias'] is defined %}
{% for d in hosts[host]['domains'] %} {{ hosts[host]['alias'] }}.{{ d }}{% endfor %}
{% endif %}
{% endfor %}