Help us understand the problem. What is going on with this article?

[AWS] 特定日付以前に作成されたスナップショットの一覧を取得する

More than 1 year has passed since last update.

jq 使おう

REGION='ap-northeast-1'
OWNER_ID=$(aws sts get-caller-identity | jq -r '.Account')
TARGET_DATE=$(date -u -d '-2 day' +%s) # 2日前をターゲットに

SNAPSHOT_IDS=$(aws ec2 --region ${REGION} describe-snapshots --owner-ids ${OWNER_ID} \
 | sed 's/\.000Z/Z/' \
 | jq ".Snapshots | sort_by(.StartTime) | .[]" \
 | jq "select (.StartTime | .== null or fromdateiso8601 <= ${TARGET_DATE})" \
 | jq -r '.SnapshotId')

あとは、これを回して消したりなんだり

for SNAPSHOT_ID in ${SNAPSHOT_IDS}; do
    SNAPSHOT=$(aws --region ${REGION} ec2 describe-snapshots --snapshot-id ${SNAPSHOT_ID} | jq '.Snapshots[]')
    DESCRIPTION=$(echo ${SNAPSHOT} | jq -r '.Description' | head -n 1)
    # Description に hogefuga が含まれる場合だけ処理
    if [[ $DESCRIPTION =~ hogefuga ]]; then
        STARTTIME=$(echo ${SNAPSHOT} | jq -r '.StartTime' | head -n 1)
        echo "Start ec2-delete-snapshot : ${SNAPSHOT_ID}[${STARTTIME}]: ${DESCRIPTION}"
        aws --region ${REGION} ec2 delete-snapshot --snapshot-id ${SNAPSHOT_ID}
        if [ $? != 0 ] ; then
            echo "Error ec2-delete-snapshot: ${SNAPSHOT_ID}"
            exit 1
        else
            echo "Success ec2-delete-snapshot : ${SNAPSHOT_ID}"
        fi
    fi
done
digitalcubeinc
デジタルキューブは AWS Partner Network (APN) アドバンスドテクノロジーパートナーです。
https://ja.amimoto-ami.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away