Adding a SwapFile to Linux Using SaltStack

  • Most cloud hosting platforms do not include swap space when deploy Linux, but often we want to have it available to us. It is cumbersome, if not impossible, to make a dedicated swap device like we normally would using a traditional Linux install, so using a swapfile is needed instead.

    It is relatively traditional to use the file /swapfile for our swap space. Using the following SaLt State file we can control our swapfile very easily.

    cat /srv/salt/swap.sls

        - 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
        - name: /etc/sysctl.conf
        - text: vm.swappiness = 10

    The first section using the Salt Grain "mem_total" to detect the amount of installed on our Linux server and then doubles that number for the size of our swapfile. (You can easily adjust this as needed.)

    The second section configures the kernel swappiness setting. A setting of "10" is pretty standard for a VPS system. The lower the number, the less likely the system is to swap. A physical install would normally use a default of "60". You can normally stick with ten here, but "5" would work well, too. I would rarely recommend going higher than "10" on a VM, as this can cause performance issues and does not play nicely in a shared environment.

    You can apply the swap settings with this command:

    salt 'myserver' state.apply swap