如何在条件下使用 Ansible 在文件中搜索字符串

How to search for a string in a file using Ansible when condition

我在变量 listofips

中有一个由 '\n' 分隔的搜索字符串列表

我想在我的 playbook_dir

下的文件 hello.csv 中搜索字符串

我可能遇到了一些我不确定的语法问题,但下面是我尝试过的问题。

- set_fact:
    listofips: '10.0.0.1\n10.0.0.2\n10.0.0.3'

- set_fact:
    foundips: "{{ foundips + item + ', ' }}"
  when: lookup('file', "{{ playbook_dir }}/hello.csv").splitlines() | select('match', "{{ item }}") | list
  loop: "{{ listofips.split('\n') }}"

不幸的是,文件中存在搜索字符串,但在条件不匹配时可以解决。

我也想知道是否可以同时匹配 exact matchwild card

你能推荐一下吗?

有几个问题需要检查:

一个。 foundips: "{{ foundips + item + ', ' }}"

在第一个运行里条件会成立,foundips没有初始化,会报错。你应该使用:

foundips: "{{ foundips|default([]) + [item] }}"

b。 select 过滤器应使用此模式进行搜索:

select('match', '.*' + item + '.*')

c。 when 条件设置不正确。您转换为列表,但为了确保获得结果,您需要检查列表的长度是否 > 0:

when: lookup('file', "{{ playbook_dir }}/hello.csv").splitlines() | select('match', '.*' + item + '.*') | list | length > 0

d。如果你使用一个简单的调试任务来查看 split('\n') 是否按预期工作,你会发现它不是,你需要使用 double 反斜杠:

loop: "{{ listofips.split('\n') }}"

总结一下,请尝试这个任务:

  - set_fact:
      foundips: "{{ foundips|default([]) + [item] }}"
    when: lookup('file', "{{ playbook_dir }}/hello.csv").splitlines() | select('match', '.*' + item + '.*') | list | length > 0
    loop: "{{ listofips.split('\n') }}"

干杯