Ansible 跨节点共享变量:从一个 target node 取值赋给所有节点

Ansible 操作三个 node,其中有一个 pod(app_api_pod_name)运行在其中一个上。需要在 node1 上检查文件是否存在,再把结果共享给其他 node 使用——但 Ansible 的变量是按 host 隔离的,直接 register 会踩坑。本文记录问题和 hostvars 解法。

背景

Step 1 需要判断这个 pod 中是否存在一个文件,希望只在第一个 node1 上执行,这样其他的 node 都会 skip。

问题

但这样 skip 其他 node 的时候,仍然会进行赋值,导致最后 CA_exist 无法 register,除了 node1,其他 node 拿到 CA_exist 都是空值。

这就理解了:Ansible 的所有变量,包括常量和临时变量,都是按 node 区分和隔离的,不能共享。

解决方案

Step 2 用来解决这个问题,在其他 node 的变量组里把这个值赋上,关键取值 hostvars[groups['role_control'][0]].CA_exist.rc

1
2
3
4
5
6
7
8
9
10
11
12
13

- name: check if CA exist in app-api
become: yes
shell: "kubectl exec -it {{ app_api_pod_name.stdout_lines[0] }} cat /etc/pki/ca-trust/source/anchors/xxxca.pem -n xxxx"
ignore_errors: yes
register: CA_exist
when: "inventory_hostname == groups['role_control'][0] and app_api_pod_name is defined"

- name: set if need to copy CA
set_fact:
need_copy: "{{ hostvars[groups['role_control'][0]].CA_exist.rc }}"
when: "hostvars[groups['role_control'][0]].CA_exist is defined and hostvars[groups['role_control'][0]].CA_exist.rc == 1"

总结

需要跨 host 引用变量时,用 hostvars['主机名']hostvars[groups['组名'][0]] 显式取值,不能指望 register 的结果自动在所有 node 上可用。

Notice: 正常情况下,这里会有一个基于utteranc.es的留言系统,如果看不到,可能要想想办法才能看到。

Powered by Hexo and Hexo-theme-hiker

Copyright © 2012 - 2026 tiaobug.com All Rights Reserved.

鲁ICP备2024124237号-1