将curl命令生成的字典转换为项目列表 - Ansible
使用ansible playbook和查找插件,如何将具有字典格式key: value
的“curl https://ifconfig.io/all
”的结果转换为item列表
country_code: US
encoding: gzip
forwarded: 29.493.593.012
host: XXX.XXX.X53.2XX
ifconfig_hostname: ifconfig.io
ip: XXX.XXX.X53.2XX
lang: ""
method: GET
mime: '/'
port: 27404
referer: ""
ua: Python-urllib/3.6
所需的输出:项目列表采用这种格式:
[
{
"key": "country_code",
"value": "US"
},
{
"key": "encoding",
"value": "gzip"
},
{
"key": "forwarded",
"value": "29.493.593.012"
},
{
"key": "host",
"value": "XXX.XXX.X53.2XX"
},
{
"key": "ifconfig_hostname",
"value": "ifconfig.io"
},
{
"key": "ip",
"value": "XXX.XXX.X53.2XX"
},
{
"key": "lang",
"value": "''"
},
{
"key": "method",
"value": "GET"
},
{
"key": "mime",
"value": "''"
},
{
"key": "port",
"value": "28180"
},
{
"key": "referer",
"value": "''"
},
{
"key": "ua",
"value": "Python-urllib/3.6"
}
]
我使用的脚本是:
- name: Get url contents
vars:
curl_res: "{{ query('url','https://ifconfig.io/all') }}"
debug:
msg: "{{ item }}"
loop: "{{ curl_res | dict2items }}"
但是我遇到了这个错误:
TASK [Get url contents] *****************************************************************************************************************
fatal: [servera]: FAILED! => {"msg": "Unexpected templating type error occurred on ({{ curl_res | dict2items }}): dict2items requires a dictionary, got <class 'list'> instead."}
所以,我手动制作了它,将curl结果保存在本地文件中,然后将其微调为以下格式:
<代码>cat 文件/curl_result
{
"country_code": "US",
"encoding": "gzip",
"forwarded": "29.493.593.012",
"host": "XXX.XXX.X53.2XX",
"ifconfig_hostname": "ifconfig.io",
"ip": "XXX.XXX.X53.2XX",
"lang": "''",
"method": "GET",
"mime": "''",
"port": "28580",
"referer": "''",
"ua": "Python-urllib/3.6"
}
然后,我在我的游戏中运行了这个任务:
- name: extract from file
vars:
items_curl_res: "{{ lookup('file', 'curl_result') | from_json | dict2items }}"
debug:
var: items_curl_res
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您获得的返回不是字典,而是表格中的字符串列表
键:value
。该表格实际上是有效的YAML格式,因此您可以使用地图 应用
from_yaml
过滤到所有这些字符串,然后,map
再次adict2items
,最后,flatten
列表列表。
最终以此为taks:
此任务将产生:
The return you are getting is not a dictionary, but a list of string in the form
key: value
.That form is actually a valid YAML format, so you could use
map
to apply afrom_yaml
filter to all those string, then,map
again adict2items
and finally,flatten
the list of list.Ending up with this taks:
This task would yield:
哇..它正在工作,谢谢β.εηοιτ.βε:
这里是工作脚本:
和输出:
Wow .. it is working, thanks β.εηοιτ.βε:
here the working script:
and the output: