ansible - 如何在 Ansible 中将多行字符串转换为 dict?
问题描述
我在 Ansible 中使用环境变量设置了一个事实query('env', 'VARIABLE')
MyVARIABLE
是多行字符串(YAML 格式):
device: eth0
bootproto: static
address: 192.168.x.x
netmask: 255.255.255.0
gateway: 192.168.x.x
当我VARIABLE
用 Ansible 打印时,我把它作为一个字符串,在行\n
之间
"msg": ["device: eth0\nbootproto: static\naddress:
192.168.x.x\nnetmask: 255.255.255.0\ngateway: 192.168.x.x"]
有没有方便的方法将其转换为dict?我需要稍后在我的任务中使用它,在配置机器的 NIC 时加载参数。
我尝试使用 Jinja2 过滤器- debug: msg="{{ network_settings | from_yaml }}"
但没有成功。
解决方案
文档中有一个重要说明:
lookup
和之间的区别query
主要在于query
总是返回一个列表。
所以:
要么替换
query('env', 'VARIABLE')
为lookup('env', 'VARIABLE')
:- debug: msg: "{{ lookup('env', 'VARIABLE') | from_yaml }}"
或相应地处理列表(内容将在第一个也是唯一的元素中):
- debug: msg: "{{ query('env', 'VARIABLE') | first | from_yaml }}"
推荐阅读
- build - Buildroot 不会重新构建修改过的文件
- css - 如何扩展网格的兄弟元素?
- latex - LaTex 字数统计,同时包括某些包
- javascript - 我正在为 node.js 使用 ES6 语法,并且我已经导出了模块,但尝试导入时出现错误找不到模块
- vue.js - vue 3 main.js 添加aos库问题
- zoom-sdk - 为什么 Zoom websdk 在 FF 上不起作用?有解决方法吗?
- python - 来自 S3 存储桶的 Fastai 输入图像
- java - 当我将一些 java 代码从另一个在线 IDE 复制到 Visual Studio 代码时,它显示“未解决的编译错误”
- python - 错误 ValueError: y 应该是一维数组,取而代之的是一个形状为 (1, 4) 的数组。使用 RASA 解释器解析文本时
- android - Android / IOS 单个应用程序可以同时具有订阅和完整购买方式吗?