I am trying to list the files in a directory and copy to some other directory.
This is my playbook:
---
- hosts: testserver
become: true
tasks:
- name: list files
command: " ls /root/"
register: r
- debug: var=r
- debug: msg="item.item={{item.item}}, item.stdout={{item.stdout}}, item.changed={{item.changed}}"
with_items: "{{r.results}}"
This is the error I am getting:
FAILED! => {"msg": "'dict object' has no attribute 'results'"}
答案 0 :(得分:1)
You have a debug
task there that shows you the contents of the variable r
. Do you see a key named results
?
You only see the results
key (and need to use item.item
) when are have registered values in a loop, as described here. You're not doing that, so the structure of r
will be much simpler.
If you're trying to iterate over the lines of the ls
output, you probably want:
- debug:
msg: "filename={{item}}"
with_items: "{{r.stdout_lines}}"
答案 1 :(得分:1)
I am trying to list the files in a directory and copy to some other directory.
Don't parse ls
output! Neither in Ansible, nor anywhere else.
Don't use command
module for what Ansible offers a native one.
Ansible has a find
module which returns a list of files. In your case:
- name: list files
find:
paths: /root
register: my_find
- debug:
var: item.path
with_items: "{{ my_find.files }}"