Skip to content

Instantly share code, notes, and snippets.

@manuelmeurer
Created June 30, 2015 09:29
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save manuelmeurer/a2c0a8c24a0bb5092250 to your computer and use it in GitHub Desktop.
Save manuelmeurer/a2c0a8c24a0bb5092250 to your computer and use it in GitHub Desktop.
Ansible role for creating a Swap file
- name: set swap_file variable
set_fact:
swap_file: /mnt/{{ swap_space }}.swap
- name: check if swap file exists
stat:
path: "{{ swap_file }}"
register: swap_file_check
- name: create swap file
sudo: yes
command: fallocate -l {{ swap_space }} {{ swap_file }}
when: not swap_file_check.stat.exists
- name: set permissions on swap file
sudo: yes
file:
path: "{{ swap_file }}"
mode: 0600
- name: format swap file
sudo: yes
command: mkswap {{ swap_file }}
when: not swap_file_check.stat.exists
- name: add to fstab
sudo: yes
lineinfile:
dest: /etc/fstab
regexp: "{{ swap_file }}"
line: "{{ swap_file }} none swap sw 0 0"
- name: turn on swap
sudo: yes
command: swapon -a
- name: set swapiness
sudo: yes
sysctl:
name: vm.swappiness
value: "1"
@pavelanni
Copy link

Great tool to create swap! I had to correct it though while using it on EC2/CentOS7/XFS. Apparently fallocate is not the right way to create swap files on XFS. swapon gives you an error. So I switched to plain dd instead. Everything else worked perfectly for me. Thanks!

@manishshukla4u
Copy link

I want to create swap on disk by using lvm module so that I can create swap vol conditional. lets say swap should be 2x memory when memory is <=4, 1x memory from 4-16 and 16 when memory is > 16. Please suggest.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment