---
# Create swap
- name: Turn off swap
  command: "swapoff --all"
  become: yes
- name: Remove old swap file
  file:
    state: absent
    path: "{{ swap_file_path }}"
  become: yes
- name: Create swap file
  command: truncate -s 0 "{{ swap_file_path }}"
            creates="{{ swap_file_path }}"
  become: yes
  when: swap_file_size_mb != 0
- name: Set swap compression
  command: chattr +C "{{ swap_file_path }}"
  become: yes
  when: swap_file_size_mb != 0
- name: Allocate swap space
  command: fallocate -l "{{ swap_file_size_mb }}M" "{{ swap_file_path }}"
  become: yes
  when: swap_file_size_mb != 0
- name: Change swap file permissions
  file: path="{{ swap_file_path }}"
        owner=root
        group=root
        mode=0600
  become: yes
  when: swap_file_size_mb != 0
- name: "Check swap file type"
  command: file {{ swap_file_path }}
  register: swapfile
  become: yes
  when: swap_file_size_mb != 0
- name: Make swap file
  command: "mkswap {{ swap_file_path }}"
  become: yes
  when: swap_file_size_mb != 0
- name: Write swap entry in fstab
  mount: name=none
        src={{ swap_file_path }}
        fstype=swap
        opts=sw
        passno=0
        dump=0
        state=present
  become: yes
  when: swap_file_size_mb != 0
- name: Mount swap
  command: "swapon {{ swap_file_path }}"
  become: yes
  when: swap_file_size_mb != 0
- name: Set swappiness
  command: sysctl -w vm.swappiness=1
  become: yes
  when: swap_file_size_mb != 0
- name: Make swappiness permanent
  copy:
    dest: "/etc/sysctl.d/99-swappiness.conf"
    content: |
      vm.swappiness=1
  become: yes
  when: swap_file_size_mb != 0
