工作中遇到的一个小问题,记录一下。假设有一千台机器运行着nginx但每台机器上的nginx目录可能不太一样,比如
/export/servers/openresty-local/nginx/
/export/servers/openresty/nginx/
/export/servers/openresty-ngx-ump/nginx/
现在要替换掉nginx目录下的某个脚本,并且重启这个nginx服务。需要用到的工具有Ansbile和自己写的批量替换脚本batch_op.py。
#准备远程机器列表
$ vim ip_list
10.191.172.201
10.190.143.38
10.187.110.4
10.190.49.237
10.190.198.192
10.190.163.211
#准备替换脚本
$ vim /tmp/b.sh
#!/bin/bash
if [ $(id -u) != "0" ]; then
echo "Error: need root to run this script."
exit 1
fi
a=`ps -ef | grep openresty | grep -v grep | awk '{ print $11 }' | cut -d\/ -f1,2,3,4`
if [ ! $a ]; then
echo 'Error! Not found $a directory.'
elif [ -f $a/lualib/resty/nginx_diviner.lua ]; then
cp $a/lualib/resty/nginx_diviner.lua $a/lualib/resty/nginx_diviner.lua.bak.`date +%Y%m%d%H%M%S` && \
wget -q -O $a/lualib/resty/nginx_diviner.lua http://172.22.193.65:8003/nginx_diviner.lua && \
chown admin:admin $a/lualib/resty/nginx_diviner.lua* && \
$a/nginx/sbin/nginx -s reload && \
echo "Found and replaced $a/lualib/resty/nginx_diviner.lua"
else
echo "Not Found $a/lualib/resty/nginx_diviner.lua"
exit 1
fi
if [ "$a" != "/export/servers/openresty" ] && [ -f /export/servers/openresty/lualib/resty/nginx_diviner.lua ]; then
cp /export/servers/openresty/lualib/resty/nginx_diviner.lua /export/servers/openresty/lualib/resty/nginx_diviner.lua.bak.`date +%Y%m%d%H%M%S` && \
wget -q -O /export/servers/openresty/lualib/resty/nginx_diviner.lua http://172.22.193.65:8003/nginx_diviner.lua && \
chown admin:admin /export/servers/openresty/lualib/resty/nginx_diviner.lua && \
echo "Extra Operation! also found and replaced /export/servers/openresty/lualib/resty/nginx_diviner.lua"
fi
把本地userA用户的key推送到远程root用户下, 实现本地userA用户无密码登陆到远程的root用户
$ vim deploy_key_local_admin_to_remote_root.yml #准备push ssh-key
- hosts: all
remote_user: root
gather_facts: no
tasks:
- name: install ssh key
authorized_key: user=root
key="{{ lookup('file', '/home/userA/.ssh/id_rsa.pub') }}"
state=present
$ vim push_file.yml #将本地的操作脚本Push到列表中的机器上
- hosts: all
user: root
tasks:
- name: push ump_agent_code to remote
copy:
src: /tmp/b.sh
dest: /tmp/
owner: admin
group: admin
mode: 0755
backup: no
follow: yes
开始操作
ansible-playbook -i ip_list deploy_ssh_key.yml -k #推送ssh key, 需要输入密码
ansible-playbook -i ip_list push_file.yml -u root #将/tmp/b.sh推送到ip_list所有机器的/tmp目录
./batch_op.py -f ip_list -u root "/tmp/b.sh" #批量在机器上执行b.sh并返回执行结果