# add new swap file if it does not already exist.
# Set `swap_add_mb` in config for swap size in MByte
#     swap_add_mb: 1024
# Based on https://gist.github.com/manuelmeurer/a2c0a8c24a0bb5092250
#
- name: set swap_file variable
  set_fact:
    swap_file: /var/swap

- name: check if swap file exists
  stat:
    path: "{{ swap_file }}"
  register: swap_file_check

- name: create swap file
  become: yes
  command: dd if=/dev/zero of="{{ swap_file }}" bs=1M count="{{ swap_add_mb }}"
  when: not swap_file_check.stat.exists

- name: set permissions on swap file
  become: yes
  file:
    path: "{{ swap_file }}"
    mode: 0600

- name: format swap file
  become: yes
  command: mkswap {{ swap_file }}
  when: not swap_file_check.stat.exists

- name: add to fstab
  become: yes
  lineinfile:
    dest: /etc/fstab
    regexp: "{{ swap_file }}"
    line: "{{ swap_file }} none swap sw 0 0"

- name: turn on swap
  become: yes
  command: swapon -a

- name: set swapiness
  become: yes
  sysctl:
    name: vm.swappiness
    value: "1"