Ansible使用不同inventory的playbook之间如何动态共享变量?
Ansible 跨不同inventory的playbook共享变量方案
方案1:本地临时变量文件存储(最常用,稳定性最高)
直接把第一个playbook生成的动态变量写入本地yaml/json文件,第二个playbook直接导入读取即可:
- 在
create_infrastructure.yml中添加任务,将获取到的控制平面IP写入本地文件:
- name: 导出基础设施生成的动态变量 hosts: infrastructure tasks: # 此处省略你原有获取control_plane_ip的逻辑 - name: 保存控制平面负载均衡IP到本地变量文件 ansible.builtin.copy: content: | # 自动生成的基础设施动态变量,请勿手动修改 control_plane_ip: {{ control_plane_ip }} dest: ./runtime_vars/infra_output.yml mode: '0600' delegate_to: localhost
- 在
bootstrap_cluster.yml中直接导入该变量文件即可直接使用变量:
- name: 引导Kubernetes集群 hosts: all vars_files: - ./runtime_vars/infra_output.yml tasks: # 业务逻辑中直接使用 {{ control_plane_ip }} 即可调用该值
注意:需要提前创建runtime_vars目录,同时在.gitignore中添加该目录,避免敏感配置提交到代码仓库
方案2:开启Ansible事实缓存
通过Ansible内置的事实缓存能力持久化存储变量,不需要手动维护文件:
- 先修改
ansible.cfg开启事实缓存:
[defaults]
fact_caching = jsonfile
fact_caching_connection = ./ansible_cache
fact_caching_timeout = 86400
- 在
create_infrastructure.yml中存储变量时添加cacheable参数:
- name: 缓存控制平面IP到全局事实缓存 ansible.builtin.set_fact: control_plane_ip: {{ control_plane_ip }} cacheable: yes
- 在
bootstrap_cluster.yml中直接读取localhost名下的缓存变量即可:
control_plane_ip: "{{ hostvars['localhost']['control_plane_ip'] }}"
注意:每次重新执行基础设施构建前需要清空缓存目录,避免读取到旧的历史值
方案3:环境变量传递(适合少量简单变量场景)
将变量写入环境变量文件,执行第二个playbook前加载环境变量即可:
create_infrastructure.yml中写入变量到.env文件:
- name: 写入IP到环境变量文件 ansible.builtin.lineinfile: path: ./.env line: "CONTROL_PLANE_IP={{ control_plane_ip }}" create: yes mode: '0600' delegate_to: localhost
- 执行第二个playbook前先加载环境变量:
source .env && ansible-playbook -i hcloud.yml bootstrap_cluster.yml
- 在第二个playbook中通过lookup读取环境变量:
control_plane_ip: "{{ lookup('env', 'CONTROL_PLANE_IP') }}"
内容的提问来源于stack exchange,提问作者MFranc
相关产品推荐
相关产品推荐

