ansible同步/etc/crontab里面的脚本

Ansible批量部署与文件同步
本文介绍如何使用Ansible进行批量服务器管理,包括通过Ansible Runner模块执行远程脚本,从远程服务器收集IP地址,并根据收集到的信息生成用于后续部署任务的Ansible命令。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import ansible.runner
from ansible.color import stringc
import sys
import socket
import re
import subprocess
 
host_list = 'qa_servers.txt'
private_key_file = '/root/.ssh/id_rsa'
pattern = '*'
forks = 10
timeout = 30
module_name = 'script'
module_args = 'test.sh'
fp = open('/home/ip.txt'"w+")
# construct the ansible runner and execute on all hosts
results = ansible.runner.Runner(
    host_list=host_list,
    private_key_file=private_key_file,
    pattern=pattern,
    forks=forks,
    timeout=timeout,
    module_name=module_name,
    module_args=module_args
).run()
# print results
if results is None:
    print "No hosts found"
    sys.exit(1)
#print results
for (hostname, result) in results['contacted'].items():
    if not 'failed' in result:
        ip = result['stdout'].strip()
        if ip != "":
            output = open('/home/ip.txt''a')
            output.write(ip)
            output.write('\n')
fp.close()
1
2
3
4
5
6
7
cat test.sh
#!/bin/bash
#if [ `ps -ef|grep tomcat|grep /opt|wc -l` -gt 0 ];then
if [ `cat /etc/crontab|grep .sh|grep -v SHELL|awk '{print $8}'|uniq|wc -l` -gt 0 ];then
echo `ifconfig|grep 'inet '|grep -'127.0'|xargs|awk -'[ :]' '{print $3}'`
echo `cat /etc/crontab|grep .sh|grep -v SHELL|awk '{print $8}'|uniq`
fi
1
2
3
cat qa_servers.txt
ip1
ip2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# !/usr/bin/env python
# coding:utf-8
import os,sys,re
sfile="/home/ip.txt"
with open(sfile,'r') as f:
    rlist=f.readlines()
    # print rlist
    llen=len(rlist)
    for in range(llen - 1):
        if i%2==0:
            ip = rlist[i].strip()
            print "ansible -i /etc/ansible/hosts %s -m shell -a 'mkdir -p /home/run/%s'" %(ip,ip)
            command = rlist[i + 1].strip()
            comlist = command.split(' ')
            for in comlist:
                #print j
                print "ansible -i /etc/ansible/hosts %s -m synchronize -a 'mode=pull src=%s dest=/home/run/%s/'"\
                %(ip,j,ip)

自动生成

1
2
ansible -/etc/ansible/hosts ip1 -m shell -'mkdir -p /home/run/ip1'
ansible -/etc/ansible/hosts ip1 -m synchronize -'mode=pull src=/home/jenkins.sh dest=/home/run/ip1/'

需要两个python脚本,生成最后的脚本,执行就可以同步各个客户端中/etc/crontab的脚本。


一个简单而笨的思路。




本文转自 liqius 51CTO博客,原文链接:http://blog.51cto.com/szgb17/1925140,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值