我在/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复制行
发布评论