Ansible output jinja2 loop to a different files

I have the following in my vars file.

aux:                "SHR"
cluster_nodes:
- { node_name: sudora123a, node_num: 1, inst_num: "123A" }
- { node_name: sudora123b, node_num: 2, inst_num: "123B" }

I am trying to loop through each node_name and write out to different files.

My template:

  (SID_LIST =
                (SID_NAME = {{ aux }}{{ cn.inst_num }})
        )
  )

I would like to have 2 different files created to have outputs like this.
file1.out

  (SID_LIST =
                (SID_NAME =SHR123A)
        )
  )

file2.out

  (SID_LIST =
                (SID_NAME =SHR123B)
        )
  )

See if this helps. (In a real case you’d use ansible.builtin.template, but this example uses ansible.builtin.copy with content: to keep it all together.)

---
# Shiraz_Kamal_01.yml
- name: Looping over cluster nodes
  hosts: localhost
  gather_facts: false
  vars:
    aux: "SHR"
    cluster_nodes:
      - { node_name: "sudora123a", node_num: 1, inst_num: "123A" }
      - { node_name: "sudora123b", node_num: 2, inst_num: "123B" }
  tasks:
    - name: I am trying to loop through each node_name and write out to different files.
      ansible.builtin.copy:
        dest: 'file{{ cn.node_num }}.out'
        mode: '0644'
        content: |
          # file{{ cn.node_num }}.out
          (SID_LIST =
                        (SID_NAME = {{ aux }}{{ cn.inst_num }})
                )
          )
      loop: '{{ cluster_nodes }}'
      loop_control:
        loop_var: cn

The output looks like this:

$ cat file1.out file2.out
# file1.out
(SID_LIST =
              (SID_NAME = SHR123A)
      )
)
# file2.out
(SID_LIST =
              (SID_NAME = SHR123B)
      )
)
1 Like

@utoddl thank you so much! that works!