Reputation: 103
I'm trying to loop through a list of lines and write the lines to a file.
- command: "{{ item }}"
with_items:
- ls
- df -h
register: files
- lineinfile:
line: "{{ item.stdout }}"
path: /home/ubuntu/log/list.log
create: yes
loop: "{{ files.results | flatten }}"
loop_control:
label: item.stdout
But I am seeing below error:
'PermissionError' object is not subscriptable
I modified code as per @toydarian suggestion and working fine. if I have multiple tasks, I have changed as follows:
- command: "{{ item }}"
loop:
- "ls"
- "df -h"
register: files
- command: "{{ item }}"
loop:
- "ls -lrt"
- "du -h"
register: files1
- lineinfile:
line: "{{ item.stdout }}"
path: /home/ubuntu/log/list.log
create: yes
loop:
- "{{ files.results }}"
- "{{ files1.results }}"
delegate_to: localhost
I can see below error:
"The task includes an option with an undefined variable. The error was: 'list object' has no attribute"
Upvotes: 1
Views: 1298
Reputation: 4584
You have a small error in your loop. You can loop over files.results
and then use {{ item.stdout }}
as line
:
- command: "{{ item }}"
loop:
- "ls"
- "df -h"
register: files
- command: "{{ item }}"
loop:
- "ls -lrt"
- "du -h"
register: files1
- lineinfile:
line: "{{ item.stdout }}"
path: /home/ubuntu/log/list.log
create: yes
loop: "{{ files.results + files1.results }}"
Check the documentation on registering variables with a loop.
Note:
Depending on what you want to do, you might want to consider using ansible modules (e.g. find) instead of running things in command
or shell
tasks.
Upvotes: 2