设为首页 收藏本站
查看: 1403|回复: 0

[经验分享] ansible安装以及配置优化和实现动态inventory

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2017-2-16 10:03:15 | 显示全部楼层 |阅读模式
系统环境

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
1
yum install ansible -y



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.






运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-342857-1-1.html 上篇帖子: Ansible批量部署zabbix-agent 下篇帖子: 我来逛逛 动态
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表