Python regexp problem in Ansible playbook

Viewed 80

I have a string in Zabbix agent configuration like

HostMetadata=Linux

I want change it with variable "nginx" to:

HostMetadata=Linux nginx

This changes must be idempotent. But when I am using code twice, line changed to

HostMetadata=Linux nginx nginx

My code:

      - name: regexp
        lineinfile:
          path: /etc/zabbix/zabbix_agentd.conf
          regexp: '^(HostMetadata=Linux.*)$'
          line:  '\1 nginx'
          backrefs: yes
        tags: regexp

I tried "^HostMetadata=((?!nginx).)*$", but it breaks next step, and result will be "x nginx"

I want create reusable code and add new parameters. For example:

VAR=nginx
"HostMetadata=Linux" -> "HostMetadata=Linux nginx"

VAR=apache
"HostMetadata=Linux nginx" ->  "HostMetadata=Linux nginx apache"

VAR=nginx
"HostMetadata=Linux nginx apache" -> "HostMetadata=Linux nginx apache" (nothing changed)
1 Answers

You should only capture the part you need to keep, the rest should be just matched.

You may use

regexp: '^(HostMetadata=Linux).*'

See the regex demo.

Details

  • ^ - start of string
  • (HostMetadata=Linux) - capturing group #1 (referred to with \1 from the replacement string): the literal string
  • .* - the rest of the string to the end, any 0 or more chars other than line break chars, as many as possible.
Related