ansible动态Inventory主机清单配置遇到的坑


Posted in Python onJanuary 19, 2020

坑1 : 动态主机清单配置,需要按照ansible的要求的格式返回给ansible命令的

源代码如下:

但是在ansible-playbook中使用动态主机配置文件的时候,发生了错误!!!

ansible动态Inventory主机清单配置遇到的坑

提示没有匹配的主机信息

分析: 数据库已配置好,python脚本也能输出,问题在于输出的结果不是ansible想要的格式作为ansible的命令输入,因此排查如下

下面看下我的动态inventory输出的格式吧

[root@ansible fang]# python ansible_inventory.py --list
{
  "all": [
    "192.168.10.104"
  ]
}
[root@ansible fang]# python ansible_inventory.py --host 192.168.10.104
{
  "ansible_ssh_host": "192.168.10.104",
  "ansible_ssh_user": "root",
  "hostname": "clone-node1"
}

在网上找的方法,虽然实现了—list  --host的输出,但是格式不满足ansible格式输出的要求,ansible需求的格式有哪些呢,请看解决办法中….

输出结果:

这是出错的信息,提示还是找不到主机的信息

[root@ansible fang]#
ansible-playbook -i ansible_inventory.py bb.yml运行出错

解决方法:

先说个知识点(ansible所要求的格式):

动态 Inventory 指通过外部脚本获取主机列表,并按照 ansible 所要求的格式返回给 ansilbe 命令的

因此,需要清楚ansible需要那种inventory的格式呢

必须输出为 JSON 格式

同时必须支持两个参数:--list 和 --host <hostname>。

--list:用于返回所有的主机组信息,每个组所包含的主机列表 hosts、所含子组列表 children、主机组变量列表 vars 都应该是字典形式的,_meta 用来存放主机变量。

正确的输出格式是什么样子的呢,请看下面:

以下的是正确的动态inventory的输出格式,其中就是ansible的第三点要求 每个组所包含的主机列表 hosts、所含子组列表 children、主机组变量列表 vars 都应该是字典形式的,_meta 用来存放主机变量。

[root@ansible fang]# vim tt.py
[root@ansible fang]# python tt.py
{
  "group1": {
    "hosts": [
      "192.168.10.104"
    ]
  },
  "group2": {
    "hosts": [
      "192.168.10.103",
      "192.168.13.5"
    ],
    "vars": {
      "ansible_ssh_port": 22,
      "ansible_connection": "ssh"
    }
  }
}
[root@ansible fang]#

按照以上的格式,来编写我们的输出吧,

SQL表格内容如下:

ansible动态Inventory主机清单配置遇到的坑

我想要输出的json格式是这样的

