歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux綜合 >> 學習Linux >> 《Ansible權威指南》筆記(2)——Inventory配置,ansible權威指南

《Ansible權威指南》筆記(2)——Inventory配置,ansible權威指南

日期:2017/3/3 17:59:34   编辑:學習Linux

《Ansible權威指南》筆記(2)——Inventory配置,ansible權威指南

《Ansible權威指南》筆記(2)——Inventory配置,ansible權威指南


四、Inventory配置
ansible通過Inventory來定義主機和組,使用時通過-i指定讀取,默認/etc/ansible/hosts。可以存在多個Inventory,支持動態生成。
1、定義主機和組
# vim /etc/ansible/hosts
192.168.12.22 #可以直接為IP地址
nfs.magedu.com #可以是域名
ntp.magedu.com:2200 #可以:接ssh端口

[webserver] #[]內為分組名,下面都是該組組員
web[1:10].magedu.com #[1:10]表示1~10所有數字
db-[a:f].magedu.com #[a:f]表示a~f所有字母

2、定義主機變量
定義的變量可以在playbook中使用,在playbook中設定的同名變量會優先於此處變量。
other1.example.com ansible_connection=ssh ansible_ssh_user=mpdehaan #選擇連接類型和連接用戶
other2.example.com http_port=8800 #定義http_port端口號8800

3、定義組變量
[test]
web1.example.com
web2.example.com

[test:vars] #組變量,下面定義的變量test組內的所有主機通用
ntp_server=ntp.example.com
proxy=proxy.example.com

4、把一個組作為另一個組的子成員
[apache]
web1.example.com
[nginx]
web2.example.com
[webserver]
other1.example.com
[webserver:children]
apache
nginx
#上例中webserver包括web1.example.com、web2.example.com、other1.example.com

5、其他Inventory參數
ansible_ssh_host
將要連接的遠程主機名.與你想要設定的主機的別名不同的話,可通過此變量設置.

ansible_ssh_port
ssh端口號.如果不是默認的端口號,通過此變量設置.

ansible_ssh_user
默認的 ssh 用戶名

ansible_ssh_pass
ssh 密碼(這種方式並不安全,我們強烈建議使用 --ask-pass 或 SSH 密鑰)

ansible_sudo_pass
sudo 密碼(這種方式並不安全,我們強烈建議使用 --ask-sudo-pass)

ansible_sudo_exe (new in version 1.8)
sudo 命令路徑(適用於1.8及以上版本)

ansible_connection
與主機的連接類型.比如:local, ssh 或者 paramiko. Ansible 1.2 以前默認使用 paramiko.1.2 以後默認使用 'smart','smart' 方式會根據是否支持 ControlPersist, 來判斷'ssh' 方式是否可行.

ansible_ssh_private_key_file
ssh 使用的私鑰文件.適用於有多個密鑰,而你不想使用 SSH 代理的情況.

ansible_shell_type
目標系統的shell類型.默認情況下,命令的執行使用 'sh' 語法,可設置為 'csh' 或 'fish'.

ansible_python_interpreter
目標主機的 python 路徑.適用於的情況: 系統中有多個 Python, 或者命令路徑不是"/usr/bin/python",比如 \*BSD, 或者 /usr/bin/python
不是 2.X 版本的 Python.我們不使用 "/usr/bin/env" 機制,因為這要求遠程用戶的路徑設置正確,且要求 "python" 可執行程序名不可為 python以外的名字(實際有可能名為python26).

與 ansible_python_interpreter 的工作方式相同,可設定如 ruby 或 perl 的路徑....

6、變量讀取的四個位置
Inventory配置
Playbook中vars定義的區域
Roles中vars目錄下的文件
Roles同級目錄group_vars和hosts_vars目錄下的文件
#設置變量時盡量沿用同一種方式。

7、ansible正則
(1)全量匹配 all與*功能相同,但*需引起來。
ansible all -m ping
ansible "*" -m ping

(2)邏輯或(or)匹配
多台主機或多個組同時執行
ansible "web1:web2" -m ping

(3)邏輯非(!)匹配
所有在web1組,但不在web2組的主機
web1:!web2

(4)邏輯與(&)匹配
web1和web2中同時存在的主機
web1:&web2

(5)模糊匹配
檢查192.168.1.0/24網段所有主機存活狀態。
ansible 192.168.1.* -m ping
test開頭的所有組
ansible "test*" -m ping

(6)域切割,同python字符串域切割
例:
[webservers]
web1.example.com
web2.example.com
web3.example.com

webservers[0] #==web1.example.com
webservers[-1] #==web3.example.com
webservers[0:2] #第一位到第三位==web1.example.com、web2.example.com、web3.example.com
webservers[1:] #第二位到最後==web2.example.com、web3.example.com

(7)正則匹配,"~"開始表示正則匹配
ansible "~(web|data|test)\.example\.(com|org)" -m ping

http://xxxxxx/Linuxjc/1182078.html TechArticle

Copyright © Linux教程網 All Rights Reserved