如何解决如何从json输出中读取值
基本上,我需要从 JSON 输出中读取一个值并在后续任务中使用它。所以,我尝试了 with_items
、loop
,但没有任何效果。
我从注册变量生成的示例 JSON:
TASK [local_volume_mount : debug Info from device that is parted] **************
Monday 29 March 2021 21:33:39 +0000 (0:00:02.271) 0:00:02.417 **********
ok: [node1] => {
"partitioned_device_live_info": {
"changed": false,"msg": "All items completed","results": [
{
"ansible_loop_var": "item","changed": false,"disk": {
"dev": "/dev/nvme2n1","logical_block": 512,"model": "SAMSUNG MZQLW960HMJP-00003","physical_block": 512,"size": 937692504.0,"table": "msdos","unit": "kib"
},"failed": false,"invocation": {
"module_args": {
"align": "optimal","device": "/dev/nvme2n1","flags": null,"label": "msdos","name": null,"number": 1,"part_end": "100%","part_start": "0%","part_type": "primary","state": "present","unit": "KiB"
}
},"item": [
{
"device": "/dev/nvme2n1","partitions": [
{
"end": "100%","start": "0%","storage_class": "ssd-wkr-services"
}
]
},{
"end": "100%","storage_class": "ssd-wkr-services"
}
],"partitions": [
{
"begin": 1024.0,"end": 937692160.0,"flags": [],"fstype": "","name": "","num": 1,"size": 937691136.0,"unit": "kib"
}
],"script": ""
}
]
}
}
因此,从上面我需要读取 partitions.num
值并在下一个任务中使用它,但是,我不知道该怎么做。
任务:
- name: THIS IS BEING TESTED
debug:
var: "{{ item.partitions }}"
ignore_errors: no
#loop: "{{ partitioned_device_live_info.results }}"
with_items: "{{ partitioned_device_live_info.results }}"
上述任务的输出是
'dict object' has no attribute 'partitions'
我想将该值 item.partitions.num
存储在一个变量中,然后在进一步的任务中使用它。
解决方法
使用 msg 搞定,下面是我的改动
- name: THIS IS BEING TESTED with MSG and with_items
debug:
msg: "{{ item.partitions[0].num }}"
with_items: "{{ partitioned_device_live_info.results }}"
,
您始终可以对 set facts
使用正则表达式。更多详情stackoverflow
以下是一些用例
- name: Long form task does not
ansible.builtin.replace:
path: /etc/hosts
regexp: '\b(localhost)(\d*)\b'
replace: '\1\2.localdomain\2 \1\2'
- name: Explicitly specifying positional matched groups in replacement
ansible.builtin.replace:
path: /etc/ssh/sshd_config
regexp: '^(ListenAddress[ ]+)[^\n]+$'
replace: '\g<1>0.0.0.0'
设置fact
- name: set version in file after replacement
set_fact:
version_in_file: "{{ version_deployment_file | regex_search(docker_image_version) }}"
更多详情 - ansible.builtin.replace
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。