Ansible的Inventory管理
Ansible将可管理的服务器集合成为Inventory,Inventory的管理便是服务器的管理。
hosts文件的位置:
- /etc/ansible/hosts
- 在命令行通过-i参数指定
- 通过/etc/ansible/ansible.cfg中的Inventory参数指定
另外Ansible还支持从云服务器获取服务器列表,还可以从CMDB获取服务器列表,
列出服务器 --list-hosts
[root@zydev01 ~]# ansible all --list-hosts
hosts (3):
192.168.1.105
120.77.85.77
192.168.1.101
单独为主机定义参数
[dbsrvs] 10.10.1.101 mysql_port=3306 10.10.1.102 mysql_port=3307
组中组,和组参数
加上children的方式声明组中包含其它组
[atlanta] host1 host2 [raleigh] host2 host3 [southeast:children] atlanta raleigh [southeast:vars] #定义组的主机的参数
ansible_port=3235 some_server=foo.southeast.example.com halon_system_timeout=30 self_destruct_countdown=60 escape_pods=2
mysql_port=3307
Inventory的参数分为行为参数(ansible默认的,如ansible_port)和自定义变量(mysql_port)
打印参数:

一些重要的行为参数:
- ansible_host SSH目的主机名或者IP
- ansible_port
- ansible_user SSH连接的用户名,默认当前用户
- ansible_ssh_pass
- ansible_ssh_private_key_file
- ansible_become 类似Linux的sudo
- ansible_become_user 切换到哪个用户下执行命令
使用正则表达式定义组和匹配组
定义组
[webservers] www[01:50].example.com
[databases]
db-[a:f].example.com
匹配组
ansible web* -m ping
使用单独的目录管理服务器和群组的变量
如果服务器特变多,还用一个hosts管理服务器和变量将会很困难。
Ansible可以为每个服务器和群组创建独立的变量文件。
Ansible将依次从Playbook目录下,hosts文件所在目录和/etc/ansible目录下寻找group_varls和host_varsx下寻找变量文件。

192.168.1.106.yaml的内容如下:

需要注意的是hosts定义ini的格式,即“var = value”,使用独立的文件是“var:value”
通过CMDB方式获取动态获取资产
一个动态获取资产的脚本必须支持两个命令行参数
--host=<hostname> : 用于列出某台服务器的详细信息
--list: 用于列出群组及群组中的服务器
返回的格式必须是json格式的
获取资产的脚本
hostlist.py
#!/usr/bin/env python
import argparse
import json
import sys
import requests
def to_json(in_dict):
return json.dumps(in_dict, sort_keys=True, indent=2)
def parse_args():
parser = argparse.ArgumentParser(description='Ansible Dynamic Inventory')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', action='store_true',
help='List active servers')
group.add_argument('--host', help='List details about the specific host')
return parser.parse_args()
def get_host_groups():
rep = requests.get('http://192.168.0.81:5000/api/cmdb/inventory/all')
return rep.text
def get_host_detail(host):
rep = requests.get(f'http://192.168.0.81:5000/api/cmdb/inventory/{host}')
return rep.text
def main():
args = parse_args()
if args.list:
output = get_host_groups()
elif args.host:
output = get_host_detail(args.host)
print(output)
sys.exit(0)
if __name__ == '__main__':
main()
测试
[root@center ansible]# python hostlist.py --list
{
"oracle": [
"192.168.0.21",
"192.168.0.32"
],
"weblogic": [
"192.168.0.31",
"192.168.0.99"
]
}
[root@center ansible]# python hostlist.py --host=192.168.0.31
{
"ansible_host": "192.168.0.31",
"ansible_port": "22",
"ansible_user": "root"
}
[root@center ansible]# ansible oracle -i hostlist.py -a 'whoami'
192.168.0.21 | CHANGED | rc=0 >>
root
192.168.0.32 | CHANGED | rc=0 >>
root

浙公网安备 33010602011771号