ansible 的任務委派功能(delegate_to)

今天遇到這樣一個需求:在對A服務器執行一個操作任務的時候,同時也要把該操作任務在B服務器執行,如在A服務器添加一條hosts 記錄: 1.1.1.1 abc.com 。這個必須是要在一個 playbook 完成,而且B服務器只需要執行這一個操作任務,其它操作任務不需要執行。也就是A服務器這一個操作任務與B服務器有依賴關係。

一開始這個需求可能通過ansible 是完成不了,但是在查閱了 ansible 文檔後,發現ansible的任務委派(delegate_to)功能可以很好的完成這一要求。先看看ansible 官網文檔對任務委派功能的描述:

Delegation

New in version 0.7.

This isn’t actually rolling update specific but comes up frequently in those cases.

If you want to perform a task on one host with reference to other hosts, use the ‘delegate_to’ keyword on a task. This is ideal for placing nodes in a load balanced pool, or removing them. It is also very useful for controlling outage windows. Using this with the ‘serial’ keyword to control the number of hosts executing at one time is also a good idea:


Ansible默認在配置的機器上執行任務,當你有一大票機器需要配置或則每個設備都可達的情況下很有用。但是,當你需要在另外一個Ansible控制機器上運行任務的時候,就需要用到任務委派了。

使用delegate_to關鍵字就可以委派任務到其他機器上運行,同時可用的fact也會使用委派機器上的值。下面的例子使用get_url到所有web服務器上下載配置:

---
- name: Fetch configuration from all webservers
hosts: webservers


tasks:
- name: Get config
get_url: dest=configs/` ansible_hostname ` force=yes url=http://` ansible_hostname `/diagnostic/config
delegate_to: localhost

當你委派給本機的時候,還可以使用更快捷的方法local_action,代碼如下:

---
- name: Fetch configuration from all webservers
hosts: webservers


tasks:
- name: Get config
local_action: get_url dest=configs/` ansible_hostname`.cfg url=http://` ansible_hostname`/diagnostic/config
你可以委派任務給設備清單上的任意機器,下面是使用任務委派的一些場景:

  • 在部署之前將一個主機從一個負載均衡集羣中刪除

  • 當你要對一個主機做改變之前去掉相應dns的記錄

  • 當在一個存儲設備上創建iscsi卷的時候

  • 當使用外部的主機來檢測網絡出口是否正常的時候




下面描述下我的場景,如我要在192.168.1.1 服務器添加一個hosts 記錄 "1.1.1.1 www.abc.com" ,同時也要把這個hosts 記錄寫到192.168.1.2

ansible hosts 192.168.1.1 文件內容

[all]

192.168.1.1


ansible task 文件內容(192.168.1.1.yml):

---

- name: add host record
shell: "echo "1.1.1.1 www.abc.com" >> /etc/hosts"


- name: add host record
shell: "echo "1.1.1.1 www.abc.com" >> /etc/hosts"
delegate_to: 192.168.1.2

# 添加上面這一行,就可以了


執行playbook

ansible-playbook -i 192.168.1.1.host 192.168.1.1.yml


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章