Ansible lineinfile is not changing file as expect

Viewed 98

THi, new to this. . . . Testing out a Ansible play to update the swappiness setting on a test box.

---
- hosts: "{{ target }}"
  become: yes
  tasks:
  - name: swapness
    lineinfile:
      path: /etc/sysctl.conf
      state: present
      regexp: vm.swappiness=*
      line: vm.swappiness=6

Currently, it is set to vm.swappiness=4 but running the above does not change that.

the way I read the logic is...

look for a line with "vm.swappiness=" and replace it with "vm.swappiness=6"

2 Answers

I would do in this way:

---
- name: Playbook who modify swapiness.
  hosts: "{{ target }}"
  become: yes

  tasks:

    # Set vm.swappiness to 6 in /etc/sysctl.conf
    - name: Set swapiness.
      sysctl:
        name: vm.swappiness
        value: '6'
        state: present
        sysctl_set: yes
        reload: yes

The reason for that is that If exists any module for it, you should be doing using that module specific instead a generic one.

Ansible has a sysctl module, so it's better to use it for this.

Note: Please, review the code and set 2 white spaces between them if not already.

Given the file

shell> cat sysctl.conf 
vm.swappiness=4

The task below works as expected

  - lineinfile:
      path: sysctl.conf
      regexp: vm.swappiness=*
      line: vm.swappiness=6

Running the playbook with the options --check --diff gives abridged

TASK [lineinfile] *****************************************************
--- before: sysctl.conf (content)
+++ after: sysctl.conf (content)
@@ -1 +1 @@
-vm.swappiness=4
+vm.swappiness=6

Notes

  • The regexp vm.swappiness=* is probably not what you really want. This regexp matches the string vm.swappiness followed by 0 or mode =. For example, below are strings that match this regexp
vm.swappiness
vm.swappiness=
vm.swappiness==========

Instead, you want a regexp that matches the string vm.swappiness= followed by 0 or more characters. For example vm.swappiness=.*

Related