Setting facts from a loop

I have a playbook where I’m trying to use the find module to find files owned by a certain user. I’m trying to do register a variable to hold the files found for each folder within the loop as follows:

vars:
folders:

  • folder: “/folder1”
    var: “temp_folder1”
  • folder: “folder2”

var: “temp_folder2”

tasks:

  • name: Find all files under {{ item.folder }}
    find:
    paths: “{{ item.folder }}”
    recurse: yes
    register: “{{ item.var }}”
    loop: “{{ folders }}”

I get a warning stating “register” is not templatable, then an error stating “Invalid variable name in ‘register’ specified: '{{ item.var }}”

Do I have to do this individually instead of via a loop?

Thanks,
Harry

register must be static, you cannot template it.

See the following link for information about registering a variable with a loop:

https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html#registering-variables-with-a-loop

OK, so if I had 10 folders I was looping through, and set the register variable to “tmp_folder” for example, how would I know then loop through that 1 variable to pull out the info I need? The next step is to set a fact based on the returned files that match a certain user name. Would the fact be something like this:

set_fact:

temp_folder1_files: “{{ tmp_folder[0].files | selectattr(‘pw_name’, ‘equalto’, remove_user) | list }}”
temp_folder2_files: “{{ tmp_folder[1].files | selectattr(‘pw_name’, ‘equalto’, remove_user) | list }}”
temp_folder3_files: “{{ tmp_folder[2].files | selectattr(‘pw_name’, ‘equalto’, remove_user) | list }}”

Thanks,
Harry