Ansible lineinfile重复行

zup*_*upo 37 ansible

我在/etc/foo.txt有一个简单的文件.该文件包含以下内容:

#bar
Run Code Online (Sandbox Code Playgroud)

我有以下ansible playbook任务取消注释上面的行:

- name: test lineinfile
  lineinfile: backup=yes state=present dest=/etc/foo.txt
              regexp='^#bar'
              line='bar'
Run Code Online (Sandbox Code Playgroud)

当我第一次运行ansible-playbook时,该行被取消注释,而/etc/foo.txt现在包含以下内容:

bar
Run Code Online (Sandbox Code Playgroud)

但是,如果我再次运行ansible-playbook,我会得到以下内容:

bar
bar
Run Code Online (Sandbox Code Playgroud)

如果我再次运行它,那么/etc/foo.txt文件将如下所示:

bar
bar
bar
Run Code Online (Sandbox Code Playgroud)

如何避免这种重复的行?我只是想取消注释'#bar'并完成它.

ana*_*nik 68

如果您不想更改正则表达式,则需要添加backrefs = yes.

- name: test lineinfile
  lineinfile: backup=yes state=present dest=/etc/foo.txt
              regexp='^#bar' backrefs=yes
              line='bar'
Run Code Online (Sandbox Code Playgroud)

这会改变lineinfile的行为:

 find
 if found
   replace line found
 else
   add line
Run Code Online (Sandbox Code Playgroud)

至:

 find
 if found
   replace line found
Run Code Online (Sandbox Code Playgroud)

换句话说,这使得操作是幂等的.


joe*_*ler 54

问题是任务的正则表达式只匹配注释掉的行,#bar.要成为幂等,lineinfile任务需要匹配行的注释和未注释状态.这样它将取消注释,#bar但将bar保持不变.

这个任务应该做你想要的:

- name: test lineinfile
  lineinfile: 
    backup=yes
    state=present
    dest=/etc/foo.txt
    regexp='^#?bar'
    line='bar'
Run Code Online (Sandbox Code Playgroud)

请注意,唯一的变化是添加"?" 到正则表达式.