Ansible Lineinfile-期望一个或另一个

时间:2019-02-25 14:14:23

标签: ansible

我的ansible将som项目从称为模块的列表中删除。我要确保这些项目在txt文件中。

- name: copy modules to setup file
  lineinfile:
   path: /etc/path/txt
   line: "#{{ item }}"
   state: present
   regexp: "{{ item }}"
  with_items: "{{ modules }}"
  when: modules is defined and (modules | length > 0)

因此,这应该在列表中添加“ #item”,但是问题是,我不希望它覆盖“ item”。应该是某种备份,添加有注释的项目,但是只有在文件中没有注释的情况下,才有办法吗?

2 个答案:

答案 0 :(得分:0)

也许您可以两次使用此任务。在第一个带有check的项中:true并注册该结果,以便在when条件下将其声明在第二个任务中。

答案 1 :(得分:0)

一种选择是测试整个文件中 item 的存在。

- set_fact:
    content: "{{ lookup('file','/etc/path/txt') }}"
- name: copy modules to setup file
  lineinfile:
    path: /etc/path/txt
    line: "#{{ item }}"
    state: present
  loop: "{{ modules|default([]) }}"
  when: not content|regex_search('.*' + item + '.*' | string)
  • modules | default([])”解决了缺少的测试“模块已定义”。
  • 测试“ 模块|长度> 0 ”是多余的。