ハンズオン(簡易版): S3基礎 レプリケーション

後始末2.1. S3バケットの全オブジェクト(全バージョン)の削除 (handson-cli-s3-replication-replication-destination-XXXXXXXXXXXX)

手順の目的 [why]

S3バケット"handson-cli-s3-replication-replication-destination-XXXXXXXXXXXX"の全てのオブジェクトを削除します。

設定値の指定

手順に必要な設定値を変数に格納をします。

1. S3バケット名

S3バケット名を指定します。

変数の設定:

S3_BUCKET_PREFIX='handson-cli-s3-replication-replication-destination'

コマンド:

AWS_ID=$( \
  aws sts get-caller-identity \
    --query 'Account' \
    --output text \
) \
  && echo ${AWS_ID}

結果(例):

XXXXXXXXXXXX

変数の設定:

S3_BUCKET_NAME="${S3_BUCKET_PREFIX}-${AWS_ID}" \
  && echo ${S3_BUCKET_NAME}

結果(例):

handson-cli-s3-replication-replication-destination-XXXXXXXXXXXX

各変数に正しい設定値が格納されていることを確認します。

変数の確認:

cat << END

  # 1. S3_BUCKET_NAME:"handson-cli-s3-replication-replication-destination-XXXXXXXXXXXX"
       S3_BUCKET_NAME="${S3_BUCKET_NAME}"

END

処理の実行

S3バケットの全オブジェクトを削除します。

変数の確認:

cat << END

  # S3_BUCKET_NAME:"handson-cli-s3-replication-replication-destination-XXXXXXXXXXXX"
    S3_BUCKET_NAME="${S3_BUCKET_NAME}"

END

コマンド:

for object_key in $(
  aws s3api list-objects-v2 \
    --bucket ${S3_BUCKET_NAME} \
    --query "Contents[].Key" \
    --output text \
); do
  for version_id in $(
    aws s3api list-object-versions \
      --bucket ${S3_BUCKET_NAME} \
      --prefix ${object_key} \
      --query "Versions[].VersionId" \
      --output text \
  ); do
    aws s3api delete-object \
      --bucket ${S3_BUCKET_NAME} \
      --key ${object_key} \
      --version-id ${version_id}
  done
done

結果(例):

{
  "VersionId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

完了確認

「S3バケット"handson-cli-s3-replication-replication-destination-XXXXXXXXXXXX"にオブジェクトとバージョンが存在しない。」ことを確認します。

コマンド:

aws s3api list-objects-v2 \
  --bucket ${S3_BUCKET_NAME} \
  --max-items 1000

結果(例):

(出力なし)

「S3バケット"handson-cli-s3-replication-replication-destination-XXXXXXXXXXXX"に削除マーカーが存在しない。」ことを確認します。

コマンド:

aws s3api list-object-versions \
  --bucket ${S3_BUCKET_NAME} \
  --query 'DeleteMarkers[?IsLatest==`true`].Key' \
  --output text

結果(例):

None

注釈

存在する場合は削除します。

変数の確認:

cat << END

  # S3_BUCKET_NAME:"handson-cli-s3-replication-replication-destination-XXXXXXXXXXXX"
    S3_BUCKET_NAME="${S3_BUCKET_NAME}"

END

コマンド:

for object_key in $( \
  aws s3api list-object-versions \
    --bucket ${S3_BUCKET_NAME} \
    --query 'DeleteMarkers[?IsLatest==`true`].Key' \
    --output text \
); do
  for version_id in $( \
    aws s3api list-object-versions \
      --bucket ${S3_BUCKET_NAME} \
      --prefix ${object_key} \
      --query 'DeleteMarkers[].VersionId' \
      --output text \
  ); do
    aws s3api delete-object \
      --bucket ${S3_BUCKET_NAME} \
      --key ${object_key} \
      --version-id ${version_id}
  done
done

結果(例):

{
  "VersionId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}