Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
main.yml 1.63 KiB
---

- name: Add additional swap if necessary.
  block:
    - name: Check if swapfile is in use.
      shell:
        cmd: swapon --show=name --noheadings |
             grep -qFx -- {{ swapfile_name | quote }}
      check_mode: false
      failed_when: r.rc not in [0, 1]
      changed_when: false
      register: r

    - name: Disable swapping to swapfile.
      command:
        cmd: swapoff -- {{ swapfile_name | quote }}
      when: not r.rc

    - name: "Update fact: ansible_swaptotal_mb."
      setup:
        filter: ansible_swaptotal_mb

    - name: Create swapfile.
      command:
        # The swapfile's header takes up 4 KiB.
        cmd: dd if=/dev/zero of={{ swapfile_name | quote }} bs=1024
             count={{ (minimum_memory_mb - ansible_memtotal_mb -
                      ansible_swaptotal_mb) * 1024 + 4 }}

    - name: Set swapfile permissions.
      file:
        path: "{{ swapfile_name }}"
        owner: root
        mode: 0600

    - name: Format swapfile.
      command:
        cmd: mkswap -- {{ swapfile_name | quote }}

    - name: Add swapfile to fstab.
      mount:
        src: "{{ swapfile_name }}"
        path: none
        fstype: swap
        state: present

    - name: Enable swapping for file.
      command:
        cmd: swapon -- {{ swapfile_name | quote }}

    - name: "Update fact: ansible_swaptotal_mb."
      setup:
        filter: ansible_swaptotal_mb

    # Nota bene: No tasks belong below this point in the block. The "when"
    # clause is re-evaluated before each task, and the setup call above this
    # will make it evaluate to false.
  when: ansible_memtotal_mb + ansible_swaptotal_mb < minimum_memory_mb