首页 > 代码库 > ansible安装以及配置优化和实现动态inventory
ansible安装以及配置优化和实现动态inventory
系统环境
# 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包
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
yum install ansible -y
2.配置ansible,优化配置,提高ansible性能【/etc/ansible/ansible.cfg】
[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性能
$ 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的执行时间
$ 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))) ) )
执行的效果如下
test connection --------------------------------------------------------- 1.17s Playbook finished: Wed Feb 15 13:09:06 2017, 1 total tasks. 0:00:01 elapsed.
4.编写ansible的动态inventory脚本
$ 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)
主机列表如下 more hostlist.txt backup01.cn 10.44.245.85
测试playbook:test.yml
$ more test.yml - hosts: all remote_user: test gather_facts: no become: yes become_method: sudo tasks: - name: test connection ping:
执行结果如下:
$ 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.
本文出自 “Linux之旅” 博客,请务必保留此出处http://openlinuxfly.blog.51cto.com/7120723/1898010
ansible安装以及配置优化和实现动态inventory
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。