如何使用 ansible 遍历文件中的每一行?

How do I loop over each line inside a file with ansible?

我正在寻找类似于 with_items: 的东西,但它会从文件中获取项目列表,而不必将其包含在剧本文件中。

如何在 ansible 中执行此操作?

假设你有一个像

这样的文件
item 1
item 2
item 3

并且您想安装这些项目。只需使用寄存器将文件内容获取到变量即可。并将此变量用于 with_items。确保您的文件每行有一项。

---
- hosts: your-host
  remote_user: your-remote_user
  tasks:
  - name: get the file contents
    command: cat /path/to/your/file
    register: my_items
  - name: install these items
    pip: name:{{item}}
    with_items: my_items.stdout_lines

我设法找到了一个简单的替代方法:

- debug: msg="{{item}}"
  with_lines: cat files/branches.txt

我很惊讶没有人提到 ansible Lookups,我认为这正是你想要的。

它从文件、管道中读取您想在剧本中使用但不想包含在剧本中的内容csvredis 等来自 你的本地控制机器(不是来自远程机器,这很重要,因为在大多数情况下,这些内容与您本地机器上的剧本一起),并且它适用于 ansible 循环。

---
- hosts: localhost
  gather_facts: no
  tasks:
    - name: Loop over lines in a file
      debug:
        var: item
      with_lines: cat "./files/lines"

with_lines 这里实际上是带行查找的循环,要了解 lines 查找是如何工作的,请参阅代码 here,它只运行你给它的任何命令(所以你可以给它任何东西,如 echo、cat 等),然后 split 将输出分成行和 return 它们。

有许多强大的查找功能,要获得全面的列表,请查看 lookup plugins folder

最新Ansible recommends loop instead of with_something. It can be used in combination with lookup and splitlines(), as 指出:

- debug: msg="{{item}}"
  loop: "{{ lookup('file', 'files/branches.txt').splitlines() }}"

files/branches.txt 应该是相对于 playbook