- name: Check swapfile stat: path: /swapfile register: swapfile - name: Size swapfile when: not swapfile.stat.exists or swapfile.stat.size != swapfile_size_gb | int * 1024 * 1024 * 1024 block: - name: Disable swapfile command: swapoff /swapfile when: swapfile.stat.exists changed_when: true - name: Remove old swapfile file: path: /swapfile state: absent - name: Allocate swapfile command: fallocate -l {{ swapfile_size_gb }}G /swapfile changed_when: true - name: Format swapfile command: mkswap /swapfile changed_when: true - name: Restrict swapfile permissions file: path: /swapfile owner: root group: root mode: "0600" - name: Persist swapfile in fstab ansible.posix.mount: src: /swapfile path: none fstype: swap opts: sw state: present - name: Check active swap command: swapon --show=NAME --noheadings register: swapfile_active changed_when: false - name: Enable swapfile command: swapon /swapfile when: "'/swapfile' not in swapfile_active.stdout_lines"