Setting facts from a loop

559 views
Skip to first unread message

lift...@gmail.com

unread,
Jul 7, 2021, 3:53:04 PM7/7/21
to Ansible Project
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

Matt Martz

unread,
Jul 7, 2021, 3:55:20 PM7/7/21
to ansible...@googlegroups.com
`register` must be static, you cannot template it.

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


--
You received this message because you are subscribed to the Google Groups "Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ansible-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/53a48929-bee0-4761-8af9-f39c92549770n%40googlegroups.com.


--
Matt Martz
@sivel
sivel.net

lift...@gmail.com

unread,
Jul 7, 2021, 4:01:06 PM7/7/21
to Ansible Project
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

Reply all
Reply to author
Forward
0 new messages