Skip to content

Instantly share code, notes, and snippets.

@devster31
Forked from manuelmeurer/swap.yml
Last active February 28, 2024 10:43
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save devster31/74e48cc1c8e73c637bc7 to your computer and use it in GitHub Desktop.
Save devster31/74e48cc1c8e73c637bc7 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: /{{ 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: Create swap space
command: dd if=/dev/zero of=/extraswap bs=1M count=512
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"
@HankB
Copy link

HankB commented Jun 14, 2023

God morning and thanks for sharing this. There are a couple things I do not understand.

  1. line #12 you create the swap file using the variable swap_file which appears to be the length of the swap file in bytes with .swap tacked on.
  2. line 16 you zero out a file named /extraswap with an arbitrary length and that file appears to be otherwise unused.

Is this something overlooked or am I missing something.

Edit.0: According to https://linuxize.com/post/how-to-change-the-swappiness-value-in-linux/ the swappiness change will revert to the default on the next boot w/out changing /etc/sysctl.conf

@nielsonsantana
Copy link

In my tests, the value for vm.swappiness will be persisted on /etc/sysctl.conf. I rebooted my instance and the value still in `/etc/sysctl.conf,

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