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

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

问题描述

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

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

#bar

我有以下有趣的剧本任务来取消上面的注释:

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天全站免登陆