Linux Swapfile

There’s a more updated post here.

Setup Swap on CentOS Localhost:

# Check memory & swap file
free -m

# Check available disk space
df -h

# Allocate swapfile, set appropriate permissions, create swapfile
sudo dd if=/dev/zero of=/swapfile count=4096 bs=1MiB #allocate
chmod 600 /swapfile #secure the directory
mkswap /swapfile #make swapfile in the /swapfile directory
swapon /swapfile #configure system to use /swapfile

# Check swapfile settings
swapon -s

# Make permanent
vim /etc/fstab
# add this line
/swapfile none swap defaults 0 0
Ansible Playbook

# need to be root
- debug: msg="{{ ansible_memtotal_mb }}M swapfile size"

- stat: path=/swapfile
register: swap

- debug: var=swap.stat.exists

- command: fallocate -l {{ ansible_memtotal_mb }}M /swapfile
when: swap.stat.exists == false

- file: path=/swapfile mode=0600
when: swap.stat.exists == false or (swap.stat.exists == true and swap.stat.mode != 0600)

- command: mkswap /swapfile
when: swap.stat.exists == false

- command: swapon /swapfile
when: swap.stat.exists == false

- lineinfile: dest=/etc/fstab
line='/swapfile none swap sw 0 0'
when: swap.stat.exists == false

- sysctl: name=vm.swappiness value=1 state=present
Posted on Categories Linux

Leave a Reply

Your email address will not be published. Required fields are marked *