仅当找到正则表达式时才追加到行

问题描述 投票:0回答:1

我有以下 Ansible 代码:

---
- name: skip fail2ban in iptables checkmk plugin
  hosts: localhost
  gather_facts: no
  tasks:
    - name: modify plugin
      ansible.builtin.lineinfile:
        path: /usr/lib/check_mk_agent/plugins/mk_iptables
        backrefs: True
        regexp: '^(iptables-save.*)'
        line: '\1 | grep -v "f2b"'

我想要的是将

 | grep -v "f2b"
附加到 bash 脚本中以
iptables-save
开头的行。这很好用。但是,我想这样做,如果
grep
功能已经添加,就不要再添加它。所以我尝试了某种
^(iptables-save.*)(?[grep])
,但我没有运气,可能是因为我误解了 1)如何正确排除正则表达式中的模式和 2)如果没有找到匹配项,
lineinfile
似乎仍会附加到 EOF .

我该如何解决这个问题?

regex ansible
1个回答
0
投票

对于测试文件

mk_iptables
,内容为

iptables-save foo bar

一个最小的示例手册

---
- hosts: localhost
  become: False
  gather_facts: False

  tasks:

    - name: modify plugin
      ansible.builtin.lineinfile:
        path: mk_iptables
        backrefs: True
        regexp: '^(iptables-save.*)(?<!"f2b")$'
        line: '\1 | grep -v "f2b"'
      diff: True

将产生

的输出
TASK [modify plugin] *****************
--- before: mk_iptables (content)
+++ after: mk_iptables (content)
@@ -1 +1 @@
-iptables-save foo bar
+iptables-save foo bar | grep -v "f2b"

第一次运行和第二次运行

TASK [modify plugin] *****************
ok: [localhost]

以及测试文件内容

cat mk_iptables
iptables-save foo bar | grep -v "f2b"

致谢

© www.soinside.com 2019 - 2024. All rights reserved.