Search code examples
linuxansiblesystem-administrationsystem-configuration

Ansible: check for file text and if not there add it


This is what I have so far:

- hosts: test
  tasks:
    - name: check existence of line in the target file to replace if there
      command: grep fs.file-max /etc/sysctl.conf
      changed_when: false
      failed_when: false
      register: file_test
    - name: add config line to the file and reload
      lineinfile:
        path: /etc/sysctl.conf
        line: fs.file-max = 65000
      when: item.rc == 1
      with_items:
        - '{{ file_test.results }}'
      command: sysctl -a

However, it keeps failing with the following:

The error appears to be in '/root/playbooks/sysctl.yml': line 8, column 7, but may                                    
be elsewhere in the file depending on the exact syntax problem.                                                      
                                                                                                                      
The offending line appears to be:                                                                                    
                                                                                                                      
      register: file_test                                                                                             
    - name: add config line to the file and reload                                                                    
      ^ here                

I've tried fixing indent and changing the way how I am doing this but I get nothing.


Solution

  • Have a look at the sysctl module. To add/edit lines in the sysctl.conf file, you can use this instead of using multiple tasks and logic.

    Example:

    - hosts: test
    
      tasks:
      - name: add fs.file-max to sysctl.conf
        sysctl:
          name: 'fs.file-max'
          value: '65000'