--- # swapfile role — provisions a swap file of configurable size # # Variables (set per-host in host_vars): # swap_size_gb: size in gigabytes (default: 4) # swap_swappiness: vm.swappiness value (default: 10) - name: Check if swapfile exists with correct size ansible.builtin.stat: path: /swapfile register: swapfile_stat - name: Allocate swapfile (fallocate) ansible.builtin.command: cmd: "fallocate -l {{ (swap_size_gb | default(4)) | int }}G /swapfile" creates: /swapfile when: not swapfile_stat.stat.exists - name: Set swapfile permissions ansible.builtin.file: path: /swapfile owner: root group: root mode: '0600' - name: Format swapfile ansible.builtin.command: cmd: mkswap /swapfile when: not swapfile_stat.stat.exists - name: Enable swapfile ansible.builtin.command: cmd: swapon /swapfile when: not swapfile_stat.stat.exists ignore_errors: true # already active is not an error - name: Ensure swapfile in /etc/fstab ansible.builtin.lineinfile: path: /etc/fstab regexp: '^/swapfile' line: '/swapfile none swap sw 0 0' state: present - name: Set vm.swappiness at runtime ansible.posix.sysctl: name: vm.swappiness value: "{{ swap_swappiness | default(10) }}" state: present reload: true - name: Persist vm.swappiness across reboots ansible.builtin.copy: dest: /etc/sysctl.d/60-swappiness.conf owner: root group: root mode: '0644' content: | # Managed by Ansible (swapfile role) vm.swappiness = {{ swap_swappiness | default(10) }}