Ansible组件之inventory主机清单

静态inventory

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

  a、中括号中的名字表明组名,能够根据本身的需求将庞大的主机分红具备标识的组。docker

  b、主机(host)部分可使用域名、主机名、IP地址表示;固然使用前二者时,也须要主机能反解析到相应的IP地址,通常此类配置中多使用IP地址。shell

定义主机和主机组

[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列表json

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

tree inventory/

inventory/
├── docker
└── hosts

如上所示,不一样的文件能够存放不一样的主机。ssh

  也能够在ansible命令的时候用-i参数指定该,目录便可;code

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定义值改为一个可执行脚本便可。ip

编写一个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脚本:utf-8

/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
相关文章
相关标签/搜索