Ansible的hosts文件在/etc/ansible目錄下,在hosts中添加你須要管理的遠程主機的信息後,ansible才能夠順利的管理這些機器。shell
添加一臺機器:bash
[host1]
192.168.1.104
複製代碼
添加一個機器組:ui
[host2]
192.168.1.101
192.168.3.44
192.168.5.201
複製代碼
添加一臺帶參數的機器:spa
[host3]
192.168.5.67 ansible_sudo_pass='123'
複製代碼
ansible.cfg是Ansible的配置文件,保存在/etc/ansible目錄下。若是須要使用become進行權限切換,或者生成日誌等功能,就須要修改ansible.cfg中的設置。scala
設置切換用戶時詢問密碼:debug
[privilege_escalation]
#become=True
#become_method=sudo
#become_user=root
become_ask_pass=True
複製代碼
設置生成日誌:日誌
log_path = /etc/ansible/log/ansible.log
複製代碼
Playbook是yaml格式文件。code
---
- name: say 'hello world'
hosts: host1 #要執行playbook的機器或機器組,在hosts文件中設置
tasks:
- name: echo 'hello world' #Task的名稱
command: echo 'hello world' #Task執行的Module,除command外還能夠是shell,copy,apt等
register: result
- name: print stdout
debug:
msg: ""
複製代碼
ansible-playbook默認不顯示執行的輸出,若是須要獲取命令執行的結果,能夠使用如下方法。token
方法一:string
ansible-playbook -v test.yaml
複製代碼
使用"-v"參數使playbook輸出所有的運行結果,但這樣輸出會很是多,格式也比較亂。
方法二:
tasks:
-name: test
shell: echo "just test"
register: test_output
-name: show output
debug: var=test_output.stdout verbosity=0
複製代碼
使用register將命令的輸出結果保存爲變量,而後使用debug module將變量輸出。這種方法能夠方便的獲取命令的運行結果。
在使用become能夠在playbook切換用戶來執行命令。好比須要在root下執行某一個命令,就能夠使用become功能。
tasks:
-name: change to root user
become: yes
become_user: root
become_method: sudo
shell: echo "test"
複製代碼
關於become有幾個注意事項:
首先須要去slack中申請一個App,而後記下生成的token。在yaml文件中只須要加入下面一段代碼就能夠向slack發送信息。
- name: send notification to slack
slack:
token: 'AAAAAA/BBBBBBB/CCCCCCCC' #申請的App的token
msg: 'just test'
username: 'test_user'
delegate_to: localhost #指派給localhost執行這段代碼
複製代碼
delegate_to能夠將一個task分配給特定的主機執行,經過delegate_to能夠在一個playbook讓不一樣的機器執行不一樣的task。