关闭

ansible在远程执行本地脚本

标签: 脚本
1846人阅读 评论(0) 收藏 举报
分类:
<span style="font-family: Arial, Helvetica, sans-serif;">#!/usr/bin/python</span>
import ansible.runner
import sys,os

#print len(sys.argv)
if len(sys.argv) != 3:
        print "usage: ansible-script <host-pattern> [scriptname and parms]"
        exit(1)
group_name=sys.argv[1]
script_name=sys.argv[2]

if not os.path.exists(script_name.split()[0]):
        print "%s:no such file" % (script_name.split()[0])
        exit(1)
results = ansible.runner.Runner(
pattern=group_name, forks=5,
module_name='script', module_args=script_name,
).run()

exit_code=0

#print results
#print results['contacted'].items()
if not results['contacted'].items() :
        print "No hosts found"
        sys.exit(1)
print "RESULTS ***********"
for (hostname, result) in results['contacted'].items():
#       print result
#       print "%s >>> %s" % (hostname, result['stdout'])
        if result['rc'] != 0:
                exit_code = result['rc']
                status =  "failed"
                print '\033[1;31;40m' #change frontcolor to red
                print "%s >>> %s \n%s" % (hostname,status,result['stdout'])
        else:
                status =  "success"
                print '\033[1;32;40m' #change frontcolor to green
                print "%s >>> %s \n%s" % (hostname,status,result['stdout'])
print '\033[0m'  #change frontcolor to default
sys.exit(exit_code)


使用方法:比如保存文件为ansible-script,运行命令为

 ansible-script <host-pattern> [scriptname and parms]

exp:  ansible-script testgroup test.sh



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2548次
    • 积分:52
    • 等级:
    • 排名:千里之外
    • 原创:3篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档