Skip to content

Instantly share code, notes, and snippets.

@yukithm
Last active February 22, 2024 09:23
Show Gist options
  • Save yukithm/d154b289743c35c64874837661de9cab to your computer and use it in GitHub Desktop.
Save yukithm/d154b289743c35c64874837661de9cab to your computer and use it in GitHub Desktop.
Make swap by cloud-init
#cloud-config
mounts:
- [ "/swapfile", "none", "swap", "defaults", "0", "0" ]
runcmd:
- [ "dd", "if=/dev/zero", "of=/swapfile", "bs=1G", "count=4" ]
- [ "chmod", "600", "/swapfile" ]
- [ "mkswap", "/swapfile" ]
- [ "swapon", "/swapfile" ]
@wrossmann
Copy link

wrossmann commented Jan 20, 2023

[ 65.622030] cloud-init[1099]: runcmd.1: ['chmod', 600, '/swapfile'] is not valid under any of the given schemas

All the command bits should likely be quoted, but at the least 600 should be.

@yukithm
Copy link
Author

yukithm commented Jan 20, 2023

Thank you for pointing this out.

root@38342f50b99d:/tmp# cat cloud-config.yaml
#cloud-config
mounts:
  - [ "/swapfile", "none", "swap", "defaults", "0", "0" ]

runcmd:
  - [ "dd", "if=/dev/zero", "of=/swapfile", "bs=1G", "count=4" ]
  - [ "chmod", "600", "/swapfile" ]
  - [ "mkswap", "/swapfile" ]
  - [ "swapon", "/swapfile" ]
root@38342f50b99d:/tmp# cloud-init schema -c cloud-config.yaml
Valid cloud-config: cloud-config.yaml

@nesterenkovy
Copy link

nesterenkovy commented Feb 22, 2024

It is better to use the standard function described in "cloud-init:Adjust mount points mounted".
Instead of the "runcmd:" section commands, add:

swap:
  filename: /.swapfile
  size: 1073741824

or

swap:
  filename: /.swapfile
  size: "auto"
  maxsize: 2147483648

This is enough to automatically create the file, format it, add the appropriate entry to /etc/fstab and execute swapon /swapfile.
So the line - ["/swapfile", "none", "swap", "defaults", "0", "0" ] in the mounts: section is not needed. It will create an unnecessary mount point.

grep swap /var/log/cloud-init.log
2024-02-22 11:04:35,604 - cc_mounts.py[DEBUG]: Creating swapfile in '/.swapfile' on fstype 'ext4' using 'fallocate'
2024-02-22 11:04:35,604 - subp.py[DEBUG]: Running command ['fallocate', '-l', '2048M', '/.swapfile'] with allowed return codes [0] (shell=False, capture=True)
2024-02-22 11:04:35,700 - subp.py[DEBUG]: Running command ['mkswap', '/.swapfile'] with allowed return codes [0] (shell=False, capture=True)
2024-02-22 11:04:35,838 - util.py[DEBUG]: Setting up swap file took 0.235 seconds
2024-02-22 11:04:35,842 - cc_mounts.py[DEBUG]: Changes to fstab: ['+ /.swapfile none swap sw,comment=cloudconfig 0 0']
2024-02-22 11:04:35,842 - subp.py[DEBUG]: Running command ['swapon', '-a'] with allowed return codes [0] (shell=False, capture=True)
2024-02-22 11:04:35,996 - cc_mounts.py[DEBUG]: Activate mounts: PASS:swapon -a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment