如何在Ansible中将数组传递给已注册的变量?

我想列出一个目录中的文件并将其复制到其他目录。如何在Ansible中将数组传递给已注册的变量?

这是我的剧本:

--- 

- 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}}"

这是我收到的错误:

失败! => {“味精”:“'字典对象有没有属性‘结果’”}

回答:

你有一个debug任务那里,说明你的变量r的内容。你看到一个名为results的钥匙吗?

当在循环中有注册值时,您只能看到results密钥(并且需要使用item.item),如here所述。你不这样做,所以r的结构将会简单得多。

如果你想遍历ls输出的线,你可能想:

- debug: 

msg: "filename={{item}}"

with_items: "{{r.stdout_lines}}"

回答:

我试图列出目录中的文件复制到其他目录。

  1. Don't parse ls output!既不Ansible,也没有任何其他地方。

  2. 请不要使用command模块Ansible提供的本地模块。

Ansible有一个find module它返回一个文件列表。你的情况:

- name: list files 

find:

paths: /root

register: my_find

- debug:

var: item.path

with_items: "{{ my_find.files }}"

以上是 如何在Ansible中将数组传递给已注册的变量? 的全部内容, 来源链接: utcz.com/qa/260971.html

回到顶部