Ansible lineinfile复制行

编程入门 行业动态 更新时间:2024-10-21 18:39:54
本文介绍了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复制行

本文发布于:2023-11-01 12:38:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1549356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Ansible   lineinfile

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!