0
0

More than 3 years have passed since last update.

自分の所有するEBS Snapshotの一覧を取得する

Last updated at Posted at 2020-09-03

解説

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インスタンスを与えることで、このコードがそのまま利用できます。

AWSの各アカウントのインスタンス一覧を取得する

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0