set_fact
并在原始数据上循环以检查每一项(也就是说,我不认为通过简单地对原始数据应用一系列过滤器就可以得到解决方案)。
新列表中的新项目将通过将原始dict与包含正确日期的dict组合或使用空dict保留当前日期来获得。
---
- name: Process date and sort
hosts: localhost
gather_facts: false
vars:
# Your original data as json on a single line to shorten display
api_events: [{"apiVersion": "v1", "count": 11, "eventTime": null, "firstTimestamp": "2020-10-20T16:17:08Z", "lastTimestamp": "2020-10-20T16:30:38Z", "involvedObject": {"apiVersion": "v1"}, "kind": "Event"}, {"apiVersion": "v1", "count": 11, "eventTime": "2020-10-20T16:17:10.182317Z", "firstTimestamp": null, "lastTimestamp": null, "involvedObject": {"apiVersion": "v1"}, "kind": "Event"}]
tasks:
- name: Process API events to determine time we will use
vars:
new_timestamp: "{{ item.firstTimestamp | ternary({}, {'firstTimestamp': item.eventTime}) }}"
current_event: "{{ item | combine(new_timestamp) }}"
set_fact:
processed_api_events: "{{ processed_api_events | default([]) + [current_event] }}"
loop: "{{ api_events }}"
- name: Show result sorted
debug:
msg: "{{ processed_api_events | sort(attribute='firstTimestamp') }}"
它给出了:
PLAY [Process date and sort] ***********************************************************************************************************************************************************************************************************
TASK [Process API events to determine time we will use] ********************************************************************************************************************************************************************************
ok: [localhost] => (item={'apiVersion': 'v1', 'count': 11, 'eventTime': None, 'firstTimestamp': '2020-10-20T16:17:08Z', 'lastTimestamp': '2020-10-20T16:30:38Z', 'involvedObject': {'apiVersion': 'v1'}, 'kind': 'Event'})
ok: [localhost] => (item={'apiVersion': 'v1', 'count': 11, 'eventTime': '2020-10-20T16:17:10.182317Z', 'firstTimestamp': None, 'lastTimestamp': None, 'involvedObject': {'apiVersion': 'v1'}, 'kind': 'Event'})
TASK [Show result sorted] **************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": [
{
"apiVersion": "v1",
"count": 11,
"eventTime": null,
"firstTimestamp": "2020-10-20T16:17:08Z",
"involvedObject": {
"apiVersion": "v1"
},
"kind": "Event",
"lastTimestamp": "2020-10-20T16:30:38Z"
},
{
"apiVersion": "v1",
"count": 11,
"eventTime": "2020-10-20T16:17:10.182317Z",
"firstTimestamp": "2020-10-20T16:17:10.182317Z",
"involvedObject": {
"apiVersion": "v1"
},
"kind": "Event",
"lastTimestamp": null
}
]
}
PLAY RECAP *****************************************************************************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0