Ansible笔记2--delegate_to指令

场景介绍

目前执行Ansible的过程中,遇到这么一个需求,在远程服务器上执行一系列操作,但是这个操作需要用到一组数据,该数据存在于Ansible服务器中的一个文件中,但是远程服务器无法读取到该文件,所以查到了这个指令,Ansible 的任务委派功能(delegate_to)。

使用 delegate_to 关键字可以委派任务到指定的机器上运行。

在 playbook 的操作如下:

1
2
3
4
5
6
7
8
## 读取指定的localhost上的文件并定义为变量
- name: read
read_csv:
path: "{{ csv_tmp_path }}"
delimiter: ','
register: file_list
changed_when: false
delegate_to: localhost

任务委派功能还可以用于以下场景:

  • 在部署之前将一个主机从一个负载均衡集群中删除;
  • 当你要对一个主机做改变之前去掉相应 dns 的记录;
  • 当在一个存储设备上创建 iscsi 卷的时候;
  • 当使用外的主机来检测网络出口是否正常的时候。

委托(delegate)

通过”delegate_to”, 用户可以把某一个任务放在委托的机器上执行.

1
2
3
4
5
6
7
hosts: webservers
serial: 5

tasks:
- name: take out of load balancer pool
command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
delegate_to: 127.0.0.1

无论定义了hosts是什么,上面的这个task都只会在localhost(即ansible运行的机器)上执行,

如果只是想在本地执行,“delegate_to: 127.0.0.1” 也可以用local_action来代替

1
2
3
4
tasks:
- name: take out of load balancer pool
local_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}

委托者的facts

默认情况下, 委托任务的facts是inventory_hostname中主机的facts, 而不是被委托机器的facts. 在ansible 2.0 中, 设置delegate_facts为true可以让任务去收集被委托机器的facts.

1
2
3
4
5
6
7
- hosts: app_servers
tasks:
- name: gather facts from db servers
setup:
delegate_to: "{{item}}"
delegate_facts: True
with_items: "{{groups['dbservers'}}"

该例子会收集dbservers的facts并分配给这些机器, 而不会去收集app_servers的facts

run_once

通过run_once: true来指定该task只能在某一台机器上执行一次. 可以和delegate_to 结合使用

1
2
3
- command: /opt/application/upgrade_db.py
run_once: true
delegate_to: web01.example.org

指定在”web01.example.org”上执行这个task

如果没有delegate_to, 那么这个task只会在当前主机组的第一台机器上执行