You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible中将注册变量以字典形式写入文件?

没问题!要把注册的变量以字典形式保存到文件,同时保证后续能通过字典键便捷访问,你可以按下面的步骤来实现:

解决方案

直接通过构建字典变量 + 写入格式化YAML文件两步就能达成需求,完整Playbook代码如下:

---
- name: Get variable1
  shell: "some java command"
  register: variable1

- name: Get variable2
  shell: "some java command"
  register: variable2

- name: Build target dictionary
  set_fact:
    dictionary_variable:
      var1: "{{ variable1 }}"
      var2: "{{ variable2 }}"

- name: Save dictionary to YAML file
  copy:
    content: "{{ {'dictionary_variable': dictionary_variable} | to_nice_yaml(indent=2) }}"
    dest: "/path/to/your/output_file.yml"
    mode: '0644'

关键部分解释:

  1. 构建字典:用set_fact模块创建dictionary_variable字典,直接把你注册的variable1和variable2分别映射到var1、var2键下,完全匹配你想要的结构。
  2. 写入文件:通过copy模块的content参数,搭配to_nice_yaml过滤器把字典转换成格式工整的YAML字符串(indent=2控制缩进,让文件更易读)。外层包裹的字典确保写入文件后的结构和你期望的完全一致。

后续访问方法:

如果需要在其他任务/Playbook中使用这个字典,只需用include_vars加载文件即可:

- name: Load saved dictionary
  include_vars:
    file: "/path/to/your/output_file.yml"
    name: loaded_dict

- name: Access specific variable from dictionary
  debug:
    msg: "Output of variable1: {{ loaded_dict.dictionary_variable.var1.stdout }}"

之后就能通过{{ loaded_dict.dictionary_variable.var1 }}(或直接{{ dictionary_variable.var1 }},如果加载时指定的name和字典名一致)访问对应变量内容了。

内容的提问来源于stack exchange,提问作者user3086551

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:17:55