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
相關文章
相關標籤/搜索