我有2个节点有一个变量:
Node1:
setup: master
Node2:
setup: slave
有了任务,请在host_vars中设置变量:
---
- hosts: myhost
tasks:
- name: Copy file to master or slave
copy:
src: somesource
dest: /tmp/"{{ setup }}"
owner: root
group: root
mode: 0775
# failed_when: setup is undefined or both_nodes_have_"master"
如果出现以下情况,我该怎么办?
master
master
或slave
如果出现以下情况,我该如何才能继续执行任务:
master
,另一个节点设置了slave
答案 0 :(得分:4)
尝试计算它们:
清单:
master ansible_connection=local
slave ansible_connection=local
[master]
master
[slave]
slave
[myhost:children]
master
slave
[master:vars]
setup_type=master
[slave:vars]
setup_type=slave
剧本:
---
- hosts: myhost
gather_facts: yes
vars:
master_count: 0
slave_count: 0
tasks:
- name: Count master fields
set_fact:
master_count: "{{master_count | int + 1}}"
with_items:
- "{{ groups.myhost }}"
when: "hostvars[item]['setup_type'] is defined and hostvars[item]['setup_type'] == 'master'"
- name: Count slave fields
set_fact:
slave_count: "{{slave_count | int + 1}}"
with_items:
- "{{ groups.myhost }}"
when: "hostvars[item]['setup_type'] is defined and hostvars[item]['setup_type'] == 'slave'"
- name: Fail if invalid master number
debug:
msg: "Master count: {{master_count}}"
failed_when: "master_count | int != 1"
- name: Fail if invalid slave number
debug:
msg: "Slave count: {{slave_count}}. Required: {{groups.myhost | length - master_count | int}}"
failed_when: "slave_count | int + master_count | int != groups.myhost | length"
如果没有多个主设备,则会失败,如果没有足够的从设备,则会失败(这将检查您自动拥有多少主机并期望所有非主设备都是从设备)
如果您需要将其粘贴到解决方案中,则需要修改这些字符串:
setup_type
:是问题中的变量master
和slave
是我们正在检查的变量值myhost
是我们正在进行搜索的群组请注意,它们出现在多个地方,因此您应该对所有这些进行搜索和替换。此外,我认为所有这些都可以变得动态,这意味着您可以将其作为一个角色或单独的游戏提取,以便于重用