U
U
Username2021-07-31 21:16:53
Regular Expressions
Username, 2021-07-31 21:16:53

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"


You need to replace name=webserver with name=dbserver, if there is no line, then add it.

My attempts:

---
- 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

3 answer(s)
M
MaxKozlov, 2021-08-01
@wizkey

Here is such a funny regex

ServerConfig="(.*)\b(name=[^\s]+)\b(.*)"|"(.*)\b(name=[^\s]+)?"

and replacement, respectively,
\1name=xxx\3\4
True, in this case, name=xxx will be inserted at the beginning, and not at the end of the line, if it was not there before
https://regex101.com/r/MILkYr/1/
ps and although it is possible to the end with such a replacement
\1\4name=xxx\3

A
Alexander Karabanov, 2021-07-31
@karabanov

I would make a config template and form the final config from it in a controlled manner.

S
Sanes, 2021-08-01
@Sanes

What is the problem? Can't write a regular expression?
Options:

  1. Regular expression with search and replace
  2. blockinfile module
  3. Sample

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question