Ansible Playbook: Add swapfile for Alibaba Cloud ECS(幂等,适配Alinux / CentOS / Ubuntu)
阿里云ECS注意:普通云盘不建议开swap;SSD/ESSD云盘才适合。小实例(1C/2G、2C/4G)最常用;大内存机器尽量不用swap,频繁swap会IO打满卡顿 。
fallocate 在部分XFS镜像不支持,playbook 优先fallocate,失败自动切dd。
add_swap_aliyun.yml
yaml
---
- name: Add swapfile on Aliyun ECS
hosts: aliyun_ecs
become: true
gather_facts: true
vars:
swap_file: "/swapfile"
swap_size_mb: 2048 # 2G,可自定义;内存<=2G建议2倍内存;2~8G等于内存;>8G不推荐
swappiness: 10 # aliyun推荐10,越低越优先用物理内存
vfs_cache_pressure: 50
tasks:
- name: Check if swapfile exists
stat:
path: "{{ swap_file }}"
register: swapfile_stat
- name: Check existing swap
command: swapon --show
register: swap_check
changed_when: false
ignore_errors: true
- name: Create swapfile with fallocate
command: fallocate -l {{ swap_size_mb }}M {{ swap_file }}
when: not swapfile_stat.stat.exists
register: fallocate_res
failed_when: false
- name: Fallocate failed, use dd fallback
command: dd if=/dev/zero of={{ swap_file }} bs=1M count={{ swap_size_mb }} status=none
when: >
not swapfile_stat.stat.exists
and fallocate_res is failed
- name: Set swapfile permission 0600
file:
path: "{{ swap_file }}"
mode: '0600'
owner: root
group: root
- name: Make swap filesystem
command: mkswap {{ swap_file }}
when: not swapfile_stat.stat.exists
- name: Enable swap
command: swapon {{ swap_file }}
when: not swapfile_stat.stat.exists
- name: Add swap to /etc/fstab (idempotent)
mount:
path: none
src: "{{ swap_file }}"
fstype: swap
opts: sw
state: present
- name: Set vm.swappiness in sysctl
sysctl:
name: vm.swappiness
value: "{{ swappiness }}"
state: present
reload: true
- name: Set vm.vfs_cache_pressure
sysctl:
name: vm.vfs_cache_pressure
value: "{{ vfs_cache_pressure }}"
state: present
reload: true
- name: Verify swap status
command: free -h
changed_when: false
register: free_out
- name: Print swap result
debug:
msg: "{{ free_out.stdout_lines }}"
执行命令
bash
ansible-playbook -i inventory.ini add_swap_aliyun.yml
inventory.ini 示例:
ini
[aliyun_ecs]
ecs-01 ansible_host=shturl.cc/dueD ansible_user=root ansible_ssh_private_key_file=~/.ssh/id_rsa
验证(在ECS内)
bash
swapon –show
free -h
cat /proc/sys/vm/swappiness
回滚/删除swap playbook片段(如需)
yaml
- name: Remove swapfile
become: true
tasks:
- name: swapoff
command: swapoff /swapfile
- name: Remove fstab entry
mount:
path: none
src: /swapfile
state: absent
- name: Delete swapfile
file:
path: /swapfile
state: absent
阿里云ECS重要提醒
1. 普通高效云盘不要开swap,IO性能差,一旦频繁换页直接卡死实例;ESSD/SSD才适合
2. 预留磁盘空间:创建swap后剩余磁盘至少保留5GB空闲,否则风险高
3. 容器环境尽量不要在容器内部配置swap,在宿主机层面管理
4. swappiness=10 适合阿里云小实例,尽量减少磁盘交换
如果你需要,我可以改成根据ECS内存自动计算swap大小(不用手动写swap_size_mb,自动按内存判断)的版本。