如何用Ansible Replace模块替换配置账号密码并排除指定条目?
问题描述
现有如下INI格式配置文件:
something.ok.user.username=abc something.ok.user.password=def another_value.log_location=/somewhere something.ok.whoop.user.username=wh something.ok.whoop.user.password=asdf something.ok.user.username=username1 something.ok.user.password=passwoordddd01 something.ok.w.user.username=mygreatuser something.ok.w.user.password=whocares something.ok.user.username=yeah something.ok.user.password=apassword something.ok.busuiness.user.username=someuser something.ok.busuiness.user.password=example
当前使用以下Ansible任务可将所有username值替换为someone,所有password值替换为somepass:
- name: replace all occurrences of username and password in config file replace: path: /tmp/file.conf regexp: '^(something\.ok.*user\.{{ item.regexp }}=).*' replace: '\g<1>{{ item.replace }}' loop: - regexp: username replace: someone - regexp: password replace: somepass
需求:跳过包含something.ok.whoop和something.ok.busuiness的条目(共4行),不对这些条目的用户名/密码进行替换。已定义变量:
vars: skip_list: - whoop - busuiness
解决方案
方法一:改进replace模块的正则表达式
可以通过正则否定前瞻实现跳过指定条目,结合skip_list动态生成匹配规则,无需修改原有模块逻辑。
修改后的Ansible任务如下:
vars: skip_list: - whoop - busuiness # 将skip_list转为正则匹配的否定前瞻模式 skip_pattern: "{{ '(' + skip_list|join('|') + ')' }}" - name: replace username/password except skipped entries replace: path: /tmp/file.conf regexp: '^(something\.ok(?!.*{{ skip_pattern }}).*user\.{{ item.regexp }}=).*' replace: '\g<1>{{ item.replace }}' loop: - regexp: username replace: someone - regexp: password replace: somepass
正则说明
^(something\.ok(?!.*{{ skip_pattern }}).*user\.(username|password)=).* 中:
(?!.*{{ skip_pattern }})是否定前瞻断言,表示匹配的行中不能包含skip_list里的任意关键词(whoop或busuiness)- 其余部分保留原有匹配逻辑,确保只匹配
something.ok开头、包含user.username或user.password的行
方法二:使用lineinfile模块(更直观)
如果对正则语法不太熟悉,lineinfile模块可以更精准地控制每一行的处理,通过regexp直接排除需要跳过的前缀:
vars: skip_list: - whoop - busuiness - name: replace username except skipped entries lineinfile: path: /tmp/file.conf regexp: '^(something\.ok(?!.*(whoop|busuiness)).*user\.username=).*' line: '\g<1>someone' - name: replace password except skipped entries lineinfile: path: /tmp/file.conf regexp: '^(something\.ok(?!.*(whoop|busuiness)).*user\.password=).*' line: '\g<1>somepass'
这种方式拆分了用户名和密码的替换逻辑,更易于理解和调试。
内容的提问来源于stack exchange,提问作者Kevin C
相关产品推荐
相关产品推荐

