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开发之for循环操作实例详解
Nov 12 Python
Python常用的内置序列结构(列表、元组、字典)学习笔记
Jul 08 Python
python开启摄像头以及深度学习实现目标检测方法
Aug 03 Python
Python常见数据结构之栈与队列用法示例
Jan 14 Python
wxPython多个窗口的基本结构
Nov 19 Python
Pytorch 中retain_graph的用法详解
Jan 07 Python
pyftplib中文乱码问题解决方案
Jan 11 Python
Python 解析pymysql模块操作数据库的方法
Feb 18 Python
Python object类中的特殊方法代码讲解
Mar 06 Python
自定义实现 PyQt5 下拉复选框 ComboCheckBox的完整代码
Mar 30 Python
详解pandas绘制矩阵散点图(scatter_matrix)的方法
Apr 23 Python
Python操作PostgreSql数据库的方法(基本的增删改查)
Dec 29 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
留言板翻页的实现详解
2006/10/09 PHP
PHP 中的面向对象编程:通向大型 PHP 工程的办法
2006/12/03 PHP
php下实现一个阿拉伯数字转中文数字的函数
2008/07/10 PHP
基于magic_quotes_gpc与magic_quotes_runtime的区别与使用介绍
2013/04/22 PHP
php实现通过soap调用.Net的WebService asmx文件
2017/02/27 PHP
JavaScript实现QueryString获取GET参数的方法
2013/07/02 Javascript
鼠标拖动实现DIV排序示例代码
2013/10/14 Javascript
理解JS绑定事件
2016/01/19 Javascript
Javascript中的数组常用方法解析
2016/06/17 Javascript
微信小程序 开发指南详解
2016/09/27 Javascript
ros::spin() 和 ros::spinOnce()函数的区别及详解
2016/10/01 Javascript
jquery插件bootstrapValidator数据验证详解
2016/11/09 Javascript
Angular2 http jsonp的实例详解
2017/08/31 Javascript
微信小程序使用npm支持踩坑
2018/11/07 Javascript
[00:36]我的中国心——Serenity vs Fnatic
2018/08/21 DOTA
比较详细Python正则表达式操作指南(re使用)
2008/09/06 Python
python多线程编程方式分析示例详解
2013/12/06 Python
vscode 远程调试python的方法
2017/12/01 Python
python3.5+tesseract+adb实现西瓜视频或头脑王者辅助答题
2018/01/17 Python
python中pygame安装过程(超级详细)
2019/08/04 Python
Python判断字符串是否为合法标示符操作
2020/09/03 Python
python使用Windows的wmic命令监控文件运行状况,如有异常发送邮件报警
2021/01/30 Python
Debenhams爱尔兰:英国知名的百货公司
2017/01/02 全球购物
英国计算机商店:Technextday
2019/12/28 全球购物
希腊品牌鞋类销售网站:epapoutsia.gr
2020/03/18 全球购物
mysql的最长数据库名,表名,字段名可以是多长
2014/04/21 面试题
如何执行一个shell程序
2012/11/23 面试题
班长自荐书范文
2014/02/11 职场文书
小学教师自我鉴定范文
2014/03/20 职场文书
团委竞选演讲稿
2014/04/24 职场文书
治超工作实施方案
2014/05/04 职场文书
销售提升方案
2014/06/07 职场文书
庆元旦主持词
2015/07/06 职场文书
SQL Server——索引+基于单表的数据插入与简单查询【1】
2021/04/05 SQL Server
使用Html+Css实现简易导航栏功能(导航栏遇到鼠标切换背景颜色)
2021/04/07 HTML / CSS
Python装饰器的练习题
2021/11/23 Python