Yaml Ansible lineinfile insertafter在文件末尾注入行

Yaml Ansible lineinfile insertafter在文件末尾注入行,yaml,ansible,ansible-playbook,Yaml,Ansible,Ansible Playbook,我使用的lineinfle如下所示: lineinfile dest=./hosts_exp insertafter='\[hosts1\]' line="xxxxxxxxx" state=present [local] localhost [hosts1] [hosts2] [hosts3] 我的hosts\u exp如下所示: lineinfile dest=./hosts_exp insertafter='\[hosts1\]' line="xxxxxxxxx" state=pr

我使用的lineinfle如下所示:

lineinfile dest=./hosts_exp insertafter='\[hosts1\]' line="xxxxxxxxx" state=present
[local]
localhost

[hosts1]

[hosts2]

[hosts3]
我的
hosts\u exp
如下所示:

lineinfile dest=./hosts_exp insertafter='\[hosts1\]' line="xxxxxxxxx" state=present
[local]
localhost

[hosts1]

[hosts2]

[hosts3]

lineinfle在[hosts3]之后插入文本,而不是在[hosts1]之后插入文本。

它看起来是多余的,但您也需要指定正则表达式:

lineinfile:
  dest: ./hosts_exp
  insertafter: '\[hosts1\]'
  regexp: '\[hosts1\]'
  line: "xxxxxxxxx"
  state=present
为什么??
regexp
显示“查找此行”。
insertafter
表示“在此处插入行”

我测试了这个。从上一行开始,我的提交中有一些小改动,请根据需要使用。

示例:

- name: "blah"
  lineinfile:
    dest: "/test.sh"
    insertafter: 'test text'
    line: "text add"
    state: present
使用:

使用backrefs:是

lineinfile:
  backrefs: yes
  dest: ./hosts_exp
  insertafter: '\[hosts1\]'
  regexp: '\[hosts1\]'
  line: "xxxxxxxxx"
  state=present

该标志稍微改变了模块的操作;insertbefore和insertafter将被忽略,如果regexp与文件中的任何地方都不匹配,则文件将保持不变。如果regexp不匹配,最后一个匹配行将被扩展行参数替换。

它在没有regex的情况下对我有效,问题是它没有一次又一次地使用相同的文本进行插入,我需要提供一个新的文本,并与我的要求保持一致。没有必要使用正则表达式。为了澄清这一点,只有在正则表达式和insertafter都匹配的情况下不希望添加行时,才需要使用正则表达式。因此,这是必要的,如果它只适用于第一次,这是最常见的情况。您使用的是什么版本的ansible?我正在使用您的测试获得预期的结果,xxxxxxx添加在[hosts01]之后。@RamondelaFuente现在请在您的hosts\u exp文件中已有行“xxxxxxxx”后重试。我的意思是尝试添加另一行。Ansible的lineinfile模块不会添加同一行两次-任务按我的预期标记为“ok”。