Ansible lineinfile - modify a line

对着背影说爱祢 提交于 2019-11-30 17:11:42

问题


I'm new to Ansible and trying to modify a line in /etc/default/grub to enable auditing.

I need to add audit=1 within the quotes somewhere on a line that looks like:

GRUB_CMDLINE_LINUX="crashkernel=auto rd.lvm.lv=centos/root rd.lvm.lv=centos/swap biosdevname=0 net.ifnames=0 rhgb quiet net.ifnames=0"

So far I've managed to delete the line and am only left with

net.ifnames=0, audit=1

when I use something like

lineinfile:
  state: present
  dest: /etc/default/grub
  backrefs: yes
  regexp: "net.ifnames=0"
  line: "\1 audit=1"

Can this be done?


回答1:


You may try this:

- lineinfile:
    state: present
    dest: /etc/default/grub
    backrefs: yes
    regexp: '^(GRUB_CMDLINE_LINUX=(?!.*audit)\"[^\"]+)(\".*)'
    line: '\1 audit=1\2'

This will add audit=1 just before closing double quote.
And it tries to be idempotent: doesn't match lines that already have audit word after GRUB_CMD...

I'd recommend to use sites like regex101 to test your regular expressions first (there's also a substitution mode there).
When you satisfied with the result, proceed with ansible task.



来源:https://stackoverflow.com/questions/39795873/ansible-lineinfile-modify-a-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!