Swap Ansible Role¶
An Ansible role to create, enable, and persist a swapfile on Linux servers.
Features¶
- Create or resize a swapfile
- Enable or disable swap
- Persist swap in
/etc/fstab - Optional sysctl tuning for swap behavior
- Fallocate or dd-based swapfile creation
Installation¶
Add the following to your requirements.yml:
roles:
- name: swap
src: https://gitlab.com/niclas-zone/tools/ansible/roles/swap.git
version: 1.0.0
scm: git
Then install:
Role Variables¶
| Variable | Default Value | Description |
|---|---|---|
swap_state |
"present" |
Desired swap state: "present" or "absent" |
swap_file_path |
"/swapfile" |
Path to the swapfile |
swap_size_mb |
2048 |
Swapfile size in MB |
swap_use_fallocate |
true |
Use fallocate to create the swapfile |
swap_file_mode |
"0600" |
Swapfile permissions |
swap_persist |
true |
Persist swap entry in /etc/fstab |
swap_fstab_options |
"sw" |
Fstab options for the swapfile |
swap_swappiness |
null |
Set vm.swappiness (null leaves unchanged) |
swap_vfs_cache_pressure |
null |
Set vm.vfs_cache_pressure (null leaves unchanged) |
swap_manage_in_container |
false |
Allow swap activation inside containers |
Example Playbooks¶
Basic: Create a 1 GB swapfile¶
Custom swapfile and sysctl tuning¶
---
- hosts: servers
become: true
roles:
- role: swap
vars:
swap_file_path: "/var/swapfile"
swap_size_mb: 4096
swap_swappiness: 10
swap_vfs_cache_pressure: 50
Disable swap¶
Notes¶
- This role manages a swapfile only. It does not modify existing swap partitions.
- Swap activation is skipped in containers unless
swap_manage_in_container: true.