Ansible Inventory进阶指南
金蝶云社区-艾贺521
艾贺521
15人赞赏了该文章 827次浏览 未经作者许可,禁止转载编辑于2018年10月29日 15:48:39

Ansible的inventory文件定义了它要操作的一些主机,它可以通过inventory对这些主机进行操控。默认的inventory文件是/etc/ansible/hosts 。也可通过-i选项,来指定不同的inventory文件。




Ansible也支持从云中拉取inventory文件执行,拉取的文件可以试`YMAL,ini,etc`等格式。 这个是在ansbible 的 2.4版本新引入的功能,Ansible也有inventory的插件来让inventory变的更灵活和自定义化。




inventory的格式一般如下:


```

mail.example.com


[webservers]

foo.example.com

bar.example.com


[dbservers]

one.example.com

two.example.com

three.example.com

```




关于inventory的详细描述,参考我早期参与的翻译项目,[Ansible 中文权威](https://ansible-tran.readthedocs.io/en/latest/docs/intro_inventory.html)




动态inventory


静态 Inventory 指的是在文件中指定的主机和组,动态 Inventory 指通过外部脚本获取主机列表,并按照 ansible 所要求的格式返回给 ansilbe 命令的。这部分一般会结合 CMDB 资管系统、云计算平台等获取主机信息。


看到一段很不错的代码,参考下。




```

#!/usr/bin/python

#!/Users/aihe/.pyenv/shims/python

#coding : utf-8


import json

import sys


def group():

    host1 = ['192.168.0.112']

    host2 = ['192.168.0.112','192.168.0.109']

    group1 = 'test1'

    group2 = 'test2'

    hostdata = {

        group1:{"hosts":host1},

        group2:{"hosts":host2}

    }

    print(json.dumps(hostdata,indent=4))


def host(ip):

    info_dict = {

        "192.168.0.112": {

            "ansible_ssh_host":"192.168.0.112",

            "ansible_ssh_port":22,

            "ansible_ssh_user":"root",

            "ansible_ssh_pass":"123457"

        },

        "192.168.0.109": {

            "ansible_ssh_host":"192.168.0.109",

            "ansible_ssh_port":22,

            "ansible_ssh_user":"root",

            "ansible_ssh_pass":"xxxx"

        }

    }

    # 判断key是否在字典中,在的话打印出来,不在的话打印空字典。

    if ip in info_dict:

        print(json.dumps(info_dict[ip],indent=4))

    else:

        print(json.dumps({},indent=4))


if len(sys.argv) == 2 and (sys.argv[1] == '--list'):

    group()

elif len(sys.argv) == 3 and (sys.argv[1] == '--host'):

    host(sys.argv[2])

else:

    print("Usage: %s --list or --host <hostname>" % sys.argv[0])

    sys.exit(1)

```




1. 单独执行的时候

![image.png](https://upload-images.jianshu.io/upload_images/426671-08ff116de7adf8a5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


2. 结合Ansible执行。虽然连接报错误了,但是这因为主机是随便定义的,如果是可以连接的主机则是正常工作的。

![image.png](https://upload-images.jianshu.io/upload_images/426671-8472ff6fc645e872.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)




到这里,其实我们的动态inventory大体框架已经出来了,剩下的则是将代码中的硬编码变为动态获取,数据库或其它持久存储的地方获取即可。



### 问题

在写这段代码的时候遇到几个问题,很有意思,解决问题的过程就是让我们成长的过程...

另外报的错误实在也是有点迷惑人啊。


##### inventory插件问题

1. 错误截图,看到因为ini的插件无法解析json数据

![image.png](https://upload-images.jianshu.io/upload_images/426671-58e505e58392b684.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


查看所有可用的插件列表

```

ansible-doc -t inventory -l

```

![image.png](https://upload-images.jianshu.io/upload_images/426671-885b7a5c4bacf17c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


2. 更改ansible的inventory可用插件。启用Ansible插件的配置在/etc/ansible/ansible.cfg文件中,具体是那个文件在起作用,执行执行`ansible --version`命令就可以看到。

![image.png](https://upload-images.jianshu.io/upload_images/426671-4082a2ff87882a44.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


修改插件的位置在。

![image.png](https://upload-images.jianshu.io/upload_images/426671-e705a2a4fefdeaf9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)



##### 执行格式问题

错误中还有关于执行格式错误的信息。


![image.png](https://upload-images.jianshu.io/upload_images/426671-04e06c7507f80e56.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


1. 错误原因

刚开始一直报执行格式错误问题,这个问题有点荒唐,因为我安装了pyenv,python执行的路径在开头写成了



```

#!/Users/aihe/.pyenv/shims/python

```


而这个文件是sh文件,普通的可执行文本文件了,导致出错,晕掉...


2. 解决方案


将开头的#!修改为python的解释器。然后就执行成功了。


```

#!/usr/bin/python

```




### 最后


要知道inventory的格式,inventory在ansible中可以理解为主机清单。动态的inventory可以给我们提供很多便利的操作,我们可以更灵活的控制主机了。




如果你的数据格式,在已有的inventory插件中,你也可以自己尝试开发一个,具体开发参考下面的参考部分。




### 参考


- [Ansible 进阶 | 动态 Inventory](https://hoxis.github.io/ansible-dynamic-inventory.html)

- [开发Ansible inventory](<https://docs.ansible.com/ansible/2.7/dev_guide/developing_inventory.html#developing-an-inventory-plugin>)

赞 15