• +43 660 1453541
  • contact@germaniumhq.com

Disabling Swap for Kubernetes in an Ansible Playbook


Disabling Swap for Kubernetes in an Ansible Playbook

If you’re trying to install a Kubernetes on bare metal, it’s useful to document this experience in an Ansible playbook. This makes the installation of new clusters trivial. But after finishing the installation, on a reboot of the node, you might find out your cluster is not coming up. One possible reason is having the swap still enabled.

Kubernetes for some reason doesn’t play well with swap. So, if the container host has swap enabled, Kubernetes shuts down on startup. A prerequisite of having the node up, is disabling the swap on the running machine.

To disable this we need to have 2 steps. First we need to disable the swap for the currently running instance:

- name: Disable SWAP since kubernetes can't work with swap enabled (1/2)
  shell: |
    swapoff -a
  when: kubernetes_installed is changed

Next we need to ensure that on reboot we don’t get the swap back on:

- name: Disable SWAP in fstab since kubernetes can't work with swap enabled (2/2)
  replace:
    path: /etc/fstab
    regexp: '^([^#].*?\sswap\s+sw\s+.*)$'
    replace: '# \1'
  when: kubernetes_installed is changed

The funky regex just matches any line that contains swap sw, even with multiple spaces, only if it’s not already commented (thanks Manuel Perrot).

If now we have a playbook that uninstalls Kubernetes, we need apply the steps in the opposite direction:

- name: Reenable SWAP in fstab (1/2)
  replace:
    path: /etc/fstab
    regexp: '^# (.+?\sswap\s+sw\s+.*)$'
    replace: '\1'

- name: Enable SWAP (2/2)
  shell: |
    swapon -a

That’s it. From now on rebooting ensures our Kubernetes cluster won’t go down because the swap is enabled.