Add swap memory with ansible
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Adding swap with Ansible is mostly about making the operation safe and repeatable. The goal is not just to run fallocate once, but to create the swap file with correct permissions, enable it, and ensure the host keeps using it after reboot without redoing the work every playbook run.
What the Playbook Needs to Do
A complete swap playbook usually has five responsibilities:
- create the swap file if it does not exist
- lock down file permissions
- format it with
mkswap - enable it with
swapon - persist the configuration in
/etc/fstab
That sequence matters because swap files should not be world-readable, and persistence should be declared only after the file is valid.
A Practical Idempotent Playbook
This is a practical baseline. It avoids recreating the swap file if it already exists and ensures the system keeps the swap definition in fstab.
What About dd Instead of fallocate
Some filesystems or environments do not support fallocate well for swapfile creation. In that case, use dd as a slower but more portable fallback.
If you run on mixed Linux fleets, this fallback is worth knowing.
Tuning After Creation
Once swap exists, you may also want to manage kernel tuning such as vm.swappiness.
This does not change the size of swap. It changes how aggressively the kernel prefers swapping versus keeping pages in RAM.
Why Idempotency Matters Here
Swap setup is a classic case where a playbook can become destructive or noisy if written casually. Re-running mkswap against an active file or rewriting fstab incorrectly is avoidable if the tasks are guarded properly.
Ansible is most valuable when the second run is as safe as the first.
Common Pitfalls
The biggest pitfall is creating the file without setting mode 0600. Swap can contain sensitive memory pages, so open permissions are a real security problem.
Another issue is forgetting persistence. A manual swapon works until the next reboot, then the host quietly loses swap.
Developers also sometimes assume fallocate works everywhere. It is fast, but some environments need dd instead.
Finally, do not treat swap as a fix for chronic memory pressure. It can help a system survive bursts, but heavy swap usage usually means the workload or machine sizing still needs attention.
Summary
- A proper Ansible swap workflow creates, secures, formats, enables, and persists the swap file.
- Guard the creation steps so the playbook stays idempotent.
- Use
ddwhenfallocateis not suitable on the target system. - Consider managing
vm.swappinessalongside swap creation. - Swap helps with resilience, but it is not a substitute for enough RAM or healthy workload sizing.

