--- - name: Check for an existing swapfile ansible.builtin.stat: path: "{{ swap_file }}" register: swap_stat - name: Create swapfile ansible.builtin.command: cmd: "dd if=/dev/zero of={{ swap_file }} bs=1M count={{ swap_size_mb }} status=none" when: not swap_stat.stat.exists or (swap_stat.stat.size != swap_size_mb * 1024 * 1024) register: swap_created - name: Restrict swapfile permissions ansible.builtin.file: path: "{{ swap_file }}" mode: '0600' owner: root group: root when: not ansible_check_mode or swap_stat.stat.exists - name: Format swapfile ansible.builtin.command: cmd: "mkswap {{ swap_file }}" when: swap_created is changed - name: Add swapfile to /etc/fstab ansible.builtin.lineinfile: path: /etc/fstab regexp: "^{{ swap_file }}\\s" line: "{{ swap_file }} none swap sw 0 0" - name: Enable swap ansible.builtin.command: cmd: "swapon {{ swap_file }}" register: swapon_result changed_when: swapon_result.rc == 0 failed_when: swapon_result.rc != 0 and 'busy' not in swapon_result.stderr - name: Set swappiness ansible.builtin.copy: dest: /etc/sysctl.d/90-swap.conf content: "vm.swappiness = {{ swap_swappiness }}\n" mode: '0644' register: swappiness_conf - name: Apply swappiness ansible.builtin.command: cmd: sysctl -p /etc/sysctl.d/90-swap.conf when: swappiness_conf is changed