|
系统环境
1
2
3
4
5
6
7
8
9
| # uname -a
Linux puppetserver25 2.6.32-431.el6.x86_64 #1 SMP Sun Nov 10 22:19:54 EST 2013 x86_64 x86_64 x86_64 GNU/Linux
# cat /etc/issue
Red Hat Enterprise Linux Server release 6.5 (Santiago)
Kernel \r on an \m
# python -V
Python 2.6.6
|
所需要的rpm包
1
2
3
4
5
6
7
8
9
10
| ansible-2.2.1.0-1.el6.noarch.rpm
libyaml-0.1.3-4.el6_6.x86_64.rpm
python-argparse-1.2.1-2.1.el6.noarch.rpm
python-crypto2.6-2.6.1-2.el6.x86_64.rpm
python-httplib2-0.7.7-1.el6.noarch.rpm
python-jinja2-26-2.6-3.el6.noarch.rpm
python-keyczar-0.71c-1.el6.noarch.rpm
python-six-1.9.0-2.el6.noarch.rpm
PyYAML-3.10-3.1.el6.x86_64.rpm
sshpass-1.05-1.el6.x86_64.rpm
|
服务器如果可以出公网可以使用pip或者yum安装ansible
1.安装ansible
2.配置ansible,优化配置,提高ansible性能【/etc/ansible/ansible.cfg】
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
| [defaults]
forks = 150
transport = paramiko
#使用facter缓存,默认使用内存,支持redis
gathering = implicit
fact_caching_timeout = 86400
fact_caching = jsonfile
fact_caching_connection = /etc/ansible/facts/cache
host_key_checking = False
remote_user = test
deprecation_warnings = False
callback_plugins = /etc/ansible/callback_plugins
retry_files_enabled = False
[privilege_escalation]
become=True
become_method=sudo
become_user=root
become_ask_pass=False
[paramiko_connection]
[ssh_connection]
ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no
pipelining = True
[accelerate]
[selinux]
[colors]
|
优化ssh,提高ansible性能
1
2
3
4
5
6
7
8
| $ more ~/.ssh/config
Host *
Compression yes
ServerAliveInterval 60
ServerAliveCountMax 5
ControlMaster auto
ControlPath ~/.ssh/%r@%h-%p
ControlPersist 4h
|
3.启用ansible的callback_plugins 显示ansible-playbook的执行时间
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
| $ more callback_plugins/profile_tasks.py
import datetime
import os
import time
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
"""
A plugin for timing tasks
"""
def __init__(self):
super(CallbackModule, self).__init__()
self.stats = {}
self.current = None
def playbook_on_task_start(self, name, is_conditional):
"""
Logs the start of each task
"""
if os.getenv("ANSIBLE_PROFILE_DISABLE") is not None:
return
if self.current is not None:
# Record the running time of the last executed task
self.stats[self.current] = time.time() - self.stats[self.current]
# Record the start time of the current task
self.current = name
self.stats[self.current] = time.time()
def playbook_on_stats(self, stats):
"""
Prints the timings
"""
if os.getenv("ANSIBLE_PROFILE_DISABLE") is not None:
return
# Record the timing of the very last task
if self.current is not None:
self.stats[self.current] = time.time() - self.stats[self.current]
# Sort the tasks by their running time
results = sorted(
self.stats.items(),
key=lambda value: value[1],
reverse=True,
)
# Just keep the top 10
results = results[:10]
# Print the timings
for name, elapsed in results:
print(
"{0:-<70}{1:->9}".format(
'{0} '.format(name),
' {0:.02f}s'.format(elapsed),
)
)
total_seconds = sum([x[1] for x in self.stats.items()])
print("\nPlaybook finished: {0}, {1} total tasks. {2} elapsed. \n".format(
time.asctime(),
len(self.stats.items()),
datetime.timedelta(seconds=(int(total_seconds)))
)
)
|
执行的效果如下
1
2
3
4
|
test connection --------------------------------------------------------- 1.17s
Playbook finished: Wed Feb 15 13:09:06 2017, 1 total tasks. 0:00:01 elapsed.
|
4.编写ansible的动态inventory脚本
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
39
40
41
42
| $ more inventory.py
#!/usr/bin/env python
import argparse
import sys
try:
import json
except ImportError:
import simplejson as json
def RFile():
with open('hostlist.txt', 'r+') as f:
result=[]
for line in f.readlines():
host = line.strip().split()
if host:
result.append(host)
return result
host_list = RFile()
def groupList():
group_list = []
for host in host_list:
group_list.append(host[1])
print (json.dumps({"all":group_list},indent=4))
def hostList(key):
host_dict = {}
for host in host_list:
host_dict[host[1]] = {"ansible_ssh_host": host[1],"ansible_ssh_port":9999, "ansible_ssh_user":"test","ansible_ssh_pass":
"test","hostname":host[0]}
print (json.dumps(host_dict[key], indent=4))
if len(sys.argv) == 2 and (sys.argv[1] == '--list'):
groupList()
elif len(sys.argv) == 3 and (sys.argv[1] == '--host'):
hostList(sys.argv[2])
else:
print "Usage: %s --list or --host <hostname>" % sys.argv[0]
sys.exit(1)
|
1
2
3
| 主机列表如下
more hostlist.txt
backup01.cn 10.44.245.85
|
测试playbook:test.yml
1
2
3
4
5
6
7
8
9
| $ more test.yml
- hosts: all
remote_user: test
gather_facts: no
become: yes
become_method: sudo
tasks:
- name: test connection
ping:
|
执行结果如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
| $ ansible-playbook -i inventory.py test.yml
PLAY [all] *********************************************************************
TASK [test connection] *********************************************************
ok: [10.44.245.85]
PLAY RECAP *********************************************************************
10.44.245.85 : ok=1 changed=0 unreachable=0 failed=0
test connection --------------------------------------------------------- 1.17s
Playbook finished: Wed Feb 15 13:20:09 2017, 1 total tasks. 0:00:01 elapsed.
|
|
|