今天由于项目需求,自己想了1小时,写出满足要求的shell 脚本:
主要实现下面功能:
管理的机器有800 多台,为了防止编辑的hostname 不准确,先在临时文件夹下编辑好hostname ,然后和hostname list 总表比较check ,如果正确,然后再放到ansible 的配置path: /etc/ansible/hosts 下,下面来看一下code:
先看一下文件:
root@sheng # cat host_ip_list
abc001 1.1.1.XXXXXXXXXXXXXXXXXXXXXX
abc002 1.1.1.2
abc003 1.1.1.3
abc004 1.1.1.4
abc005
abc006
[root@sheng sony]# cat host_ip_new
abc001 1.1.1.1
abc002 1.1.1.2
abc100 1.1.1.0
功能就是看host_ip_new 里面的host ,ip 是否再host_ip_list 是否正确:
#This is for Ansible project checking
#Anthor: David
#Date: 2019-07-02
#0: Pre-checking the ansible host file, delete it if exited:
cd /etc/ansible/
if [ ! -f "/etc/ansible/hosts" ];
then
echo " Ansible hosts is NOT exited, OK status, continue!"
else
rm -rf /etc/ansible/hosts
fi
echo "======================"
#1: First read the new host name:
cd /tool/scripts/sony
awk '{print $1}' host_ip_new > new_h
cat new_h | while read line;
do
NAME=$line
echo "The new hostname is: $NAME"
#2: checking the host in the host_list file
awk '/'"$NAME"'/{print}' host_ip_list > resultfile
RF=resultfile
# below line can display the corresponding line in the server list
# RF_content=`cat $RF`
# echo "$RF_content"
num=`cat $RF |wc -l`
if [ $num -eq 1 ]
then
echo "Hostname: OK!"
echo "======================"
#3: checking the IP in the list file.
awk '{print $2}' resultfile > ip01
ip02=ip01
ip03=`cat $ip02`
echo "the inventory list IP is: $ip03"
awk '/'"$NAME"'/{print $2}' host_ip_new > ip001
ip002=ip001
ip003=`cat $ip002`
echo "The new server IP is: $ip003"
if [ "$ip03" == "$ip003" ]
then
echo "the new host IP is OK"
else
echo "IP is wrong"
fi
echo "======================"
#4: write the host to Ansible configure path:
#cat host_new > /etc/ansible/hosts
else
echo "Please check the host name again!"
fi
done
----好的,下面来看一下运行结果:
[root@sheng ]# ./h.sh
Ansible hosts is NOT exited, OK status, continue!
======================
The new hostname is: abc001
Hostname: OK!
======================
the inventory list IP is: 1.1.1.XXXXXXXXXXXXXXXXXXXXXX
The new server IP is: 1.1.1.1
IP is wrong
======================
The new hostname is: abc002
Hostname: OK!
======================
the inventory list IP is: 1.1.1.2
The new server IP is: 1.1.1.2
the new host IP is OK
======================
The new hostname is: abc100
Please check the host name again!