Opinionated Programmer - Jo Liss's musings on enlightened software development.

Creating a swap file with Chef

In case anyone else needs this, here is my Chef snippet to create a swap file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
script 'create swapfile' do
  interpreter 'bash'
  not_if { File.exists?('/var/swapfile') }
  code <<-eof
    dd if=/dev/zero of=/var/swapfile bs=1M count=2048 &&
    chmod 600 /var/swapfile &&
    mkswap /var/swapfile
  eof
end

mount '/dev/null' do  # swap file entry for fstab
  action :enable  # cannot mount; only add to fstab
  device '/var/swapfile'
  fstype 'swap'
end

script 'activate swap' do
  interpreter 'bash'
  code 'swapon -a'
end

Normally I would use “none” as the mount point for a swap file, but Chef requires the mount point to exist, so we use /dev/null instead. Chef cannot mount the fstab entry it just created (because it only calls mount), so we use swapon.

Depending on how fast your disk is (I’m looking at you, Amazon!), dd can take a while, so I recommend you put this at the end of your recipe (or recipe list).

P.S. In case you were wondering where to put the swap file: Apparently /var/swapfile is as good a place as any.

P.P.S. No proselytizing in the comments about how swap partitions are faster please, unless you show me a benchmark. ;-)