Myluzh Blog

使用Ansible-Playbook批量扩容云主机系统盘

发布时间: 2024-7-18 文章作者: myluzh 分类名称: Linux 朗读文章


0x00 前言 
接到一个需求,有200台云主机系统盘扩容到了80g,/dev/sda已经变成了80g,需要对dev/sda1扩展分区大小。
0x01 编写主机清单
myluzh@myluzhMacBookPro % cat inventory 
[node]
36.134.92.10
36.212.225.133
36.212.225.129
36.212.225.222
....

# 给node这个组设置账号密码
[node:vars]
ansible_ssh_port=22
ansible_ssh_user=root
ansible_ssh_pass="k@s8#as0912e"
# ansible_python_interpreter=/usr/bin/python3.10
0x02 编写playbook
myluzh@myluzhMacBookPro % cat  playbook.yml
- name: 批量扩容磁盘
  hosts: all
  max_fail_percentage: 0
  become: yes
  tasks:
    - name: 获取/dev/sda大小
      shell: lsblk /dev/sda | awk 'NR==2 {print $4}' | tr -d 'G'
      register: sda_size

    - name: 获取未扩容之前的/dev/sda1大小
      shell: lsblk /dev/sda1 | awk 'NR==2 {print $4}' | tr -d 'G'
      register: sda1_size_before

    - name: 扩展分区大小
      command: growpart /dev/sda 1
      when: sda_size.stdout|int >= 80 and sda1_size_before.stdout|int < sda_size.stdout|int

    - name: 调整文件系统大小
      command: resize2fs /dev/sda1
      when: sda_size.stdout|int >= 80 and sda1_size_before.stdout|int < sda_size.stdout|int

    - name: 获取扩容后的/dev/sda1大小
      shell: lsblk /dev/sda1 | awk 'NR==2 {print $4}' | tr -d 'G'
      register: sda1_size_after

    - name: 检查扩容是否成功
      assert:
        that:
          - sda_size.stdout|int >= 80
          - sda1_size_after.stdout|int >= sda_size.stdout|int
0x03 执行playbook
-f 20就是并发20.
myluzh@myluzhMacBookPro % ansible-playbook -i inventory playbook.yml -f 20
36.134.178.242             : ok=7    changed=5    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
36.134.71.19               : ok=7    changed=5    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
36.134.92.10               : ok=5    changed=3    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0   
36.137.22.91               : ok=7    changed=5    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  
......

标签: ansible playbook 云主机 磁盘扩容

发表评论