{组名:{
hosts:[‘ip1','ip2'],
vars:{
  “ansible_ssh_port”:22,
“ansilble_connection”:'ssh'
……….
}
}
}

脚本代码列出来了如下:

#_*_coding:utf-8_*_
__author__ = 'fang'
import pymysql
import json
import argparse
import sys
def execude_sql(table): #定义一个执行SQL的函数
  sql = 'select * from {0};'.format(table)
  cur.execute(sql) #args即要传入SQL的参数
  sys_result = cur.fetchall()
  #index = cur.description
  hostlist = {}#放入主机清单的信息
  for i in sys_result:
    hostlist[i[2]] = []
  for i in sys_result:
    hostlist[i[2]].append([i[1], i[5], i[6]])
  host_lists = dict()
  for i in hostlist.iteritems():
    dict_item = dict()
    for index in i[1]:
      dict_item[index[0]] = {'ansible_connection': index[1], 'ansible_ssh_port': index[2]}
    host_lists[i[0]] = dict_item
  # print json.dumps(host_lists, indent=4)
return host_lists
def group(data):
  '''
  all hostip
  :param data:
  :return:
  '''
  count_ip = dict()
  count_ip['all'] = {}
  count_ip['all']['hosts'] = []
  index = []
  for i in data:
    index.extend(data[i].keys())
  count_ip['all']['hosts'].extend(list(set(index)))
  print json.dumps(count_ip, indent=4)
def host(data, ip):
  dict_host = {}
  for i in data:
    if data[i].keys() == [ip]:
      dict_host[i] = {}
      dict_host[i]['hosts'] = [ip]
      dict_host[i]['vars'] = data[i][ip]
      print json.dumps(dict_host, indent=4)
      break
if __name__ == "__main__":
  global file, con, cur #文件对象,连接和游标对象
  #连接数据库
  con = pymysql.connect('127.0.0.1', 'root', '', 'ansible', charset='utf8') # 连接数据库
  cur = con.cursor() # 定义一个游标 
  data = execude_sql('hosts_table')
# parser = argparse.ArgumentParser()#定义参数解析器
#获取参数的方法1:
#以下是参数解析器添加参数格式,有—list和—host dest表示都可以通过args.list或者args.host来获取到可变参数的值,action中store_true表存储的是布尔值,当没有—list的时候默认false,当有—list的时候,但是没有值,默认则为true,help表示帮助时候提示的信息,argparse很好用,在这里恰当好处
  # parser.add_argument('--list',action='store_true',dest='list',help='get all hosts')
  # parser.add_argument('--host',action='store',dest='host',help='get sigle host')
  # args = parser.parse_args()
  # if args.list:
  #   group(data)
  # if args.host:
  #   host(data, args.host)
#获取参数的方法2:
   if len(sys.argv) == 2 and (sys.argv[1] == '--list'):
      group(data)
   elif len(sys.argv) == 3 and (sys.argv[1] == '--host'):
       host(data, sys.argv[2])
   else:
     print "Usage %s --list or --host <hostname>"% sys.argv[0]
     sys.exit(1)

坑 2: 动态inventory脚本要制定python的解释器,否则无法执行

问题分析:

Ansible-playbook ?I ansbile_inventory.py bb.yml执行

提示:无法识别host,还是出现了问题

对比ansible要求的格式,没有差别,最后进行代码的比对,问题出现在脚本没有制定Python解释器,导致出现的问题

解决办法:

添加python解释器的路径

ansible动态Inventory主机清单配置遇到的坑

执行结果:

Yml文件

ansible动态Inventory主机清单配置遇到的坑

命令执行结果:

[root@ansible fang]# ansible-playbook -i ansible_inventory.py bb.yml
PLAY [192.168.10.104] *********************************************************************
TASK [debug] *********************************************************************
ok: [192.168.10.104] => {
  "msg": "this is test block"
}
TASK [file] *********************************************************************
ok: [192.168.10.104]
TASK [debug] *********************************************************************
ok: [192.168.10.104] => {
  "msg": "this is always"
}
PLAY RECAP *********************************************************************
192.168.10.104       : ok=3  changed=0  unreachable=0  failed=0 
[root@ansible fang]# python ansible_inventory.py --host 192.168.10.104
{
  "xiaoming": {
    "hosts": [
      "192.168.10.104"
    ],
    "vars": {
      "ansible_ssh_port": 22,
      "ansible_connection": "ssh"
    }
  }
}

另外注意点:  --list    --host 正是通过yml中的hosts指定的内容,即为脚本中命令行的参数的内容

 总结

以上所述是小编给大家介绍的ansible动态Inventory主机清单配置遇到的坑,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Python 相关文章推荐
python使用rabbitmq实现网络爬虫示例
Feb 20 Python
python实现简单的计时器功能函数
Mar 14 Python
Python下使用Psyco模块优化运行速度
Apr 05 Python
Python学生成绩管理系统简洁版
Apr 05 Python
Django1.9 加载通过ImageField上传的图片方法
May 25 Python
通过python顺序修改文件名字的方法
Jul 11 Python
对TensorFlow的assign赋值用法详解
Jul 30 Python
安装Pycharm2019以及配置anconda教程的方法步骤
Nov 11 Python
python 实现两个npy档案合并
Jul 01 Python
如何使用Django Admin管理后台导入CSV
Nov 06 Python
python基础入门之普通操作与函数(三)
Jun 13 Python
asyncio异步编程之Task对象详解
Mar 13 Python
python实现五子棋游戏(pygame版)
Jan 19 #Python
Python turtle画图库&amp;&amp;画姓名实例
Jan 19 #Python
python3连接mysql获取ansible动态inventory脚本
Jan 19 #Python
基于Pycharm加载多个项目过程图解
Jan 19 #Python
使用Python脚本从文件读取数据代码实例
Jan 19 #Python
Python安装tar.gz格式文件方法详解
Jan 19 #Python
Python : turtle色彩控制实例详解
Jan 19 #Python
You might like
【COS正片】蕾姆睡衣cos,纯洁可爱被治愈了 cn名濑弥七
2020/03/02 日漫
PHP 获取文件权限函数介绍
2013/07/11 PHP
理清apply(),call()的区别和关系
2011/08/14 Javascript
18个非常棒的jQuery代码片段
2015/11/02 Javascript
JS字符串的切分用法实例
2016/02/22 Javascript
jQuery实现的导航动画效果(附demo源码)
2016/04/01 Javascript
浅析vue数据绑定
2017/01/17 Javascript
JS实现简易刻度时钟示例代码
2017/03/11 Javascript
JS+DIV实现的卷帘效果示例
2017/03/22 Javascript
详解使用nodeJs安装Vue-cli
2017/05/17 NodeJs
利用jquery去掉时光轴头尾部线条的方法实例
2017/06/16 jQuery
Vue.js获取被选择的option的value和text值方法
2018/08/24 Javascript
在Vue项目中引入JQuery-ui插件的讲解
2019/01/27 jQuery
node.js中事件触发器events的使用方法实例分析
2019/11/23 Javascript
js prototype深入理解及应用实例分析
2019/11/25 Javascript
react结合bootstrap实现评论功能
2020/05/30 Javascript
Python中用memcached来减少数据库查询次数的教程
2015/04/07 Python
python递归计算N!的方法
2015/05/05 Python
简单讲解Python中的数字类型及基本的数学计算
2016/03/11 Python
Python编程实现生成特定范围内不重复多个随机数的2种方法
2017/04/14 Python
Python3中bytes类型转换为str类型
2018/09/27 Python
Django项目中添加ldap登陆认证功能的实现
2019/04/04 Python
详解用Python为直方图绘制拟合曲线的两种方法
2019/08/21 Python
Python龙贝格法求积分实例
2020/02/29 Python
Pytorch转onnx、torchscript方式
2020/05/25 Python
keras的siamese(孪生网络)实现案例
2020/06/12 Python
Canvas 像素处理之改变透明度的实现代码
2019/01/08 HTML / CSS
美国最受欢迎的童装品牌之一:The Children’s Place
2016/07/23 全球购物
奉献演讲稿范文
2014/05/21 职场文书
公司应聘求职信
2014/06/21 职场文书
2014国庆节餐厅促销活动策划方案
2014/09/16 职场文书
中学生打架检讨书
2014/10/13 职场文书
签字仪式主持词
2015/07/03 职场文书
2016年妇联“6﹒26国际禁毒日”宣传活动总结
2016/04/05 职场文书
MySQL基于索引的压力测试的实现
2021/11/07 MySQL
GO语言异常处理分析 err接口及defer延迟
2022/04/14 Golang