Search code examples
automationansibleansible-template

Ansible: Create Config based on File List


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!


Solution

  • 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