1

I'm a little confused on how to make this work and need a better understanding in terms of the ansible side of getting the following done:

I have 500 images and I need to generate a default json config based on the image names. For example:

1.jpg
2.jpg
3.jpg
etc etc

From that list, I need to generate the following:

1.json
2.json
3.json
etc etc

When it's all said and done the directory should have 500 images and 500 json files. I would also like to have that json file as a j2 template so I can pre define some information in the json file based on the project in a group_var.

I know I can do the following to copy the template doing this:

- name: Copy JSON Configuration
  ansible.builtin.template:
    src: sample.json.j2
    dest: /path/to/directory

I'm just lost in the part to generate the list of the json files based on the image list. I have googled some stuff that is maybe the same but what I have found seem way beyond what I needed to get done or I'm not simply understanding it correctly. Thank you for any and all help I really appreciate it!

mvelez83
  • 161
  • 1
  • 1
  • 9

1 Answers1

1

For example, given the tree

shell> tree test-616
test-616
├── 1.jpg
├── 2.jpg
└── 3.jpg

and the template

shell> cat sample.json.j2
{{ item }}

Find the files and iterate the paths

    - find:
        path: test-616
      register: result
    - template:
        src: sample.json.j2
        dest: "{{ _item }}.json"
      loop: "{{ result.files|map(attribute='path')|list }}"
      vars:
        _item: "{{ item|splitext|first }}"

This will create the files

shell> tree test-616
test-616
├── 1.jpg
├── 1.json
├── 2.jpg
├── 2.json
├── 3.jpg
└── 3.json
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • Hello Vladimir thank you for your example and explanation. This is exactly what I needed and it worked perfectly. The other examples I ran into seemed like so much but you broke it down in a way that was easy to understand thank you so much! – mvelez83 Mar 04 '22 at 01:08