我想检查是否可以删除一些满足特定条件的 AWS EBS 快照。但是,由于我们有很多快照,我不想逐一迭代,而是执行检查是否可以并行删除它们。我得到了这样的 JSON 形式的快照列表
{
"Snapshots": [
{
"Description": "",
"Encrypted": false,
"OwnerId": "0123456789",
"Progress": "100%",
"SnapshotId": "snap-0123456789",
"StartTime": "2021-03-23T23:58:42.019000+00:00",
"State": "completed",
"VolumeId": "vol-ffffffff",
"VolumeSize": 8,
"OwnerAlias": "amazon",
"StorageTier": "standard"
},
// more snapshots
]
}
这是(简化的)闭包,用于确定是否可以删除快照,将 JSON 中的快照元素传递给它
// Closure to check if I can delete snapshot
private Closure snapshotCanBeDeleted(final String s) {
return {
s.State.equals("completed")
}
}
这是使用上述闭包的代码。
// Get a list of snapshots via AWS SDK or CLI in JSON
def snapshots = functionToGetAListOfSnapshots() // function not shown
// Create a map of snapshots and closures that can be run in parallel
Map<String, Closure> map = new TreeMap()
snapshots.Snapshots.each {
map.put(it.SnapshotId, snapshotCanBeDeleted(it))
}
parallel map // This runs the snapshotCanBeDeleted(it) closures in parallel
但是我现在如何打印出闭包的值(布尔值)?我试过这个
map.each {k,v ->
println "Snapshot $k can be deleted: $v"
}
但我认为这是试图打印闭包本身,而不是它的值,对于
true
来说应该是 false
,因为我只是得到了,而没有打印出地图的 v
部分。
snap-0123456789 can be deleted:
[Pipeline] echo
snap-1234567890 can be deleted:
[Pipeline] echo
snap-9876543210 can be deleted:
我想要
snap-0123456789 can be deleted: true
[Pipeline] echo
snap-1234567890 can be deleted: false
[Pipeline] echo
snap-9876543210 can be deleted: true
有什么线索吗?这不是运行返回值的闭包的正确方法吗?谢谢。
parallel
步骤不会修改您提供的地图。将其视为.each{}
。因此,您必须在闭包外部定义一个列表并将所有结果放在那里:
def completedSnapshots = []
private Closure snapshotCanBeDeleted(final String s) {
return {
if (s.State.equals("completed")) {
completedSnapshots.add(s.SnapshotId)
}
}
}