Ansible lineinfile 重复行 [英] Ansible lineinfile duplicates line

查看:65
本文介绍了Ansible lineinfile 重复行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple file at /etc/foo.txt. The file contains the following:

#bar

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

I have the following ansible playbook task to uncomment the line above:

- name: test lineinfile
  lineinfile: backup=yes state=present dest=/etc/foo.txt
              regexp='^#bar'
              line='bar'

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

When I first run ansible-playbook, the line gets uncommented and the /etc/foo.txt now contains the following:

bar

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

However, if I run ansible-playbook again, I get the following:

bar
bar

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

If I run it yet again, then the /etc/foo.txt file will look like this:

bar
bar
bar

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

How to avoid this duplications of lines? I just want to uncomment the '#bar' and be done with it.

推荐答案

问题是任务的正则表达式只匹配注释掉的行 #bar.为了具有幂等性,lineinfile 任务需要匹配该行的注释状态.这样它会取消注释 #bar 但会通过 bar 不变.

The problem is the task's regex only matches the commented out line, #bar. To be idempotent, the lineinfile task needs to match both the commented and uncommented state of the line. This way it will uncomment #bar but will pass bar unchanged.

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

This task should do what you want:

- name: test lineinfile
  lineinfile: 
    backup=yes
    state=present
    dest=/etc/foo.txt
    regexp='^#?bar'
    line='bar'

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

Note the only change was adding a "?" to the regex.

这篇关于Ansible lineinfile 重复行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