Ansible-获取值的索引并在jinja模板中替换它

Ansible-获取值的索引并在jinja模板中替换它,ansible,jinja2,Ansible,Jinja2,我有一个清单文件,如: [cluster] node1 node2 node3 node4 我想在每台机器上创建一个文件,文件内容作为其节点的索引 所以, 目前,我可以通过以下方式访问jinja模板中的列表:groups['cluster'] 如何使用jinja模板来实现这一点?这是一种可能性。适应你自己的要求。如果使用循环控制,这里的关键点是(请参阅) 在列表的最后一个节点上应该发生什么?为澄清而编辑该列表有4个元素,基本上只是将索引放入相应节点上的文件中。最后一个节点将是相同的,它应该有一

我有一个清单文件,如:

[cluster]
node1
node2
node3
node4
我想在每台机器上创建一个文件,文件内容作为其节点的索引

所以,

目前,我可以通过以下方式访问jinja模板中的列表:
groups['cluster']


如何使用jinja模板来实现这一点?

这是一种可能性。适应你自己的要求。如果使用
循环控制
,这里的关键点是(请参阅)


在列表的最后一个节点上应该发生什么?为澄清而编辑该列表有4个元素,基本上只是将索引放入相应节点上的文件中。最后一个节点将是相同的,它应该有一个包含其索引3的文件
node1, should have a file `myfile.txt` with `0` inside 
node2, should have a file `myfile.txt` with `1` inside 
node3, should have a file `myfile.txt` with `2` inside 
node4, should have a file `myfile.txt` with `3` inside
- name: Create the needed files locally
  hosts: localhost
  gather_fact: false

  tasks:
    - name: Create a local file for each cluster host with its index as content
      copy:
        dest: "/tmp/myfile_{{ server }}.txt"
        content: "{{ server_index }}"
      loop: "{{ groups['cluster'] }}"
      loop_control:
        loop_var: server
        index_var: server_index

- name: Copy each files to the desired host
  hosts: cluster
  gather_facts: false

  tasks:
    - name: Copy file from local tmp to host
      copy:
        src: "/tmp/myfile_{{ inventory_hostname }}.txt"
        dest: /what/ever/path/myfile.txt"