【问题标题】:Ansible lineinfile RegexAnsible lineinfile 正则表达式
【发布时间】:2020-03-13 18:13:02
【问题描述】:

我有这段文字

[john]
age=20
group=wheel
[doe]
age=30
group=wheel
[stack]
age=undefined
group=wheel
color=white
[overflow]
age=undefined

我想用第一个正则表达式捕获:

age=20

和 group=wheel 的 [stack] 与第二个

【问题讨论】:

  • /\[john\].*?(age=\d+).*\[stack\].*?(group=[^\r\n]+)/gs 会给你$1 和$2 你所寻找的
  • 感谢您的回复,但是使用 ansible 我不能选择 $1 和 $2,它需要完全匹配,因此我需要 2 个完全匹配正则表达式的不同正则表达式。
  • Ansible 是否支持\K?
  • Ansible 使用 python 正则表达式 (docs.python.org/2/library/re.html)。我认为 python 没有 \K 但我不确定。
  • Python 确实不支持\K。你运气不好。您不能使用捕获组,不支持\K,也不支持使用可变长度后视的遥远的第三个选项。没有办法干净地检索您想要的结果。实际上,age=20 是可行的,但group=wheel 不是。

标签: regex ansible


【解决方案1】:

您正在尝试将正则表达式用于定义明确的文本文件格式; ini lookup 是你真正追求的:

# assuming the ini file is /tmp/foo.ini
tasks:
- set_fact:
    john_age: '{{ lookup("ini", "age section=john file=/tmp/foo.ini") }}'
    stack_group: '{{ lookup("ini", "group section=stack file=/tmp/foo.ini") }}'

然后,如果您的内容实际上不在文件中,则查找似乎仅适用于 files,因此您需要暂时将其写入文件:

tasks:
- copy:
    dest: /tmp/foo.ini
    content: '{{ the_ini_from_your_question_goes_here }}'
- set_fact:
    john_age: '{{ lookup("ini", "age section=john file=/tmp/foo.ini") }}'
    stack_group: '{{ lookup("ini", "group section=stack file=/tmp/foo.ini") }}'
- file:
    path: /tmp/foo.ini
    state: absent

【讨论】:

  • 最后我使用 ini_file (docs.ansible.com/ansible/latest/modules/ini_file_module.html) 解决了它让我完全不用担心正则表达式
  • 哦,抱歉,我以为您是在尝试提取信息,而不是对其进行变异。但无论哪种方式,我很高兴你使用了一个为处理 ini 文件而不是正则表达式而设计的模块:)
猜你喜欢
  • 2016-01-10
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
相关资源
最近更新 更多