Helgi
Helgi

Reputation: 338

Ansible lineinfile doesn't recognize regular expression

File to be edited

#CentOS-Base.repo
#
[base]
name=CentOS-$releasever - Base

[updates]
name=CentOS-$releasever - Updates

[contrib]
name=CentOS-$releasever - Contrib

Ansible task

- name: PostgreSQL | Yum | exclude old version
  remote_user: root
  sudo: no
  lineinfile: dest=/etc/yum.repos.d/CentOS-Base.repo
              line='exclude=postgresql*'
              insertafter={{ item }}
  with_items:
    - ^\[base\]
    - ^\[updates\]

Results:

The line is added only once to the file AND it's added at the EOF instead of at the next line after [base] and [updates].

I am fairly certain that the regex is valid(checked on https://pythex.org/ ).

Upvotes: 0

Views: 2816

Answers (2)

Mxx
Mxx

Reputation: 9344

Instead of lineinfile module, consider using ini_file module. That way you don't have bust your head with regex expressions.

Manage (add, remove, change) individual settings in an INI-style file without having to manage the file as a whole with, say, template or assemble. Adds missing sections if they don’t exist.

Example:

# Ensure "fav=lemonade is in section "[drinks]" in specified file
- ini_file: dest=/etc/conf section=drinks option=fav value=lemonade mode=0600 backup=yes

- ini_file: dest=/etc/anotherconf
            section=drinks
            option=temperature
            value=cold
            backup=yes

Upvotes: 4

300D7309EF17
300D7309EF17

Reputation: 24633

Using lineinfile multiple times for the same file is a code smell in Ansible. Instead, use copy or template.

However, here's one way you can do it. Note it's more lines than a file + copy command would be.

- name: PostgreSQL | Yum | exclude old version
  lineinfile: dest=test.repo
              line="\1\nexclude=postgresql*"
              insertafter="\[{{ item }}\]"
              regexp="(\[{{ item }}\])"
              backrefs=true
  with_items:
    - base
    - updates

Upvotes: 0

Related Questions