简体   繁体   English

Ansible 剧本中的 Python 正则表达式问题

[英]Python regexp problem in Ansible playbook

I have a string in Zabbix agent configuration like我在 Zabbix 代理配置中有一个字符串,例如

HostMetadata=Linux

I want change it with variable "nginx" to:我想用变量“nginx”将其更改为:

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"我尝试了“^HostMetadata=((?.nginx),)*$”,但它中断了下一步,结果将是“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)

You should only capture the part you need to keep, the rest should be just matched.您应该只捕获您需要保留的部分,rest 应该只是匹配。

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 (HostMetadata=Linux) - 捕获组 #1(用替换字符串中的\1引用):文字字符串
  • .* - the rest of the string to the end, any 0 or more chars other than line break chars, as many as possible. .* - 字符串的 rest 到末尾,除换行符之外的任何 0 个或多个字符,尽可能多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM