Create a Linux Swap File in SaltStack

  • Using Salt Stack, it is quite easy to create a swap file on our Linux systems. We can add this to our SLS files.

        - name: |
            [ -f /swapfile ] || dd if=/dev/zero of=/swapfile bs=1M count={{ grains["mem_total"] * 2 }}
            chmod 0600 /swapfile
            mkswap /swapfile
            swapon -a
        - unless:
          - file /swapfile 2>&1 | grep -q "Linux/i386 swap"
        - persist: true

    This is Linux specific and will not work on other operating systems. It's common with modern cloud VMs that no swap space is provided and creating a swap file on top of the normal file system is warranted. This command doesn't just make a swap file but looks up the system of the memory on the system and doubles it before making the swap file. So if you have a 2GB RAM VM, this will create a 4GB swap file. Easy to modify if you want half the swap space as memory, one to one or whatever. And it adds the swapspace to the /etc/fstab file for persistence.