首页 > 解决方案 > 如何通过ansible playbook检查线路是否存在

问题描述

我有文件名测试

cat test
[tag1]

我想在测试中的 [tag1] 之后添加行我找到了这个解决方案

- ini_file:
    path: test
    section: "{{ item.section }}"
    option: "{{ item.option }}"
    allow_no_value: yes
  loop:
    - section: 'tag1'
      option: '# This is line 1'
    - section: 'tag1'
      option: '# This is line 2'

但是,如果该行存在,我什么也不想做,如果不存在,则添加它们。我应该怎么办?

标签: ubuntuansiblecentos

解决方案


Cat 文件并注册输出。如果文件中不存在“字符串”,则执行任务。

- shell: cat test
  register: check
  changed_when: false

- ini_file:
    path: test
    section: "{{ item.section }}"
    option: "{{ item.option }}"
    allow_no_value: yes
  when: '# This is line 1' not in check.stdout
  loop:
    - section: 'tag1'
      option: '# This is line 1'
    - section: 'tag1'
      option: '# This is line 2'

推荐阅读