A D Vishnu Prasad

Director of Cloud Engineering @ Team8Solutions, Freelancer

Create Swap Using Ansible in Ubuntu

This ansible script will help you to create SWAP memory in a single command. Just change this line based on your required memory.

For 4 GB : command: dd if=/dev/zero of=/swapfile bs=1G count=4

For 2 GB : command: dd if=/dev/zero of=/swapfile bs=1G count=2

Playbook command
1
ansible-playbook swap.yml -i inventorys/hosts --ask-pass
swap.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
- name: Create swap
  hosts: all
  remote_user: advp
  become: True
  become_method: sudo
  become_user: root
  gather_facts: True

  tasks:
    - name: Check whether swap is already enabled or not
      shell: cat /etc/sysctl.conf
      register: swap_enabled

    - block:
      - name: create swap file
        command: dd if=/dev/zero of=/swapfile bs=1G count=4

      - name: change permission type
        file: path=/swapfile mode=600 state=file

      - name: setup swap
        command: mkswap /swapfile
    
      - name: create swap
        command: swapon /swapfile

      - name: Add to fstab
        action: lineinfile dest=/etc/fstab regexp="swapfile" line="/swapfile none swap sw 0 0" state=present

      - name: start swap
        command: swapon -a

      - name: set swapiness
        sysctl:
          name: vm.swappiness
          value: "10"

      - name: set swapiness
        sysctl:
          name: vm.vfs_cache_pressure
          value: "50"

      when: swap_enabled.stdout.find('swappiness') == -1