Home > Software engineering >  ansible - Modify line closest to [string] in file
ansible - Modify line closest to [string] in file

Time:08-11

Struggling to get a play working.If I have a file such as:

[host]:
  port: 8080
  name2
[city]
  port: 8080

How could I write an ansible module that modifies the first occurrence of port: 8080 to port: 80 from the [host] string?

I have tried to insert after but so far can only get it to add a second port: 80 above the port: 8080. Any thoughts on how to search for a string then replace the first occurence under that string using ansible? Thanks!

CodePudding user response:

Match the entire file so there's only one replacement:

- replace:
    path: <your-file-path>
    regexp: '8080([\s\S]*)'
    replace: '80\1'

This works by matching 8080 but capturing (as group 1) the rest of the file that follows, thanks to [\s\S] matching every character (importantly, including newlines).

The replacement puts but 80 and the rest of the file via \1 - the back-reference to group 1.

See live demo of regex.

CodePudding user response:

Replace between two specified expressions Documentation

  - name: Replace between the expressions (requires Ansible >= 2.4)
    ansible.builtin.replace:
      path: file.yml
      after: 'host'
      before: 'city'
      regexp: '8080'
      replace: '80'
  • Related