Ansible 系列:html
- (一):快速上手 Ansible
- (二):Ansible 命令
- (三):Ansible 主機清單配置文件
- (四):Ansible Playbook 劇本語法
參考至官方文檔,官方文檔包含了清單文件的 YAML 寫法node
在經過 Ansible 操做目標主機以前,你須要先在 Inventory(主機清單)中配置目標主機信息。python
默認狀況下主機清單保存在系統的 /etc/ansible/hosts
文件中,你也能夠經過命令行選項指定其它的清單文件 -i <path>。nginx
主機清單配置默認格式爲 INI,下面是一個主機清單配置例子:web
[web]
www.abc.com1
192.168.0.2
複製代碼
上述配置中方括號爲組名,www.abc.com1 和 192.168.0.2 爲被監控主機的域名或 IP。也能夠是主機名,但此時須要指定主機 IP 環境變量 。redis
[web]
node ansible_host=192.0.2.50
複製代碼
默認採用密鑰認證,若是沒有密鑰認證,那麼你須要配置主機密碼環境變量。shell
[web]
www.abc.com1 ansible_user=root ansible_password=123456
複製代碼
你也能夠對指定組下的主機進行統一的環境變量配置:apache
[web]
www.abc.com1 ansible_user=root ansible_password=123456 http_port=8080
192.168.0.2 ansible_user=root ansible_password=123451
[web:vars]
http_port=80
ssh_port=22
redis_port=6379
複製代碼
若是主機名或 IP 是有序有規則的,你還能夠採用數字或字符範圍格式,而不是列出每一個主機名:tomcat
[webservers]
www[01:50].example.com
[databases]
db-[a:f].example.com
複製代碼
組還支持繼承(嵌套),其格式爲 組名+":children" 組成,以下:ruby
[shenzhen]
host1
host2
[guangzhou]
host3
host4
[guangdong:children]
shenzhen
guangzhou
[guangdong:vars]
tomcat=192.168.8.8
nginx=192.168.8.66
apache=192.168.8.77
zabbix=192.168.8.88
[china:children]
guangdong
beijing
shanghai
複製代碼
上面我指定了深圳組有 host一、host2,廣州組有host三、host4。廣東組包含深圳和廣州,同時爲該組內的全部主機指定了四個環境變量。後又設定了一箇中國組,包含廣東、北京、上海。
全部主機都屬於兩個隱式的組:
環境變量除了寫在主機清單文件中,還能夠單獨存儲在單個文件中。
咱們能夠在主機清單文件的同級目錄中建立兩個目錄 "group_vars" 和 "host_vars",分別存儲組變量與主機變量文件。
如咱們在主機清單文件中聲明瞭組 test,此時在 group_vars 目錄下建立一個名爲 test 的文件(該文件爲 YAML 格式),其內容以下:
tomcat: 192.168.8.8
複製代碼
此時 test 組中的主機將會包含 tomcat 這個環境變量。
當 "group_vars" 或 "host_vars" 外部環境變量文件與主機清單文件中的環境變量衝突時,前者優先級更高。
Ansible 定義了一些固定的環境變量名,這些環境變量將會影響 Ansible 的行爲。
ansible_connection #主機鏈接類型,這能夠是任何 ansible 鏈接插件的名稱,如 smart、ssh、paramiko、local
ansible_ssh_host # 將要鏈接的遠程主機名.與你想要設定的主機的別名不一樣的話,可經過此變量設置.
ansible_ssh_port # 鏈接端口號(默認22)
ansible_ssh_user # 鏈接主機時的用戶名
ansible_ssh_pass # 用於驗證主機的密碼
ansible_ssh_private_key_file # ssh 使用的私鑰文件.適用於有多個密鑰,而你不想使用 SSH 代理的狀況.
ansible_ssh_common_args # 此設置附加到 sftp,scp 和 ssh 的缺省命令行
ansible_sftp_extra_args # 此設置附加到默認 sftp 命令行
ansible_scp_extra_args # 此設置附加到默認 scp 命令行
ansible_ssh_extra_args # 此設置附加到默認 ssh 命令行
ansible_ssh_pipelining # 肯定是否使用 SSH 管道。 這能夠覆蓋 ansible.cfg 中得設置
ansible_shell_type # 目標系統的 shell 類型,默認狀況下命令的執行使用 'sh' 語法,可設置爲 'csh' 或 'fish'
ansible_python_interpreter # 目標主機的 python 路徑,適用於的狀況: 系統中有多個 Python, 或者命令路徑不是"/usr/bin/python",好比 *BSD, 或者 /usr/bin/python
ansible_interpreter # 這裏的""能夠是 ruby、perl 或其餘語言的解釋器,做用和ansible_python_interpreter 相似
ansible_shell_executable # 這將設置 ansible 控制器將在目標機器上使用的 shell,覆蓋 ansible.cfg 中的配置,默認爲 /bin/sh
複製代碼