1、背景:公司研发新提交项目需求,需要分配21台虚拟机,需要额外挂载一块数据盘,更改模板的默认密码。经过分析发现,所有虚拟机的需求相同,正好最近在学习ansible,可以使用ansible进行管理配置。
2、首先先将21台虚拟机分配好,并配置网络。
3、在环境中找到一台跟这21台虚拟机能通的虚拟机,安装ansible
[root@localhost ~]# yum install epel-release -y
[root@localhost ~]# yum -y install ansible
根据之前学习的建议,新建一个ansible文件夹,编辑ansible配置文件
[root@localhost ~]# mkdir ansible
[root@localhost ~]# cd ansible/
[root@localhost ansible]# vim ansible.cfg
[defaults]
inventory=hosts
host_key_checking = False ###因为本次使用用户名加密码方式控制虚拟机,所以提示host_key有报错,加入这一行将验证关闭。
配置主机配置文件
[root@localhost ansible]# vim hosts
[group]
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=c******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=c******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX ansible_ssh_user=root ansible_ssh_pass=******
XX.XX.XX.XX表示虚拟机的ip地址,ansible_ssh_user表示ansible的用户,ansible_ssh_pass表示ansible用户的密码
4、配置完成以后,使用ping模块进行测试
[root@localhost ansible]# ansible XX.XX.XX.XX -m ping
发现所有设备都可以测试成功
5、编写硬盘挂载脚本并赋予执行权限
[root@localhost ansible]# vim mount.sh
#!/bin/bash
mkdir /data
echo " n
p
1
w" | fdisk /dev/sdb
mkfs.xfs /dev/sdb1
mount /dev/sdb1 /data
echo " /dev/sdb1 /data xfs defaults 0 0" >> /etc/fstab
chmod 777 mount.sh
6、使用ansilbe脚本模块进行执行
[root@localhost ansible]# ansible all -m script -a 'mount.sh'
可以看到每台执行成功的提示
[root@localhost ansible]# ansible XX.XX.XX.XX -a 'df -h' 使用ansible命令模块 ,进行查看
可以发现已经挂载成功
7、编写更改密码的脚本
[root@localhost ansible]# vim changepass.sh
#!/bin/bash
echo "******" | passwd --stdin root
[root@localhost ansible]# chmod 777 changepass.sh
8、使用ansilbe脚本模块进行执行
[root@localhost ansible]# ansible all -m script -a 'changepass.sh'
9、使用xshell进行远程登陆验证,发现密码已经更改,本次任务圆满完成,节约了大量的时间,避免20多次重复操作。