我的一个玩法是在集群中的组节点上运行,我根据特定条件设置一个变量,例如当节点在集群中成为主节点时将变量设置为“主节点”。
- name: Determine master node in the cluster
hosts: cluster
gather_facts: no
tasks:
- name: Get the Master node hostname
shell: <command>
register: host_info
set_fact:
master_node: {{ host_info.stdout }}
when: host_info has "master". #Sample when condition to understand
我需要从其他主机访问 host_info master_node 变量
- name: Add async standby node
hosts: new_node
become: yes
tasks:
- debug:
var: hostvars[item]['master_node']
loop: "{{ groups['cluster'] }}"
库存:
[cluster]
cluster_01
cluster_02
[new_node]
new_node_01
当我执行此操作时,调试任务显示
TASK [debug] *********************************************************************************************************************************************************************************
ok: [new_node_01] => (item=cluster_01) => {
"ansible_loop_var": "item",
"hostvars[item]['primary_node']": "cluster_01",
"item": "cluster_01"
}
ok: [new_node_01] => (item=cluster_02) => {
"ansible_loop_var": "item",
"hostvars[item]['primary_node']": "VARIABLE IS NOT DEFINED!",
"item": "cluster_02"
}
如何才能只访问定义的循环项?
我就这样用过,效果很好
- set_fact:
primary_host: "{{ hostvars[item]['master_node'] }}"
loop: "{{ groups['cluster'] }}"
when: hostvars[item]['master_node'] is defined
执行日志
ok: [new_node_01] => (item= cluster_01) => {
"ansible_facts": {
"primary_host": "cluster_01"
},
"ansible_loop_var": "item",
"changed": false,
"item": "cluster_01"
}
skipping: [new_node_01] => (item= cluster_02) => {
"ansible_loop_var": "item",
"changed": false,
"item": "cluster_02",
"skip_reason": "Conditional result was False"
}