#!/usr/bin/python
import ansible.runner
import sys
# construct the ansible runner and execute on all hosts
results = ansible.runner.Runner(
pattern='*', forks=10,
module_name='command', module_args='/usr/bin/uptime',
).run()
if results is None:
print "No hosts found"
sys.exit(1)
print "UP ***********"
for (hostname, result) in results['contacted'].items():
if not 'failed' in result:
print "%s >>> %s" % (hostname, result['stdout'])
print "FAILED *******"
for (hostname, result) in results['contacted'].items():
if 'failed' in result:
print "%s >>> %s" % (hostname, result['msg'])
print "DOWN *********"
for (hostname, result) in results['dark'].items():
print "%s >>> %s" % (hostname, result)
一个简单的执行shell命令的模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/env python
#coding:utf-8
import subprocess
import json
import os,sys
space = []
df= os.popen('df -P -k').read()
df = subprocess.Popen(["df", "-P", "-k"], stdout=subprocess.PIPE)
output = df.communicate()[0]
for line in output.split("\n")[1:]:
if len(line):
try:
device, size, used, available, percent, mountpoint = line.split()
space.append(dict(mountpoint=mountpoint, available=available))
except:
pass
print json.dumps(dict(space=space), indent=4)
总结:
这东西还行,真的可以用用。可以和puppet chef saltstack做互补。这段时间我看了不少国外的运维自动化,平台话。 我发现在老外的圈子里,ansible貌似比saltstack用的还广,看了老外大牛的文章, 他说 他们公司的老机器很多,没人敢动 ,看起来运维自动化在国外不少公司里也只是在慢慢的推进,并不是咱们想的那样的疯狂。