解説
Custom AMIを作ったけど、AMIを削除した後にSnapshot消し忘れたなんて経験はありませんか? Snapshotにも定期的な棚卸しが必要です。
基本的にはec2.describeSnapshotsを呼ぶだけなのですが、そのまま実行するとPublicなsnapshotが大量に取得されて悲しい気分になります。
OwnerIdsとして実行中のAWS Account IDを設定すれば良いのですが、より簡単な方法として"self","amazon"という二つのキーワードも利用できます。
APIリファレンスにより引用
/**
* Scopes the results to snapshots with the specified owners. You can specify a combination of AWS account IDs, self, and amazon.
*/
OwnerIds?: OwnerStringList;
サンプルコード
async function getVolumeSnapshots(ec2: EC2, NextToken?: string): Promise<Snapshot[]> {
console.log(`getVolumeSnapshots ${NextToken || "initial"}`)
const r = await ec2.describeSnapshots({
OwnerIds: ["self"],
NextToken,
}).promise()
if (!r.Snapshots) {
return []
}
let result: Snapshot[] = []
if (r.Snapshots) {
result = result.concat(r.Snapshots)
}
if (r.NextToken) {
result = result.concat(await getVolumeSnapshots(ec2, r.NextToken))
}
return result
}
複数のアカウントからまとめて取得する方法
別記事で、Organizationの各アカウントにAssumeRoleしながらAPIを呼び出す方法を解説しています。その手法で作ったAssumeRole済のec2インスタンスを与えることで、このコードがそのまま利用できます。