ansible - 在特定主机上执行 ansible 任务
问题描述
我有一组主机:
[hosts]
host1
host2
host3
我想只在一个给定的主机上运行一些脚本(实际上并不重要),然后在第二个任务中,运行另一个脚本,但只在剩下的两个主机上运行,前一个任务没有执行。
- name: Task to be run on any host from given group of host
shell: sth
.
.
- name: Task to be run on the other 2 hosts from the same group
shell: sth else
.
.
我知道它可以实现,例如。使用serial
,虽然没有其他想法。将不胜感激任何帮助!
解决方案
还有更多选择。
- 运行一次块中的第一个任务并将inventory_hostname 放入一个变量中。在没有第一个主机的情况下运行循环中的下一个任务。例如
- name: Play1
hosts: all
gather_facts: false
tasks:
- block:
- name: Task to be run on any host from given group of host
command: echo {{ inventory_hostname }}
register: result_first
- set_fact:
first_host: "{{ inventory_hostname }}"
run_once: true
- name: Task to be run on the other 2 hosts from the same group
command: echo {{ item }}
register: result_others
loop: "{{ groups.all|difference([first_host]) }}"
delegate_to: "{{ item }}"
run_once: true
- debug:
msg:
- "{{ result_first.stdout }}"
- "{{ result_others.results|map(attribute='stdout')|list }}"
run_once: true
给
ok: [host1] =>
msg:
- host1
- - host2
- host3
- 下一个选项是创建一组没有第一个主机的主机。这种方法不需要委托。例如
- name: Play2
hosts: all
gather_facts: false
tasks:
- block:
- name: Task to be run on any host from given group of host
command: echo {{ inventory_hostname }}
register: result_first
- set_fact:
first_host: "{{ inventory_hostname }}"
- add_host:
name: "{{ item }}"
groups: my_group_without_first_host
result_first: "{{ result_first }}"
loop: "{{ groups.all|difference([first_host]) }}"
run_once: true
- hosts: my_group_without_first_host
gather_facts: false
tasks:
- name: Task to be run on the other 2 hosts from the same group
command: echo {{ inventory_hostname }}
register: result_others
- debug:
msg:
- "{{ result_first.stdout }}"
- "{{ result_others.stdout }}"
给
ok: [host2] =>
msg:
- host1
- host2
ok: [host3] =>
msg:
- host1
- host3
推荐阅读
- tsql - 从单个表插入到具有自动 id FK 的多个表中
- python - 用python获取oracle函数的返回值
- javascript - 通过使用文件中的“日期”重命名“.txt”文件的批处理脚本
- php - Laravel 5 中相关产品数量的产品类别列表
- angular - 父组件的选择值改变时如何重新加载子组件
- python - 如何比较具有相同数量元素的多个列表
- c# - 从视频中创建 Dicom 文件
- php - Laravel "logging.php" - 了解它是如何使用的
- python - Beautiful Soup KeyError:返回 self.attrs[key],但保留发生错误之前(和之后)的值
- windows - 比较文件夹中的文件并删除不存在的文件 - 第 2 部分