0

Just getting my head around Ansible. Just trying to see what I am doing wrong or what is a better way to reach my goal.

Task :

My goal here is to update a file /proc/sys/vm/overcommit_memory. I want to put the value 0 into it. I also want the value it was before I changed it to be logged and displayed to me in output in case I need to rollback.

The below works fine but wanted to see if there are better ways to do it.

---
- hosts: "{{ target }}"
  gather_facts: yes
  become: yes

  tasks:

  - name: "update overcommit value on {{ target }} ..."
    shell: |
      echo "the value was "
      cat /proc/sys/vm/overcommit_memory
      echo 0 > /proc/sys/vm/overcommit_memory
      echo "the value now is  "
      cat /proc/sys/vm/overcommit_memory
    register: rc
    become: true
    become_user: root

  - debug:
      var: rc.stdout_lines

Thanks in advance

U880D
  • 8,601
  • 6
  • 24
  • 40

1 Answers1

1

Regarding your example it is recommend to use an Ansible module, sysctl.

---
- hosts: localhost
  become: true
  gather_facts: true

  vars:

    OVERCOMMIT_MEMORY: 0

  tasks:

  - name: 
    sysctl:
      name: vm.overcommit_memory
      value: "{{ OVERCOMMIT_MEMORY }}"
      state: present

Since Ansible is a Configuration Management it makes sure that the above task is idempotent and the value is available and set after. An "reporting" could than just be like


- name: Show value
  debug:
    msg: "'vm.overcommit_memory' values is {{ OVERCOMMIT_MEMORY }}"

Because of

Ansible lets you define when a particular task has “changed” a remote node using the changed_when conditional. This lets you determine, based on return codes or output, whether a change should be reported in Ansible statistics and whether a handler should be triggered or not.

you will get already the information if the key was there and the value not 0 if.

I also want the value it was before I changed it to be logged and displayed to me in output in case I need to rollback.

For a simple reporting of the current value set you could use a reporting task like

- name: Gather Facts OVERCOMMIT_MEMORY
  shell: "cat /proc/sys/vm/overcommit_memory"
  register: overcommit_memory
  changed_when: false
  failed_when: overcommit_memory.rc != 0 and overcommit_memory.rc != 1

- name: Show vaule
  debug:
    msg: "'vm.overcommit_memory' values was {{ overcommit_memory.stdout }}"

You may need to adjust Defining failure to catch cases if the key and therefore the file does not exists or if access rights are missing.

Further Documentation

Since it might be that Ansible facts are already contain the value

U880D
  • 8,601
  • 6
  • 24
  • 40