【AWS/Python】S3のタグを登録/更新/取得/削除する

もくじ

タグ

S3に置いたオブジェクト(ファイル)にタグを付加することで検索を容易にしたりできます。

同じバケット内にprojectAとprojectBのオブジェクトがあった場合、それぞれにタグをつけておけたり活用の場は多々あります。

boto3をインストール

AWS S3のファイル操作にはライブラリboto3を使います。

$ pip install boto3

projectA = "test",
projectB = "production"

タグは単数でも複数でも設定可能です。

タグを登録/更新 put_object_tagging

import boto3

# バケット取得
s3 = boto3.resource("s3")
bucket_name = s3.Bucket("sample_bucket")
file_path = 'sample.jpg'

client = boto3.client('s3')
res = client.put_object_tagging(
  Bucket=bucket_name,
  Key=file_path,
  res={
    'TagSet': [
      {
        'Key': 'projectA',
        'Value': 'test',
      },
      {
        'Key': 'projectB',
        'Value': 'production',
      },
    ],
  },
)

タグを取得 get_object_tagging

タグを取得して、先ほど登録したオブジェクトを検索します。

import boto3

# バケット取得
s3 = boto3.resource("s3")
bucket_name = s3.Bucket("sample_bucket")
file_path = 'sample.jpg'

client = boto3.client('s3')
res = client.get_object_tagging(
  Bucket=bucket_name,
  Key=file_path
)
for tag in res['TagSet']:
  if tag['Key'] == "projectA" && tag['Value'] == "test":
    print('projectA の test というタグがあります')
  else:
    print('projectA の test というタグはありません')

「projectA の test というタグがあります」と出力されます。

タグを削除 delete_object_tagging

import boto3

# バケット取得
s3 = boto3.resource("s3")
bucket_name = s3.Bucket("sample_bucket")
file_path = 'sample.jpg'

client = boto3.client('s3')
res = client.delete_object_tagging(
  Bucket=bucket_name,
  Key=file_path
)

設定されているタグはすべて削除されます。

エラー「expected string or bytes-like object」

実は何度かうまくいかなかったき、下記のようなエラーが出てました。

expected string or bytes-like object

トライキャッチするとバケット指定が適切ではなかったようです。

bucket: s3.Bucket(name='sample_bucket')

*今回の記事ではエラーにならないよう反映しています。

このエラーでわかったことは、Bucketに指定すべきはバケット名前ということです。バケット自体を渡すのではなく、バケットの名前を渡してくださいね!

ドキュメントでは渡せる引数の型を記載してくれてますので、参考までに引用します。

response = client.put_object_tagging(
    Bucket='string',
    Key='string',
    VersionId='string',
    ContentMD5='string',
    Tagging={
        'TagSet': [
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    },
    ExpectedBucketOwner='string',
    RequestPayer='requester'
)

参考URL

get-object-tagging — AWS CLI 1.24.6 Command Reference

S3 — Boto3 Docs 1.23.6 documentation

boto3でS3のファイル操作 | 分析ノート

【boto3】EC2インスタンスの情報を取得する - サーバーワークスエンジニアブログ

S3に保存されたRedshiftの監査ログを作成イベント通知(Lambda)で自動でタグ付けしてみた | DevelopersIO