环境
- 管理节点:CentOS Stream release 9
- 控制节点:同上
- Ansible:2.15.4
从文件读取yaml数据
假设目标机器上有文件 data.yml 内容如下:
a:
b: 111
c: 222
d.e: 333
现在要读取该文件内容,并转成yaml数据。
创建文件 test1.yml 如下:
---
- hosts: all
tasks:
- name: task1
shell: cat /root/temp1117/data.yml
register: result
- name: task2
set_fact:
data: "{{ result.stdout | from_yaml }}"
- name: task3
debug:
msg: "{{ data | type_debug }}"
- name: task4
debug:
msg: "{{ data.a }}"
- name: task5
debug:
msg: "{{ data.a.b }}"
运行结果如下:
......
TASK [task1] *************************************************************************************************************************************
changed: [127.0.0.1]
TASK [task2] *************************************************************************************************************************************
ok: [127.0.0.1]
TASK [task3] *************************************************************************************************************************************
ok: [127.0.0.1] => {
"msg": "dict"
}
TASK [task4] *************************************************************************************************************************************
ok: [127.0.0.1] => {
"msg": {
"b": 111,
"c": 222,
"d.e": 333
}
}
TASK [task5] *************************************************************************************************************************************
ok: [127.0.0.1] => {
"msg": "111"
}
......
读取文件内容后,用 from_yaml 将其转成yaml格式(其数据类型是 dict )。
然后就可以访问其内容了。本例中,通过 a 、 a.b 、 a.c 来访问数据。
key里包含圆点( . )
现在的问题是,要如何访问 d.e 这个key呢?用 a.d.e 会出错,因为这种方式表示 a 、 d 、 e 是三个层次。
......
- name: task 6
debug:
msg: "{{ data.a.d.e }}"
......
报错如下:
......
TASK [task 6] ************************************************************************************************************************************
fatal: [127.0.0.1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'd'. 'dict object' has no attribute 'd'\n\nThe error appears to be in '/root/temp1117/test1.yml': line 24, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: task 6\n ^ here\n"}
......
解决方法:不是用 a.d.e 的方式,而是用 a['d.e'] 的方式。
......
- name: task7
debug:
msg: "{{ data.a['d.e'] }}"
......
运行结果如下:
......
TASK [task7] *************************************************************************************************************************************
ok: [127.0.0.1] => {
"msg": "333"
}
......
其它
事实上, a[b] 也是python的用法。
创建文件 test.py 如下:
#!/bin/python3
data = {'a': {'b': 111, 'c': 222, 'd.e': 333}}
print(data['a']['b'])
print(data['a']['d.e'])
运行结果如下:
111
333
如果不喜欢 data['a']['d.e'] 这种方式,还可以用 get() 方法:
data.get('a').get('d.e')
本文介绍了如何在Ansible任务中通过`from_yaml`读取data.yml文件,并处理嵌套键d.e。使用`a[d.e]`而非`a.d.e`的方式解决了访问问题。同时提到了Python中类似操作的示例。

被折叠的 条评论
为什么被折叠?



