[英]using regexp in ansible to replace word
I am newbie to ansible actually.Can anyone please help me change the ip address in a file using regexp with my original system ip. 我实际上是ansible的新手。有人可以帮我使用带有原始系统ip的regexp更改文件中的ip地址。 Let say I wanted to replace "Djgroups.bind_address=<*/WHATEVER/BLANK>" to "Djgroups.bind_address=10.0.0.45"
假设我想将“ Djgroups.bind_address = <* / WHATEVER / BLANK>”替换为“ Djgroups.bind_address = 10.0.0.45”
This would be for a tomcat instance. 这将是一个tomcat实例。 The Line where the replacement is required:
需要更换的生产线:
JAVA_OPTS="-Xms6144m -Xmx6144m -Djava.awt.headless=true -Djava.net.preferIPv4Stack=true -Djgroups.bind_address="
I Wrote ansible as below: 我写了如下:
- name: Verifying Instance IP Address
shell: grep Djgroups.bind_address /apache-tomcat-8.5.15_1/bin/catalina.sh|grep -v ^#|tr -s '=' '"'|cut -d '"' -f5
register: tomcat_instance_ip
- debug: msg='Tomcat instance has {{ tomcat_instance_ip.stdout }} set.'
- name: Updating Tomcat Instance with valid local IP address
replace:
dest: /apache-tomcat-8.5.15_1/bin/catalina.sh
regexp: '^(Djgroups.bind_address(?!.*\b{{ tomcat_instance_ip.stdout }}\b).*)$'
replace: '\1 {{ ip_address }}'
when: tomcat_instance_ip.stdout != ip_address
Thanks, Sam 谢谢山姆
I see at least 4 issues with the regexp: 我看到正则表达式至少有四个问题:
.
.
is not escaped, so it is interpreted as a special character. ^
at the beginning. ^
放在开头。 Seems like you are trying to find something in the middle of a string, not at the beginning. Djgroups.bind_address
part of the string, while i believe you meant to match whatever comes afterwards instead. Djgroups.bind_address
部分,而我相信您的意思是匹配之后出现的所有内容。 try: Djgroups\\.bind_address=(?!.*?{{ tomcat_instance_ip.stdout }}.*?)(.*)$
尝试:
Djgroups\\.bind_address=(?!.*?{{ tomcat_instance_ip.stdout }}.*?)(.*)$
And please test your regex first. 并且请先测试您的正则表达式。 https://regex101.com/ Make sure it actually matches your input like you imagined.
https://regex101.com/确保它确实与您想像的输入相匹配。
Remove the shell
task, this is not needed. 删除
shell
任务,这不是必需的。
Try this : 尝试这个 :
- name: Updating Tomcat Instance with valid local IP address
replace:
path: /apache-tomcat-8.5.15_1/bin/catalina.sh
regexp: 'JAVA_OPTS="(.* )?-Djgroups.bind_address=[^ "]*(.*)"'
replace: 'JAVA_OPTS="\1-Djgroups.bind_address={{ ip_address }}\2"'
The when
is not needed either, since replace
module is idempotent. 由于
replace
模块是幂等的when
因此也不需要when
。
Edit : some explanations about the regular expression used in this example 编辑:有关此示例中使用的正则表达式的一些说明
'JAVA_OPTS="(.* )?-Djgroups.bind_address=[^ "]*(.*)"'
^___^ ^__^
^_________^ (1) ^______________________^ (2)
(3) (4)
^__^
(5)
\\1
and \\2
. \\1
和\\2
引用它们来替换它们。 Regular expressions are somewhat intimidating at first, with this weird syntax. 首先,使用这种怪异的语法, 正则表达式有些令人生畏。 This not as complicated as it seems.
这并不像看起来那样复杂。 You can find a lot of tutorials to help you understand it.
您可以找到很多教程来帮助您理解它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.