如何使用ansible循环文件中的每一行?

问题描述 投票:14回答:4

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

我怎样才能在ansible中做到这一点?

ansible ansible-playbook
4个回答
21
投票

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

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

11
投票

假设你有一个类似的文件

item 1
item 2
item 3

并且您想要安装这些项目。只需使用register将文件内容传递给变量。并将此变量用于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

7
投票

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

它会读取你想要在你的剧本中使用的内容,但是不希望从本地控制机器(不是来自远程机器)的文件,管道,csv,redis等中包含在剧本中,这很重要,因为在大多数情况下,这些内容与本地计算机上的剧本一起使用),它适用于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等),然后将输出分成线并返回它们。

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


1
投票

最新的Ansible recommends loop而不是with_something。它可以与lookupsplitlines()结合使用,正如Ikar Pohorský所指出的:

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

files/branches.txt应该与剧本相关

© www.soinside.com 2019 - 2024. All rights reserved.