Ansible:在行尾插入字符串,但前提是字符串不存在 OR/AND 如果存在则更改值

Ansible: insert string at the end of the line but only if string is not present OR/AND change value if present

我在以下情况下苦苦挣扎:

/etc/default/grub文件中,有GRUB_CMDLINE_LINUX_DEFAULT节, 我需要在行尾插入 audit=1 if value is not there already (注意有引号字符在行尾)。如果存在 audit=0,请将其更改为 audit=1

lineinfile ansible 模块不起作用,尤其是在最后一个引号 (") 之前插入。

原文/etc/default/grub:

GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi="

可选/etc/default/grub:

GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=0" # change audit=0 to audit=1
#OR:
#GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=1" # audit=1 is already here, so no action needed

想要/etc/default/grub:

GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=1"

我创建了一个文本为 audit=0 的文件,并尝试将其替换为 audit=1

我的文件是: grub 文件:

GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=0"

我的剧本:

---
  - name: read grub file
    lineinfile:
      dest: /home/myhome/grubfile.txt
      regexp: '^(.*)audit=0(.*)$'
      line: 'audit=1'
      backup: yes
      backrefs: yes

基本上我们使用 regexp 将 audit=1 作为 regexp 并使用 backrefs 存储字符串的其余部分 结果文件是:

GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="rootfstype=xfs quiet splash acpi_osi= audit=1"

编辑: 这段代码即使不存在也会添加它,如果 audit=0 存在,它将首先修改,然后检查 audit=1 是否存在,如果不存在,则将 audit=1 附加到 audit=1 的开头报价:

---
  - name:
    lineinfile:
      dest: /home/mypath/grubfile.txt
      regexp: '^(.*)audit=1(.*)$'
      state: absent
    check_mode: yes
    changed_when: false
    register: auditexist
  - name: if audit=0 write audit=1
    lineinfile:
      dest: /home/mypath/grubfile.txt
      regexp: '^(.*)audit=0(.*)$'
      line: 'audit=1'
      backup: yes
      backrefs: yes
    register: auditmodified
  - name: appen
    lineinfile:
     dest: /home/ivan/grubfile.txt
     regexp: '^(.*)GRUB_CMDLINE_LINUX_DEFAULT="(.*)$'
     line: 'GRUB_CMDLINE_LINUX_DEFAULT="audit=1  '
     backup: yes
     backrefs: yes
    when: not auditexist.found and not auditmodified.changed

结果:

GRUB_TIMEOUT=5
GRUB_DEFAULT=saved
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="audit=1 rootfstype=xfs quiet splash acpi_osi="