模板列表中每个项目的单个模板(Jinja2,Anisble)

时间:2017-10-03 09:29:27

标签: ansible jinja2

我有一个Jinja模板如下

{% for cust, config in customers.items() %}
sim.gw.{{ cust|lower }}.mw.tport.type=udp
sim.gw.{{ cust|lower }}.mw.tport.udp.interface=lo
{% if config['accept'] is defined %}
sim.gw.{{ cust|lower }}.fix.accept_port={{ config['accept'] }}
{% endif %}
sim.gw.{{ cust|lower }}.fix.version=4.4
sim.gw.{{ cust|lower }}.fix.tagetsubid={{ config['type'] }}
sim.gw.{{ cust|lower }}.fix.sess.sendercompid0=CITIFX-UAT
sim.gw.{{ cust|lower }}.fix.sess.targetcompid0={{ cust }}-S-QUOTE
sim.gw.{{ cust|lower }}.fix.sess.sendercompid1=CITIFX-UAT
sim.gw.{{ cust|lower }}.fix.sess.targetcompid1={{ cust }}-S-TRADE
sim.gw.{{ cust|lower }}.fix.handler=libfixpythonhandler.so
sim.gw.{{ cust|lower }}.fix.py_script=pySimulator.py
sim.gw.{{ cust|lower }}.log={{ cust|lower }}.log
{% endfor %}

即使用此客户yml文件中的变量:

BTG-VELOCITY:
    type: PBSTP
    accept: 1010
GFAM:
    type: PBSTP
    connect: 1010
ONEZERO2:
    type: TRADESTREAM
GUANFABANK:
    type: FXSIM
MAINBANK:
    type: FXSIM
TYPOBANK:
    type: TRADESTREAM
TEST-BANK:
    type: PBSTP
    connect: 32620
    accept: 33620
WEAKBANK:
    type: TRADESTREAM

当我运行我的剧本时,我正在使用此配置:

- include_vars:
    file: /home/vagrant/stunnelSimAnsPractice/roles/ns16/vars/customers.yml
    name: customers
- name: templating
  template:
    src: /home/vagrant/stunnelSimAnsPractice/roles/ns16/templates/simulator.properties.j2
    dest: /home/vagrant/stunnelSimAnsPractice/roles/ns16/sessions/{{ item }}/simulator.properties
    owner: root
    group: root
  register: result
  with_items: "{{ customers }}"

我的问题是我希望创建一个个人的“模拟器”属性'为每个客户。目前,我的playbook生成一个包含所有客户所有属性的long simulator.properties,并将相同的文件放在每个客户目录中。输出应该对每个客户都是唯一的,这样每个目录只包含给定客户的属性。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

从模板中删除{% for...{% endfor...行,因为您只需要一个客户在结果文件中。并按如下方式执行模板任务:

- name: templating
  template:
    src: /home/vagrant/stunnelSimAnsPractice/roles/ns16/templates/simulator.properties.j2
    dest: /home/vagrant/stunnelSimAnsPractice/roles/ns16/sessions/{{ item }}/simulator.properties
    owner: root
    group: root
  register: result
  vars:
    cust: "{{ item.key }}"
    config: "{{ item.value }}"
  with_dict: "{{ customers }}"