我正在开发 Ansible 角色来删除 VMWARE 快照。 但是,因为删除所有这些文件可能很容易,所以我想删除那些名称与特定字符串匹配且早于 x 天的文件。
为了实现该目标,我首先使用 vmware_guest_snapshot_info 集合收集每个虚拟机的快照详细信息。这是最简单的部分。 我将输出注册在一个变量中(不知道 Ansible 是如何定义它的)。 我最终得到了以下字典:
{"changed": false,
"guest_snapshots":
{
"current_snapshot":
{"creation_time": "2023-06-06T18:31:37.532826+00:00",
"description": "Snapshot TEST",
"id": 1243,
"name": "Patching_Linux2023-06-06",
"state": "poweredOff"
},
"snapshots": [
{"creation_time": "2023-06-06T14:38:17.909158+00:00",
"description": "",
"id": 1242,
"name": "Linux_test",
"state": "poweredOff"
},
{
"creation_time": "2023-06-06T18:31:37.532826+00:00",
"description": "Snapshot TEST",
"id": 1243, "name": "Patching_Linux2023-06-06",
"state": "poweredOff"
}
]
}
}
我需要考虑到我可能有多个快照。 我尝试使用以下 Ansible 任务进行删除(起初我没有专注于快照年龄):
第一枪是:
- name: Remove old snapshots
vmware_guest_snapshot:
hostname: "{{ vcenter_hostname_uni }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: myvcenter
validate_certs: no
#name: "{{ inventory_hostname |upper }}"
folder: "{{ vm_folders }}"
vm_id: "{{ item.item }}"
snapshot_name: "{{ item.name }}"
state: absent
delegate_to: "{{vcenter_launcher_uni }}"
loop: "{{ snapshots_info.name }}"
when: item.name is search('Patching_Linux')
tags:
- clean_patching_snap
我已经尝试了其他带有循环和with_items条件的东西,但我仍然无法弄清楚如何访问所有快照名称。
有什么想法吗?
应该这样做:
列出快照
```
- name: Find all sanpshots
vmware_guest_snapshot_info:
hostname: "{{ vcenter_hostname_uni }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: myvcenter
validate_certs: no
name: "{{ inventory_hostname |upper }}"
folder: "{{ vm_folders }}"
delegate_to: "{{vcenter_launcher_uni }}"
register: snapshots_info
tags:
- list_snap
- clean_patching_snap```
删除名称中包含特定模式的快照:
```
- name: Remove old snapshots
vmware_guest_snapshot:
hostname: "{{ vcenter_hostname_uni }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: myvcenter
validate_certs: no
name: "{{ inventory_hostname |upper }}"
folder: "{{ vm_folders }}"
snapshot_name: "{{ item.name }}"
state: absent
delegate_to: "{{vcenter_launcher_uni }}"
loop: "{{ snapshots_info.guest_snapshots.snapshots }}"
when: item.name is search('MyPatternName')```
我仍然坚持选择那些超过定义天数的内容。
添加这个没有帮助: ` 和 (ansible_date_time.epoch - (item.creation_time | int)) > 4 * 86400)
Something like this will probably work but I am stucked with the exact syntax
'{{ (( ansible_date_time.iso8601 | to_datetime('%Y-%m-%dT%H:%M:%S.%f%z')) - (item.creation_time | to_datetime('%Y-%m-%dT%H:%M:%S.%f%z')) > (4 * 24 * 60 * 60) and item.name is search('Patching_Linux') }}'
It gives an error
您还在寻找解决方案吗?