我在 Ansible 變數server_info中有以下資料,在任務結束時通過暫存器設定;
ok: [server123] => {
"msg": {
"changed": false,
"failed": false,
"instances": [
{
"ami_launch_index": 0,
"architecture": "x86_64",
"block_device_mappings": [
{
"device_name": "/dev/sda1",
"ebs": {
"attach_time": "2021-02-11T11:48:30 00:00",
"delete_on_termination": false,
"status": "attached",
"volume_id": "vol-5436546546"
}
},
{
"device_name": "/dev/sda2",
"ebs": {
"attach_time": "2021-02-11T11:48:30 00:00",
"delete_on_termination": false,
"status": "attached",
"volume_id": "vol-3546456535"
}
}
],
"capacity_reservation_specification": {
"capacity_reservation_preference": "open"
},
"client_token": "",
"cpu_options": {
"core_count": 2,
"threads_per_core": 1
},
"ebs_optimized": false,
"ena_support": true,
"enclave_options": {
"enabled": false
},
"hibernation_options": {
"configured": false
},
"hypervisor": "xen",
"iam_instance_profile": {
"arn": "arn:aws:iam::6346346356:instance-profile/bla",
"id": "SXIUIAHFKBAFIUAEKBADF"
},
"image_id": "ami-65754765475476",
"instance_id": "i-4657654765476547765",
"instance_type": "t2.large",
"key_name": "bla",
"launch_time": "2021-02-15T08:51:44 00:00",
"maintenance_options": {
"auto_recovery": "default"
},
etc... etc...
}
]
}
}
我正在嘗試檢索“ instance_id ”的值,但是出現以下錯誤;
- name: "Instance ID"
debug:
msg: "{{ server_info.instances.instance_id }}"
任務 [實體 ID] ********************************************* ****************************************************** *************致命:[server123]:失敗!=> {"msg": "該任務包含一個帶有未定義變數的選項。錯誤是:'list object' has no attribute 'instance_id'\n\n錯誤出現在 '/ansible/testing.yml' 中:第 38 行第 7 列,但可能\n位于檔案中的其他位置,具體取決于確切的語法問題。\n\n違規行似乎是:\n\n\n - 名稱:“實體 ID”\n ^ 此處\n "}
我的嵌套變數檢索語法哪里出錯了?
謝謝你。
uj5u.com熱心網友回復:
只需修改您的任務:
- name: "Instance ID"
debug:
msg: "{{ server_info.instances.0.instance_id }}"
我想instances是一個只有一條記錄的陣列......
如果陣列中有更多記錄,則可以使用 map:
- name: find all instances
debug:
msg:
- "==========================="
- "List of instances id"
- "==========================="
- '{{ server_info.instances | map(attribute="instance_id")|list}}'
- ""
uj5u.com熱心網友回復:
看看下面的代碼是否有效
- name: get instance id
set_fact:
new_result: "{{ server_info.instances['instances'] }}"
register: filterd_result
- name: get all ids
vars:
reduce_query: >-
[].{
instance_id: instance_id
}
names: "{{ new_result | json_query(reduce_query)}}"
register: result_names
no_log: true
debug:
var: names
- name: display result
debug:
msg: "{{ result_names.names | map(attribute='instance_id') | flatten }}"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/484424.html
