Loop files that will be used as variables

Hi ,

I’m using the template module that takes a J2 template and update the relevant fields.

My problem is When I want to create a file per file input should be used as variable – I’m actually need to understand how to loop file that should be used as var files

My J2 file

select * from {{ item.id}} where {{ item.color}}

My input files

File-1.yml :

Id: 1
color: blue

File-2**.yml** :

Id: 2
color: red

My Playbook – that is not working.

  • hosts: localhost
    become: true
    gather_facts: yes
    tasks:

  • name:
    template:
    src: /opt/input.sql.j2
    dest: /opt//{{item.id}}.sql
    with_items:

  • file-1.yaml

  • file-2.yaml

The output files I wish to have

1.sql

select * from 1 where blue

2.sql

select * from 2 where red

I think this answer might give you a pointer in the right direction: https://stackoverflow.com/a/52237675

It should work, but there could be a better/simpler way to do this. Do you control the generation of the files that provide your source variables?

What’s the actual problem you need to solve? (Obviously dynamically generating and presumably running some SQL but can you step back a level or two and describe the actual goal?)

Sorry - But i didnt fully understand your question

My input files are static - The problem that i’m trying to solve is how to loop “vars_file” for the same task

ב-יום רביעי, 14 ביוני 2023 בשעה 22:01:56 UTC+3, Will McDonald כתב/ה:

Sorry - But i didnt fully understand your question

My input files are static - The problem that i’m trying to solve is how to loop “vars_file” for the same task

What are you trying to achieve with the playbook?

*My J2 file*

select * from {{ item.id}} where {{ item.color}}

*My input files*

*File-1.yml :*
Id: 1
color: blue

*File-2**.yml** :*
Id: 2
color: red

*My Playbook – that is not working. *
- hosts: localhost
  become: true
  gather_facts: yes
  tasks:
    - name:
      template:
        src: /opt/input.sql.j2
        dest: /opt//{{item.id}}.sql
      with_items:
        - file-1.yaml

        - file-2.yaml

*The output files I wish to have *

1.sql
select * from 1 where blue

2.sql
select * from 2 where red

Given the files

  > cat file-1.yaml
  id: 1
  color: blue

  > cat file-2.yaml
  id: 2
  color: red

Read the files in the loop. Test it

  > cat pb.yml
  - hosts: localhost
    tasks:
      - debug:
          var: i
        loop:
          - file-1.yaml
          - file-2.yaml
        vars:
          i: "{{ lookup('file', item )|from_yaml }}"

gives (abridged)

  TASK [debug]

Vladimir Botka‏@
Thank you - it works

ב-יום ראשון, 18 ביוני 2023 בשעה 09:51:58 UTC+3, Vladimir Botka כתב/ה: