ansible 正则表达式不适用于数字
我的 ansible 剧本摘录
- name: replace variable
ansible.builtin.replace:
path: "{{ item }}"
regexp: '(?x)(--my_variable(\s|\t)*=(\s|\t)*")(.*?)((\")(\s\\\n)|(\"(\s|\t)))'
replace: "\\1{{ my_number }}\\5"
该变量的值为 222
我在 ansible 库中有一个变量 my_number
当 行替换:“\\1{{ my_number } 时, }\\5"
被执行 我收到一条错误消息 但是,如果我用字符串替换变量,我的捕获组是错误的,即 “my_number = ytiuytuytiu”
一切按预期工作,而“my_number = 3333”
失败。
我的问题
my_number
是数字时为什么替换失败?
为什么 my_number
是字符串时替换成功?
如何解决这个问题?
PS
正则表达式是为了匹配和替换这种类型的字符串而设计的,
--my_variable="333" \
错误看起来像这样
raise s.error(\"invalid group reference %d\" % index, pos)\r\nsre_constants.error: invalid group reference 18 at position 1\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1
an excerpt from my ansible playbook
- name: replace variable
ansible.builtin.replace:
path: "{{ item }}"
regexp: '(?x)(--my_variable(\s|\t)*=(\s|\t)*")(.*?)((\")(\s\\\n)|(\"(\s|\t)))'
replace: "\\1{{ my_number }}\\5"
I have a variable in ansible vault my_number
this variable has a value 222
when the line replace: "\\1{{ my_number }}\\5"
gets executed I get an error saying
that my capture group is wrong, however, if I replace variable with a string literal, i.e"my_number = ytiuytuytiu"
everything works as expected where "my_number = 3333"
fails.
My questions
Why does it fail to replace when my_number
is a number?
why does it succeed to replace when my_number
is a String?
How to solve this issue?
P.S
Regex is crafted to match and replace the strings of this type
--my_variable="333" \
The error looks like this
raise s.error(\"invalid group reference %d\" % index, pos)\r\nsre_constants.error: invalid group reference 18 at position 1\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当 ansible 做一些奇怪的事情时,解决方案几乎总是增加详细程度
ansible-playbook -vv
这将向您显示实际的模块参数,并希望引导您找到解决方案:通过用数字替换使用\1
语法,它会变成\1333
,无论正则表达式引擎如何将其切碎,都是非法的反向引用python re.sub 手册 说
\g<1> ;
是明确的样式:When ansible is doing something weird, the solution is almost always to increase the verbosity
ansible-playbook -vv
which would have shown you the actual module arguments, and hopefully led you to the solution: by substituting in numbers with that\1
syntax, it becomes\1333
which no matter how the regex engine chopped it up, is an illegal backreferenceThe python re.sub manual says that
\g<1>
is the unambiguous style: