Answer the question
In order to leave comments, you need to log in
How to replace or paste text into a file in Ansible?
For example, there is some kind of config, it has a line with parameters. The string can contain different parameters, the entire string cannot be replaced.
How can Ansible find the desired text, replace if it does not match and insert if it is missing in a certain place after a certain line?
file:
ServerConfig=" ip=10.0.0.0 dns=10.0.0.1 name=webserver"
---
- hosts: webserver
vars:
config:
- { param: name=, value: dbserver }
tasks:
- name: change param
become: yes
lineinfile:
backup: yes
backrefs: yes
path: /etc/file/config
regexp: '^ServerConfig=/"(?!.*\b{{ item.param }}{{ item.value }}\b).*)$'
line: '\1{{ item.param }}{{ item.value }}\2'
state: present
loop: "{{ config }}"
Answer the question
In order to leave comments, you need to log in
Here is such a funny regex
ServerConfig="(.*)\b(name=[^\s]+)\b(.*)"|"(.*)\b(name=[^\s]+)?"
I would make a config template and form the final config from it in a controlled manner.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question