From b3bc776dd8d52f914b041479edb32a6d540f5e65 Mon Sep 17 00:00:00 2001 From: simon Date: Tue, 31 May 2022 19:59:07 +0700 Subject: [PATCH] create swap file if needed --- ansible-docker-ubuntu/playbook.yml | 1 + .../roles/swap/tasks/main.yml | 56 +++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 ansible-docker-ubuntu/roles/swap/tasks/main.yml diff --git a/ansible-docker-ubuntu/playbook.yml b/ansible-docker-ubuntu/playbook.yml index ada568e..0be9570 100644 --- a/ansible-docker-ubuntu/playbook.yml +++ b/ansible-docker-ubuntu/playbook.yml @@ -10,3 +10,4 @@ - docker - docker-compose - userconf + - swap diff --git a/ansible-docker-ubuntu/roles/swap/tasks/main.yml b/ansible-docker-ubuntu/roles/swap/tasks/main.yml new file mode 100644 index 0000000..cd32c8f --- /dev/null +++ b/ansible-docker-ubuntu/roles/swap/tasks/main.yml @@ -0,0 +1,56 @@ +--- + +- block: + - name: "check if swap is there" + command: swapon -s + register: swap + + - name: "get mem size" + shell: cat /proc/meminfo | grep -i 'memtotal' | grep -o '[[:digit:]]*' + register: mem_size + when: not swap.stdout + + - name: "calc swap size" + set_fact: + swap_size: | + {% if mem_size.stdout|int // 1024 > 4096 %} + mem_size.stdout|int // 1024 + {% else %} + 4096 + {% endif %} + when: not swap.stdout + + - name: "create swap file" + command: dd if=/dev/zero of=/swapfile bs=1M count={{ swap_size|int }} + when: not swap.stdout + + - name: Set swap file permissions + file: + path: "/swapfile" + state: "file" + owner: "root" + group: "root" + mode: "0600" + when: not swap.stdout + + - name: Initialize swap file + command: mkswap /swapfile + when: not swap.stdout + + - name: Enable swap file + command: swapon /swapfile + when: not swap.stdout + + - name: Manage swap file in /etc/fstab + mount: + src: "/swapfile" + name: "none" + fstype: "swap" + opts: "sw,nofail" + dump: "0" + passno: "0" + state: "present" + when: not swap.stdout + + become: true + become_user: root