Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping using with_fileglob

How do i loop using "with_fileglob". I am trying to copy files matching wildcard, but with different permissions at the destination.

- hosts: myhost
  gather_facts: no
  tasks:
  - name: Ansible copy test
    copy:
      src: "{{ item.origin }}"
      dest: /home/user1/tmps/
      owner: user1
      mode: "{{item.mode}}"
    with_fileglob:
      - { origin: '/tmp/hello*', mode: '640'}
      - { origin: '/tmp/hi*', mode: '600'}

It throws error as below:

An exception occurred during task execution. To see the full traceback, use 
-vvv. The error was: AttributeError: 'dict' object has no attribute 'rfind'
like image 446
Webair Avatar asked Oct 26 '25 03:10

Webair


1 Answers

I think the cleanest way is to implement this, would be a nested loop with include_tasks.

Where you main playbook file contains:

...

vars:
  my_patterns:
    - origin: "/tmp/hello*"
      mode: "0640"
    - origin: "/tmp/hi*"
      mode: "0600"

tasks:
  - include_tasks: "my_glob.yml"
    with_items: "{{ my_patterns }}"
    loop_control:
      loop_var: my_pattern

...

and a subordinate my_glob.yml-tasks file:

---
- name: Ansible copy test
  copy:
    src: "{{ item }}"
    dest: /home/user1/tmps/
    owner: user1
    mode: "{{ my_pattern.mode }}"
  with_fileglob: "{{ my_pattern.origin }}"

Alternative method

Using Jinja2 to populate a list of objects { 'path': '...', 'mode': '...' }' based on fileglob-lookup plugin results.

vars:
  my_patterns:
    - origin: '/tmp/hello*'
      mode: '0640'
    - origin: '/tmp/hi*'
      mode: '0600'
tasks:
  - copy:
      src: "{{ item.paht }}"
      dest: /home/user1/tmps/
      owner: user1
      mode: "{{ item.mode }}"
    with_items: "[{% for match in my_patterns %}{% for file in lookup('fileglob', match.origin, wantlist=True) %}{ 'path':'{{ file }}','mode':'{{ match.mode }}'}{% if not loop.last %},{% endif %}{% endfor %}{% if not loop.last %},{% endif %}{% endfor %}]"

The above works if patterns are matched, you'd need to add checks if the results are not empty.

like image 100
techraf Avatar answered Oct 29 '25 08:10

techraf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!