背景
刚刚开通了 100 台 CentOS7 服务器,现在要批量分区怎么办?一台台的操作显然不符合我摸鱼的风格,既然每台操作都一样,Ansible Roles 就有用武之地了。
正常分区流程
- fdisk -l 查看有哪些磁盘
- fdisk /dev/sdb 新建分区,保存
- mkfs.xfs /dev/sdb1 格式化为 xfs 格式
- mkdir -p /data 新建目录
- mount /dev/sdb1 /data 挂载
- 编辑 /etc/fstab ,服务器重启后自动挂载
可以看到这个过程是比较繁琐的,光打字我都觉得累了。下面是详细过程:
[root@wlj179 ~]# fdisk -l|grep 'Disk /dev/'
Disk /dev/sda: 479.0 GB, 478998953984 bytes, 935544832 sectors
Disk /dev/sdb: 1999.0 GB, 1998998994944 bytes, 3904294912 sectors
Disk /dev/mapper/centos-root: 107.4 GB, 107374182400 bytes, 209715200 sectors
Disk /dev/mapper/centos-swap: 17.2 GB, 17179869184 bytes, 33554432 sectors
[root@wlj179 ~]# fdisk /dev/sdb
Welcome to fdisk (util-linux 2.23.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.
Command (m for help): n
Partition type:
p primary (0 primary, 0 extended, 4 free)
e extended
Select (default p): p
Partition number (1-4, default 1):
First sector (2048-3907029167, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-3907029167, default 3907029167):
Using default value 3907029167
Partition 1 of type Linux and of size 1.8 TiB is set
Command (m for help): w
The partition table has been altered!
Calling ioctl() to re-read partition table.
Syncing disks.
[root@wlj179 ~]# mkfs.xfs /dev/sdb1
meta-data=/dev/sdb1 isize=512 agcount=4, agsize=122094598 blks
= sectsz=512 attr=2, projid32bit=1
= crc=1 finobt=0, sparse=0
data = bsize=4096 blocks=488378390, imaxpct=5
= sunit=0 swidth=0 blks
naming =version 2 bsize=4096 ascii-ci=0 ftype=1
log =internal log bsize=4096 blocks=238466, version=2
= sectsz=512 sunit=0 blks, lazy-count=1
realtime =none extsz=4096 blocks=0, rtextents=0
[root@wlj179 ~]# mkdir -p /data
[root@wlj179 ~]# mount /dev/sdb1 /data/
[root@wlj179 ~]# cat /etc/fstab
#
# /etc/fstab
# Created by anaconda on Thu Mar 26 04:55:31 2020
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root / xfs defaults 0 0
UUID=0135710d-4dd6-4a55-98a3-9453637e441a /boot xfs defaults 0 0
/dev/mapper/centos-swap swap swap defaults 0 0
/dev/sdb1 /data xfs defaults 0 0
Ansible playbooks
通俗的说,把 playbooks 理解为一个 shell 脚本就差不多了,一样是执行以后实现某个功能。
简单来说, playbooks 是一种简单的配置管理系统与多机器部署系统的基础.与现有的其他系统有不同之处,且非常适合于复杂应用的部署.
Playbooks 可用于声明配置,更强大的地方在于,在 playbooks 中可以编排有序的执行过程,甚至于做到在多组机器间,来回有序的执行特别指定的步骤.并且可以同步或异步的发起任务.
我们使用 adhoc 时,主要是使用 /usr/bin/ansible 程序执行任务.而使用 playbooks 时,更多是将之放入源码控制之中,用之推送你的配置或是用于确认你的远程系统的配置是否符合配置规范.
批量分区
[root@iZ88n11npysZ fdisk]# more tasks/main.yaml
---
- name: Create a new primary partition
parted:
device: /dev/sdb
number: 1
state: present
- name: Create a xfs filesystem on /dev/sdb
filesystem:
fstype: xfs
dev: /dev/sdb1
- name: Create folder
shell: mkdir -p /data
- name: Mount up device by label
mount:
path: /data
src: /dev/vdb1
fstype: xfs
state: mounted
执行
ansible-playbook main.yaml
亲测 5s 完成一台。