swap: add a swapfile role, 2 GB on asxpio-ops

The ops server has 3.7 GB RAM and no swap. Forgejo, MinIO and the apps
fit with room to spare, but a spike (a big push, git gc, parallel
image pulls) would OOM-kill a service instead of paging out.

swappiness 10, so it only swaps under real pressure.

Assisted-by: Claude:opus-5
This commit is contained in:
Sergei Poljanski 2026-10-12 05:31:32 +04:00
commit 0af23425f9
3 changed files with 67 additions and 0 deletions

View file

@ -0,0 +1,6 @@
---
# Swapfile so a memory spike pages out instead of OOM-killing a service.
swap_file: /swapfile
swap_size_mb: 2048
# Low: only swap under real pressure, keep the page cache for the apps.
swap_swappiness: 10

View file

@ -0,0 +1,49 @@
---
- 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