0

I want to insert a line with a user test999 before a construction site with a user test3 .I can't insert a line before another one, it is constantly inserted into the last one, for what reason can this happen?

---
- hosts: app_stage
  become: yes
  vars:
    user: test999
  tasks:
    - name: remove immutable
      file:
        path: /etc/sudoers
        attr: '-i'
    - name: change permission
      file:
        path: /etc/sudoers
        mode: 0660
    - name: Allow ‘user’ to have passwordless sudo
      lineinfile:
        dest: /etc/sudoers
        state: present
        regexp: '^test3 ALL=(ALL) NOPASSWD: ALL'
        insertbefore: '^test3 ALL=(ALL) NOPASSWD: ALL'
        line: '{{ user }} ALL=(ALL) NOPASSWD: ALL'
        validate: visudo -cf %s
    - name: change permissions back
      file:
        path: /etc/sudoers
        mode: 0440
        owner: root
        group: root
    - name: back immutable
      file:
        path: /etc/sudoers
        attr: '+i'
Iceforest
  • 309
  • 1
  • 11
  • To make things easier and if possible in your environment and infrastructure, you may have a look into the [`template`](https://stackoverflow.com/a/35468363/6771046) module. – U880D Oct 04 '22 at 18:44

1 Answers1

3

Check the lineinfile module documentation for insertbefore:

Used with state=present

If specified regular expression has no matches, the line will be inserted at the end of the file.

If regular expressions are passed to both regexp and insertbefore, insertbefore is only honored if no match for regexp is found.

HiroCereal
  • 550
  • 1
  • 11
  • of course i use state: present (sorry for my mistake), but i used only insertbefore and only regexp, but still the line was put down. is it possible to somehow debug this? as I understand it, the fact is that he does not find matches, but they are there – Iceforest Oct 05 '22 at 05:53
  • Try to come up with a [Minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) and edit your question. We cannot help without complete information – HiroCereal Oct 05 '22 at 10:32
  • @Iceforest, if I would have to bet on where your problem is, probably the regexp is not matching because you have more than one space or tabs in your sudoers file – HiroCereal Oct 05 '22 at 14:28