Ansible组件之inventory主机清单

静态inventory

  所有的主机信息都存放在Ansible的inventory组件里面,默认Ansible的inventory是一个静态的ini格式的文件/etc/ansible/hosts,当然还可以通过ANSIBLE_HOSTS环境变量指定或者运行ansible和ansible-playbook的时候用-i参数临时设置。

  a、中括号中的名字代表组名,可以根据自己的需求将庞大的主机分成具有标识的组。

  b、主机(host)部分可以使用域名、主机名、IP地址表示;当然使用前两者时,也需要主机能反解析到相应的IP地址,一般此类配置中多使用IP地址。

定义主机和主机组

[docker]
172.16.1.11
[docker:vars]
ansible_ssh_pass='123456'
[ansible:children]	
docker

inventory内置参数

ansible_ssh_host				# 要连接的主机名
ansible_ssh_port				# 端口号,默认22
ansible_ssh_user				# ssh连接时默认使用的用户名
ansible_ssh_pass				# ssh连接时的密码
ansible_sudo_pass				# 使用sudo连接用户时的密码
ansible_ssh_private_key_file	# 秘钥文件如果不想使用ssh-agent管理时可以使用此选项
ansible_shell_type				# shell类型,默认sh
ansible_connection				# SSH连接类型:local、ssh、paramiko在ansible 1.2之前默认paramiko
ansible_python_interpreter		# 用来指定Python解释器的路径,同样可以指定ruby、Perl的路径

多个inventory列表

  配置支持多个inventory列表

  首先需要在Ansible的配置文件ansible.cfg中hosts的定义改成一个目录,比如:hostfile = /etc/ansible/inventory,然后在该目录中放入多个hosts文件。

tree inventory/

inventory/
├── docker
└── hosts

如上所示,不同的文件可以存放不同的主机。

  也可以在ansible命令的时候用-i参数指定该,目录即可;

ansible -i /etc/ansible/inventory all -a "who"

172.16.1.10 | SUCCESS | rc=0 >>
root     tty1         2018-04-07 02:19
root     pts/0        2018-04-06 18:50 (10.0.0.253)
root     pts/1        2018-04-06 22:30 (172.16.1.5)

172.16.1.11 | SUCCESS | rc=0 >>
root     tty1         2018-04-07 02:21
root     pts/0        2018-04-06 18:50 (10.0.0.253)
root     pts/1        2018-04-06 22:30 (172.16.1.5)	

动态inventory

  动态inventory的意思就是所有的变量可以从外部获取,也就是说我们可以从CMDB一级zabbix系统拉取所有的主机信息然后使用Ansible进行管理。易用inventory只需要把ansible.cfg文件中的inventory定义值改成一个可执行脚本即可。

编写一个inventory.py文件动态获取主机信息

#!/usr/bin/env python
# coding=utf-8
import json
ip1 = ["172.16.1.10"]	
ip2 = ["172.16.1.11"]
g1= "test1"
g2 = "test2"
hostdata = {g1:{"hosts":ip1},g2:{"hosts":ip2}}
print json.dumps(hostdata,indent=4)

  运行该python脚本:

/usr/bin/python inventory.py 

{
    "test1": {
        "hosts": [
            "172.16.1.10"
        ]
    }, 
    "test2": {
        "hosts": [
            "172.16.1.11"
        ]
    }
}

  该脚本必须要有可执行权限才可以被ansible命令调用:

chmod +x inventory.py

  运行ansible命令并调用该python脚本:

ansible -i inventory.py all -a "date" -k

SSH password: 
172.16.1.11 | SUCCESS | rc=0 >>
Sat Apr  7 01:04:12 CST 2018

172.16.1.10 | SUCCESS | rc=0 >>
Sat Apr  7 01:04:12 CST 2018
posted @ 2019-01-19 20:43  StaryJie  阅读(3170)  评论(0编辑  收藏  举报