ansible任务委托
  r5GSNpWCXO1K 2023年11月02日 61 0

一、概述

默认情况下,ansible的所有任务都是在指定的机器上运行的。当在一个独立的群集环境中配置时,只是想操作其中的某一台主机,或者在特
定的主机上运行task任务,此时就需要用到ansible的任务委托功能

二、参数

1、委托delegate_to

使用delegate_to关键字可以配置task任务在指定的机器上执行
就是说其他的task任务还是在hosts关键字配置的机器上运行,到了这个关键字所在的任务时,就使用委托的机器运行。

1、delegate_to
ansible可以把某一个task任务放在委托的机器上执行。即在指定的组内的某一台或多台机器上执行task任务。
- hosts : test_server
serial: 10
tasks :
- name: test-haha
shell: echo "test" > /root/test.list
delegate_to: 172.16.60.245
#则上面的shell模块的task任务只会在172.16.60.245这台节点上执行,
#test_server组内其他的机器不会执行shell任务。

3、多个delegate_to
#如果设置了多个delegate_to,则执行时只会匹配最下面那个。
#例如下面配置中,只会执行"delegate_to: 172.16.60.245",
#上面那个"delegate_to: 172.16.60.241"就会被忽略了。
- hosts : all
serial: 10
tasks :
- name: test-haha
shell: echo "test" > /root/test.list
delegate_to: 172.16.60.241
delegate_to: 172.16.60.245

4、多个ip委托
# delegate_to默认后面只能跟一个主机ip,不能跟多个主机ip。即默认委托到单个主机。
# 如果有多个ip需要委托,则可以将这些ip重新放一个group,然后delegate_to委托给group组。
# delegate_to委托到组的方式:通过items变量方式!!!
- hosts: all
tasks:
- name: test-haha
shell: echo "test" > /root/test.list
delegate_to: "{{item}}"
with_items: "{{groups['kevin_server']}}"
# 即将shell这个task任务委托给kevin_server组内的机器执行。

2、委托local_action和connection

1、local_action
#如果 "delegate_to: 127.0.0.1" 则可以用local_action来代替。即下面两个配置效果是一样的!!
- hosts : test_server
serial: 10
tasks :
- name: test-haha
shell: echo "test" > /root/test.list
delegate_to: 127.0.0.1 #也可以写成localhost

- hosts : test_server
serial: 10
tasks :
- name: test-haha
local_action: shell echo "test" > /root/test.list

2、connection
connection: local
- hosts : test_server
serial: 10
tasks :
- name: test-haha
shell: echo "test" > /root/test.list
connection: local

delegate_to和connection最后达到的目标是一致的,
补充: connection: local 可以针对playbook全局使用,而delegate_to: localhost 只能针对role task等局部代理

3、委托者的facts

#默认情况下, ansible委托任务的facts是inventory_hostname中主机的facts, 
#而不是被委托机器的facts。

1、delegate_facts
#在ansible 2.0 中, 通过设置"delegate_facts: True"可以让task任务去收集被委托机器的facts。
- hosts: test_server
tasks:
- name: test-haha
shell: echo "test" > /root/test.list
delegate_to: "{{item}}"
delegate_facts: True
with_items: "{{groups['kevin_server']}}"
#如上配置,表示会收集kevin_server的facts并分配给这些机器, 而不会去收集test_server的facts

4、执行一次run_once

1、RUN ONCE
#通过设置"run_once: true"来指定该task只能在委托的某一台机器或委托的组内机器上执行一次!!
#可以和delegate_to 结合使用。
#如果没有delegate_to, 那么这个task默认就会在第一台机器上执行!!!
- hosts: test_server
tasks:
- name: test-haha
shell: echo "test" > /root/test.list
delegate_to: "{{item}}"
run_once: true
delegate_facts: True
with_items: "{{groups['kevin_server']}}"
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论