객체 메타데이터 보기 및 수정

개념

이 페이지에서는 Cloud Storage에 저장된 객체와 연결된 메타데이터를 보고 수정하는 방법에 대해 설명합니다.

이 페이지에는 데이터에 액세스할 수 있는 사람을 관리하는 Identity and Access Management(IAM) 정책 또는 객체 액세스제어 목록(ACL)을 보거나 수정하는 방법을 다루지 않습니다. 이러한 작업을 수행하기 위한 가이드는 IAM 권한 사용ACL 생성 및 관리를 참조하세요.

필요한 역할

객체의 메타데이터를 보고 수정하는 데 필요한 권한을 얻으려면 관리자에게 버킷에 대한 스토리지 객체 사용자(roles/storage.objectUser) 역할을 부여해 달라고 요청하세요.

이 역할에는 객체의 메타데이터를 보고 수정하는 데 필요한 권한이 포함됩니다. 필요한 정확한 권한을 보려면 필수 권한 섹션을 확장하세요.

필수 권한

  • storage.buckets.list
    • 이 권한은 Google Cloud 콘솔을 사용하여 이 페이지의 태스크를 수행하려는 경우에만 필요합니다.
  • storage.objects.get
  • storage.objects.getIamPolicy
    • 이 권한은 객체의 IAM 정책을 반환하려는 경우에만 필요합니다.
  • storage.objects.list
  • storage.objects.setRetention
    • 이 권한은 객체의 보관 구성을 설정하려는 경우에만 필요합니다.
  • storage.objects.update

다른 사전 정의된 역할이나 커스텀 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

버킷에 대한 역할 부여는 버킷에 IAM 사용을 참조하세요.

객체 메타데이터 보기

객체와 연관된 메타데이터를 보려면 다음 안내를 따르세요.

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 메타데이터를 보려는 객체가 포함된 버킷의 이름을 클릭합니다.

    객체 탭이 선택된 상태로 버킷 세부정보 페이지가 열립니다.

  3. 객체(폴더에 있을 수 있음)로 이동합니다.

    객체의 크기 및 스토리지 클래스와 같은 특정 객체 메타데이터 값이 객체 이름과 함께 표시됩니다.

  4. 객체의 이름을 클릭합니다.

    객체 세부정보 페이지가 열리고 추가 객체 메타데이터가 표시됩니다.

  5. 메타데이터 수정을 클릭합니다.

    표시되는 오버레이 창에 커스텀 메타데이터를 포함하여 몇 가지 추가 객체 메타데이터 키의 현재 값이 표시됩니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

gcloud storage objects describe 명령어를 사용합니다.

gcloud storage objects describe gs://BUCKET_NAME/OBJECT_NAME

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 메타데이터를 보려는 객체가 포함된 버킷의 이름입니다. 예를 들면 my-awesome-bucket입니다.
  • OBJECT_NAME은 메타데이터를 보려는 객체의 이름입니다. 예를 들면 cat.jpeg입니다.

성공하면 다음 예시와 비슷한 응답이 표시됩니다.

bucket: my-awesome-bucket
content_type: image/png
crc32c_hash: pNKjPQ==
creation_time: 2024-01-26T21:33:04+0000
custom_fields:
  Animal: Cat
  Type: Cute
custom_time: 1970-01-01T00:00:00+0000
etag: CMXyydSA/IMDEAE=
generation: '1706304784726341'
md5_hash: KCbI3PYk1aHfekIvf/osrw==
metageneration: 1
name: kitten.png
size: 168276
storage_class: STANDARD
storage_class_update_time: 2024-01-26T21:33:04+0000
storage_url: gs://nstocktest8/kitten.png#1706304784726341
update_time: 2024-01-26T21:33:04+0000

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  StatusOr<gcs::ObjectMetadata> object_metadata =
      client.GetObjectMetadata(bucket_name, object_name);
  if (!object_metadata) throw std::move(object_metadata).status();

  std::cout << "The metadata for object " << object_metadata->name()
            << " in bucket " << object_metadata->bucket() << " is "
            << *object_metadata << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Cloud.Storage.V1;
using System;

public class GetMetadataSample
{
    public Google.Apis.Storage.v1.Data.Object GetMetadata(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions { Projection = Projection.Full });
        Console.WriteLine($"Bucket:\t{storageObject.Bucket}");
        Console.WriteLine($"CacheControl:\t{storageObject.CacheControl}");
        Console.WriteLine($"ComponentCount:\t{storageObject.ComponentCount}");
        Console.WriteLine($"ContentDisposition:\t{storageObject.ContentDisposition}");
        Console.WriteLine($"ContentEncoding:\t{storageObject.ContentEncoding}");
        Console.WriteLine($"ContentLanguage:\t{storageObject.ContentLanguage}");
        Console.WriteLine($"ContentType:\t{storageObject.ContentType}");
        Console.WriteLine($"Crc32c:\t{storageObject.Crc32c}");
        Console.WriteLine($"ETag:\t{storageObject.ETag}");
        Console.WriteLine($"Generation:\t{storageObject.Generation}");
        Console.WriteLine($"Id:\t{storageObject.Id}");
        Console.WriteLine($"Kind:\t{storageObject.Kind}");
        Console.WriteLine($"KmsKeyName:\t{storageObject.KmsKeyName}");
        Console.WriteLine($"Md5Hash:\t{storageObject.Md5Hash}");
        Console.WriteLine($"MediaLink:\t{storageObject.MediaLink}");
        Console.WriteLine($"Metageneration:\t{storageObject.Metageneration}");
        Console.WriteLine($"Name:\t{storageObject.Name}");
        Console.WriteLine($"Size:\t{storageObject.Size}");
        Console.WriteLine($"StorageClass:\t{storageObject.StorageClass}");
        Console.WriteLine($"TimeCreated:\t{storageObject.TimeCreated}");
        Console.WriteLine($"Updated:\t{storageObject.Updated}");
        bool eventBasedHold = storageObject.EventBasedHold ?? false;
        Console.WriteLine("Event-based hold enabled? {0}", eventBasedHold);
        bool temporaryHold = storageObject.TemporaryHold ?? false;
        Console.WriteLine("Temporary hold enabled? {0}", temporaryHold);
        Console.WriteLine($"RetentionExpirationTime\t{storageObject.RetentionExpirationTime}");
        if (storageObject.Metadata != null)
        {
            Console.WriteLine("Metadata: ");
            foreach (var metadata in storageObject.Metadata)
            {
                Console.WriteLine($"{metadata.Key}:\t{metadata.Value}");
            }
        }
        Console.WriteLine($"CustomTime:\t{storageObject.CustomTime}");
        return storageObject;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// getMetadata prints all of the object attributes.
func getMetadata(w io.Writer, bucket, object string) (*storage.ObjectAttrs, error) {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	o := client.Bucket(bucket).Object(object)
	attrs, err := o.Attrs(ctx)
	if err != nil {
		return nil, fmt.Errorf("Object(%q).Attrs: %w", object, err)
	}
	fmt.Fprintf(w, "Bucket: %v\n", attrs.Bucket)
	fmt.Fprintf(w, "CacheControl: %v\n", attrs.CacheControl)
	fmt.Fprintf(w, "ContentDisposition: %v\n", attrs.ContentDisposition)
	fmt.Fprintf(w, "ContentEncoding: %v\n", attrs.ContentEncoding)
	fmt.Fprintf(w, "ContentLanguage: %v\n", attrs.ContentLanguage)
	fmt.Fprintf(w, "ContentType: %v\n", attrs.ContentType)
	fmt.Fprintf(w, "Crc32c: %v\n", attrs.CRC32C)
	fmt.Fprintf(w, "Generation: %v\n", attrs.Generation)
	fmt.Fprintf(w, "KmsKeyName: %v\n", attrs.KMSKeyName)
	fmt.Fprintf(w, "Md5Hash: %v\n", attrs.MD5)
	fmt.Fprintf(w, "MediaLink: %v\n", attrs.MediaLink)
	fmt.Fprintf(w, "Metageneration: %v\n", attrs.Metageneration)
	fmt.Fprintf(w, "Name: %v\n", attrs.Name)
	fmt.Fprintf(w, "Size: %v\n", attrs.Size)
	fmt.Fprintf(w, "StorageClass: %v\n", attrs.StorageClass)
	fmt.Fprintf(w, "TimeCreated: %v\n", attrs.Created)
	fmt.Fprintf(w, "Updated: %v\n", attrs.Updated)
	fmt.Fprintf(w, "Event-based hold enabled? %t\n", attrs.EventBasedHold)
	fmt.Fprintf(w, "Temporary hold enabled? %t\n", attrs.TemporaryHold)
	fmt.Fprintf(w, "Retention expiration time %v\n", attrs.RetentionExpirationTime)
	fmt.Fprintf(w, "Custom time %v\n", attrs.CustomTime)
	fmt.Fprintf(w, "\n\nMetadata\n")
	for key, value := range attrs.Metadata {
		fmt.Fprintf(w, "\t%v = %v\n", key, value)
	}
	return attrs, nil
}

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageException;
import com.google.cloud.storage.StorageOptions;
import java.util.Date;
import java.util.Map;

public class GetObjectMetadata {
  public static void getObjectMetadata(String projectId, String bucketName, String blobName)
      throws StorageException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    // Select all fields
    // Fields can be selected individually e.g. Storage.BlobField.CACHE_CONTROL
    Blob blob =
        storage.get(bucketName, blobName, Storage.BlobGetOption.fields(Storage.BlobField.values()));

    // Print blob metadata
    System.out.println("Bucket: " + blob.getBucket());
    System.out.println("CacheControl: " + blob.getCacheControl());
    System.out.println("ComponentCount: " + blob.getComponentCount());
    System.out.println("ContentDisposition: " + blob.getContentDisposition());
    System.out.println("ContentEncoding: " + blob.getContentEncoding());
    System.out.println("ContentLanguage: " + blob.getContentLanguage());
    System.out.println("ContentType: " + blob.getContentType());
    System.out.println("CustomTime: " + blob.getCustomTime());
    System.out.println("Crc32c: " + blob.getCrc32c());
    System.out.println("Crc32cHexString: " + blob.getCrc32cToHexString());
    System.out.println("ETag: " + blob.getEtag());
    System.out.println("Generation: " + blob.getGeneration());
    System.out.println("Id: " + blob.getBlobId());
    System.out.println("KmsKeyName: " + blob.getKmsKeyName());
    System.out.println("Md5Hash: " + blob.getMd5());
    System.out.println("Md5HexString: " + blob.getMd5ToHexString());
    System.out.println("MediaLink: " + blob.getMediaLink());
    System.out.println("Metageneration: " + blob.getMetageneration());
    System.out.println("Name: " + blob.getName());
    System.out.println("Size: " + blob.getSize());
    System.out.println("StorageClass: " + blob.getStorageClass());
    System.out.println("TimeCreated: " + new Date(blob.getCreateTime()));
    System.out.println("Last Metadata Update: " + new Date(blob.getUpdateTime()));
    System.out.println("Object Retention Policy: " + blob.getRetention());
    Boolean temporaryHoldIsEnabled = (blob.getTemporaryHold() != null && blob.getTemporaryHold());
    System.out.println("temporaryHold: " + (temporaryHoldIsEnabled ? "enabled" : "disabled"));
    Boolean eventBasedHoldIsEnabled =
        (blob.getEventBasedHold() != null && blob.getEventBasedHold());
    System.out.println("eventBasedHold: " + (eventBasedHoldIsEnabled ? "enabled" : "disabled"));
    if (blob.getRetentionExpirationTime() != null) {
      System.out.println("retentionExpirationTime: " + new Date(blob.getRetentionExpirationTime()));
    }
    if (blob.getMetadata() != null) {
      System.out.println("\n\n\nUser metadata:");
      for (Map.Entry<String, String> userMetadata : blob.getMetadata().entrySet()) {
        System.out.println(userMetadata.getKey() + "=" + userMetadata.getValue());
      }
    }
  }
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function getMetadata() {
  // Gets the metadata for the file
  const [metadata] = await storage
    .bucket(bucketName)
    .file(fileName)
    .getMetadata();

  console.log(`Bucket: ${metadata.bucket}`);
  console.log(`CacheControl: ${metadata.cacheControl}`);
  console.log(`ComponentCount: ${metadata.componentCount}`);
  console.log(`ContentDisposition: ${metadata.contentDisposition}`);
  console.log(`ContentEncoding: ${metadata.contentEncoding}`);
  console.log(`ContentLanguage: ${metadata.contentLanguage}`);
  console.log(`ContentType: ${metadata.contentType}`);
  console.log(`CustomTime: ${metadata.customTime}`);
  console.log(`Crc32c: ${metadata.crc32c}`);
  console.log(`ETag: ${metadata.etag}`);
  console.log(`Generation: ${metadata.generation}`);
  console.log(`Id: ${metadata.id}`);
  console.log(`KmsKeyName: ${metadata.kmsKeyName}`);
  console.log(`Md5Hash: ${metadata.md5Hash}`);
  console.log(`MediaLink: ${metadata.mediaLink}`);
  console.log(`Metageneration: ${metadata.metageneration}`);
  console.log(`Name: ${metadata.name}`);
  console.log(`Size: ${metadata.size}`);
  console.log(`StorageClass: ${metadata.storageClass}`);
  console.log(`TimeCreated: ${new Date(metadata.timeCreated)}`);
  console.log(`Last Metadata Update: ${new Date(metadata.updated)}`);
  console.log(`TurboReplication: ${metadata.rpo}`);
  console.log(
    `temporaryHold: ${metadata.temporaryHold ? 'enabled' : 'disabled'}`
  );
  console.log(
    `eventBasedHold: ${metadata.eventBasedHold ? 'enabled' : 'disabled'}`
  );
  if (metadata.retentionExpirationTime) {
    console.log(
      `retentionExpirationTime: ${new Date(metadata.retentionExpirationTime)}`
    );
  }
  if (metadata.metadata) {
    console.log('\n\n\nUser metadata:');
    for (const key in metadata.metadata) {
      console.log(`${key}=${metadata.metadata[key]}`);
    }
  }
}

getMetadata().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * List object metadata.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 */
function object_metadata(string $bucketName, string $objectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $info = $object->info();
    if (isset($info['name'])) {
        printf('Blob: %s' . PHP_EOL, $info['name']);
    }
    if (isset($info['bucket'])) {
        printf('Bucket: %s' . PHP_EOL, $info['bucket']);
    }
    if (isset($info['storageClass'])) {
        printf('Storage class: %s' . PHP_EOL, $info['storageClass']);
    }
    if (isset($info['id'])) {
        printf('ID: %s' . PHP_EOL, $info['id']);
    }
    if (isset($info['size'])) {
        printf('Size: %s' . PHP_EOL, $info['size']);
    }
    if (isset($info['updated'])) {
        printf('Updated: %s' . PHP_EOL, $info['updated']);
    }
    if (isset($info['generation'])) {
        printf('Generation: %s' . PHP_EOL, $info['generation']);
    }
    if (isset($info['metageneration'])) {
        printf('Metageneration: %s' . PHP_EOL, $info['metageneration']);
    }
    if (isset($info['etag'])) {
        printf('Etag: %s' . PHP_EOL, $info['etag']);
    }
    if (isset($info['crc32c'])) {
        printf('Crc32c: %s' . PHP_EOL, $info['crc32c']);
    }
    if (isset($info['md5Hash'])) {
        printf('MD5 Hash: %s' . PHP_EOL, $info['md5Hash']);
    }
    if (isset($info['contentType'])) {
        printf('Content-type: %s' . PHP_EOL, $info['contentType']);
    }
    if (isset($info['temporaryHold'])) {
        printf('Temporary hold: %s' . PHP_EOL, ($info['temporaryHold'] ? 'enabled' : 'disabled'));
    }
    if (isset($info['eventBasedHold'])) {
        printf('Event-based hold: %s' . PHP_EOL, ($info['eventBasedHold'] ? 'enabled' : 'disabled'));
    }
    if (isset($info['retentionExpirationTime'])) {
        printf('Retention Expiration Time: %s' . PHP_EOL, $info['retentionExpirationTime']);
    }
    if (isset($info['retention'])) {
        printf('Retention mode: %s' . PHP_EOL, $info['retention']['mode']);
        printf('Retain until time is: %s' . PHP_EOL, $info['retention']['retainUntilTime']);
    }
    if (isset($info['customTime'])) {
        printf('Custom Time: %s' . PHP_EOL, $info['customTime']);
    }
    if (isset($info['metadata'])) {
        printf('Metadata: %s' . PHP_EOL, print_r($info['metadata'], true));
    }
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import storage


def blob_metadata(bucket_name, blob_name):
    """Prints out a blob's metadata."""
    # bucket_name = 'your-bucket-name'
    # blob_name = 'your-object-name'

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    # Retrieve a blob, and its metadata, from Google Cloud Storage.
    # Note that `get_blob` differs from `Bucket.blob`, which does not
    # make an HTTP request.
    blob = bucket.get_blob(blob_name)

    print(f"Blob: {blob.name}")
    print(f"Bucket: {blob.bucket.name}")
    print(f"Storage class: {blob.storage_class}")
    print(f"ID: {blob.id}")
    print(f"Size: {blob.size} bytes")
    print(f"Updated: {blob.updated}")
    print(f"Generation: {blob.generation}")
    print(f"Metageneration: {blob.metageneration}")
    print(f"Etag: {blob.etag}")
    print(f"Owner: {blob.owner}")
    print(f"Component count: {blob.component_count}")
    print(f"Crc32c: {blob.crc32c}")
    print(f"md5_hash: {blob.md5_hash}")
    print(f"Cache-control: {blob.cache_control}")
    print(f"Content-type: {blob.content_type}")
    print(f"Content-disposition: {blob.content_disposition}")
    print(f"Content-encoding: {blob.content_encoding}")
    print(f"Content-language: {blob.content_language}")
    print(f"Metadata: {blob.metadata}")
    print(f"Medialink: {blob.media_link}")
    print(f"Custom Time: {blob.custom_time}")
    print("Temporary hold: ", "enabled" if blob.temporary_hold else "disabled")
    print(
        "Event based hold: ",
        "enabled" if blob.event_based_hold else "disabled",
    )
    if blob.retention_expiration_time:
        print(
            f"retentionExpirationTime: {blob.retention_expiration_time}"
        )

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def get_metadata bucket_name:, file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name
  file    = bucket.file file_name

  puts "Name: #{file.name}"
  puts "Bucket: #{bucket.name}"
  puts "Storage class: #{bucket.storage_class}"
  puts "ID: #{file.id}"
  puts "Size: #{file.size} bytes"
  puts "Created: #{file.created_at}"
  puts "Updated: #{file.updated_at}"
  puts "Generation: #{file.generation}"
  puts "Metageneration: #{file.metageneration}"
  puts "Etag: #{file.etag}"
  puts "Owners: #{file.acl.owners.join ','}"
  puts "Crc32c: #{file.crc32c}"
  puts "md5_hash: #{file.md5}"
  puts "Cache-control: #{file.cache_control}"
  puts "Content-type: #{file.content_type}"
  puts "Content-disposition: #{file.content_disposition}"
  puts "Content-encoding: #{file.content_encoding}"
  puts "Content-language: #{file.content_language}"
  puts "KmsKeyName: #{file.kms_key}"
  puts "Event-based hold enabled?: #{file.event_based_hold?}"
  puts "Temporary hold enaled?: #{file.temporary_hold?}"
  puts "Retention Expiration: #{file.retention_expires_at}"
  puts "Custom Time: #{file.custom_time}"
  puts "Metadata:"
  file.metadata.each do |key, value|
    puts " - #{key} = #{value}"
  end
end

Terraform

Terraform 리소스를 사용하여 객체의 메타데이터를 볼 수 있습니다.

# Get object metadata
data "google_storage_bucket_object" "default" {
  name   = google_storage_bucket_object.default.name
  bucket = google_storage_bucket.static.id
}

output "object_metadata" {
  value = data.google_storage_bucket_object.default
}

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 GET 객체 요청으로 JSON API를 호출합니다.

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • BUCKET_NAME은 메타데이터를 보려는 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • OBJECT_NAME은 메타데이터를 보려는 객체의 URL로 인코딩된 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

XML API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. cURL을 사용하여 HEAD 객체 요청으로 XML API를 호출합니다.

    curl -I HEAD \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    각 항목의 의미는 다음과 같습니다.

    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰입니다.
    • BUCKET_NAME은 메타데이터를 보려는 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • OBJECT_NAME은 메타데이터를 보려는 객체의 URL로 인코딩된 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

객체 메타데이터 수정

객체와 연관된 메타데이터를 수정하려면 다음 단계를 완료합니다.

콘솔

  1. Google Cloud 콘솔에서 Cloud Storage 버킷 페이지로 이동합니다.

    버킷으로 이동

  2. 버킷 목록에서 메타데이터를 수정하려는 객체가 포함된 버킷의 이름을 클릭합니다.

    객체 탭이 선택된 상태로 버킷 세부정보 페이지가 열립니다.

  3. 객체(폴더에 있을 수 있음)로 이동합니다.

  4. 객체의 이름을 클릭합니다.

    객체 세부정보 페이지가 열리고 객체 메타데이터가 표시됩니다.

  5. 수정할 메타데이터에 연결된 연필 아이콘이 페이지에 표시되면 클릭합니다.

  6. 그렇지 않으면 메타데이터 수정을 클릭하여 수정 가능한 추가 메타데이터에 액세스합니다.

    오버레이 창이 나타나면 필요에 따라 메타데이터를 수정합니다.

    • 표준 메타데이터 필드의 경우 을 수정하세요.

    • 항목 추가 버튼을 클릭하여 나만의 커스텀 메타데이터를 추가하세요.

    • 커스텀 메타데이터의 을 모두 수정할 수 있습니다.

    • 연결된 X를 클릭하여 커스텀 메타데이터를 삭제하세요.

    오버레이 창에서 메타데이터 수정을 완료했으면 저장을 클릭합니다.

Google Cloud 콘솔에서 실패한 Cloud Storage 작업에 대한 자세한 오류 정보를 가져오는 방법은 문제 해결을 참조하세요.

명령줄

gcloud storage objects update 명령어를 사용합니다.

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME METADATA_FLAG

각 항목의 의미는 다음과 같습니다.

  • BUCKET_NAME은 메타데이터를 수정하려는 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
  • OBJECT_NAME은 메타데이터를 수정하려는 객체의 이름입니다. 예를 들면 pets/dog.png입니다.
  • METADATA_FLAG는 수정하려는 메타데이터의 플래그입니다. 예를 들면 --content-type=image/png입니다.

성공하면 응답은 다음 예시와 같습니다.

Patching gs://my-bucket/pets/dog.png#1560574162144861...
  Completed 1

이 명령어로 업데이트할 수 있는 메타데이터의 전체 목록은 명령어 참조 페이지를 확인하세요.

클라이언트 라이브러리

C++

자세한 내용은 Cloud Storage C++ API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& key,
   std::string const& value) {
  StatusOr<gcs::ObjectMetadata> object_metadata =
      client.GetObjectMetadata(bucket_name, object_name);
  if (!object_metadata) throw std::move(object_metadata).status();

  gcs::ObjectMetadata desired = *object_metadata;
  desired.mutable_metadata().emplace(key, value);

  StatusOr<gcs::ObjectMetadata> updated =
      client.UpdateObject(bucket_name, object_name, desired,
                          gcs::Generation(object_metadata->generation()));

  if (!updated) throw std::move(updated).status();
  std::cout << "Object updated. The full metadata after the update is: "
            << *updated << "\n";
}

C#

자세한 내용은 Cloud Storage C# API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Cloud.Storage.V1;
using System;
using System.Collections.Generic;

public class SetObjectMetadataSample
{
    public Google.Apis.Storage.v1.Data.Object SetObjectMetadata(
        string bucketName = "your-bucket-name",
        string objectName = "your-object-name",
        string key = "key-to-add",
        string value = "value-to-add")
    {
        var storage = StorageClient.Create();
        var file = storage.GetObject(bucketName, objectName);

        if (file.Metadata == null)
        {
            file.Metadata = new Dictionary<string, string>();
        }
        file.Metadata.Add(key, value);

        file = storage.UpdateObject(file);
        Console.WriteLine($"Updated custom metadata for object {objectName} in bucket {bucketName}");
        return file;
    }
}

Go

자세한 내용은 Cloud Storage Go API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// setMetadata sets an object's metadata.
func setMetadata(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	o := client.Bucket(bucket).Object(object)

	// Optional: set a metageneration-match precondition to avoid potential race
	// conditions and data corruptions. The request to update is aborted if the
	// object's metageneration does not match your precondition.
	attrs, err := o.Attrs(ctx)
	if err != nil {
		return fmt.Errorf("object.Attrs: %w", err)
	}
	o = o.If(storage.Conditions{MetagenerationMatch: attrs.Metageneration})

	// Update the object to set the metadata.
	objectAttrsToUpdate := storage.ObjectAttrsToUpdate{
		Metadata: map[string]string{
			"keyToAddOrUpdate": "value",
		},
	}
	if _, err := o.Update(ctx, objectAttrsToUpdate); err != nil {
		return fmt.Errorf("ObjectHandle(%q).Update: %w", object, err)
	}
	fmt.Fprintf(w, "Updated custom metadata for object %v in bucket %v.\n", object, bucket)
	return nil
}

Node.js

자세한 내용은 Cloud Storage Node.js API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

async function setFileMetadata() {
  // Optional: set a meta-generation-match precondition to avoid potential race
  // conditions and data corruptions. The request to set metadata is aborted if the
  // object's metageneration number does not match your precondition.
  const options = {
    ifMetagenerationMatch: metagenerationMatchPrecondition,
  };

  // Set file metadata.
  const [metadata] = await storage
    .bucket(bucketName)
    .file(fileName)
    .setMetadata(
      {
        // Predefined metadata for server e.g. 'cacheControl', 'contentDisposition',
        // 'contentEncoding', 'contentLanguage', 'contentType'
        contentDisposition:
          'attachment; filename*=utf-8\'\'"anotherImage.jpg"',
        contentType: 'image/jpeg',

        // A note or actionable items for user e.g. uniqueId, object description,
        // or other useful information.
        metadata: {
          description: 'file description...',
          modified: '1900-01-01',
        },
      },
      options
    );

  console.log(
    'Updated metadata for object',
    fileName,
    'in bucket ',
    bucketName
  );
  console.log(metadata);
}

setFileMetadata().catch(console.error);

PHP

자세한 내용은 Cloud Storage PHP API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Storage\StorageClient;

/**
 * Set a metadata key and value on the specified object.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 */
function set_metadata(string $bucketName, string $objectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->update([
        'metadata' => [
            'keyToAddOrUpdate' => 'value',
        ]
    ]);

    printf('Updated custom metadata for object %s in bucket %s', $objectName, $bucketName);
}

Python

자세한 내용은 Cloud Storage Python API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import storage


def set_blob_metadata(bucket_name, blob_name):
    """Set a blob's metadata."""
    # bucket_name = 'your-bucket-name'
    # blob_name = 'your-object-name'

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.get_blob(blob_name)
    metageneration_match_precondition = None

    # Optional: set a metageneration-match precondition to avoid potential race
    # conditions and data corruptions. The request to patch is aborted if the
    # object's metageneration does not match your precondition.
    metageneration_match_precondition = blob.metageneration

    metadata = {'color': 'Red', 'name': 'Test'}
    blob.metadata = metadata
    blob.patch(if_metageneration_match=metageneration_match_precondition)

    print(f"The metadata for the blob {blob.name} is {blob.metadata}")

Ruby

자세한 내용은 Cloud Storage Ruby API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

def set_metadata bucket_name:, file_name:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name, skip_lookup: true
  file    = bucket.file file_name

  file.update do |file|
    # Fixed key file metadata
    file.content_type = "text/plain"

    # Custom file metadata
    file.metadata["your-metadata-key"] = "your-metadata-value"
  end

  puts "Metadata for #{file_name} has been updated."
end

Java

자세한 내용은 Cloud Storage Java API 참고 문서를 확인하세요.

Cloud Storage에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.HashMap;
import java.util.Map;

public class SetObjectMetadata {
  public static void setObjectMetadata(String projectId, String bucketName, String objectName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Map<String, String> newMetadata = new HashMap<>();
    newMetadata.put("keyToAddOrUpdate", "value");
    BlobId blobId = BlobId.of(bucketName, objectName);
    Blob blob = storage.get(blobId);
    if (blob == null) {
      System.out.println("The object " + objectName + " was not found in " + bucketName);
      return;
    }

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request to upload returns a 412 error if
    // the object's generation number does not match your precondition.
    Storage.BlobTargetOption precondition = Storage.BlobTargetOption.generationMatch();

    // Does an upsert operation, if the key already exists it's replaced by the new value, otherwise
    // it's added.
    blob.toBuilder().setMetadata(newMetadata).build().update(precondition);

    System.out.println(
        "Updated custom metadata for object " + objectName + " in bucket " + bucketName);
  }
}

REST API

JSON API

  1. OAuth 2.0 Playground에서 승인 액세스 토큰을 가져옵니다. 자체 OAuth 사용자 인증 정보를 사용하도록 Playground를 구성합니다. 자세한 내용은 API 인증을 참조하세요.
  2. 수정하려는 메타데이터가 포함된 JSON 파일을 만듭니다.

    contentType과 같은 고정 키 메타데이터를 추가하거나 수정하려면 다음 형식을 사용하세요.

    {
      "STANDARD_METADATA_KEY": "STANDARD_METADATA_VALUE"
    }

    각 항목의 의미는 다음과 같습니다.

    • STANDARD_METADATA_KEY는 추가하거나 수정할 메타데이터의 키입니다. 예를 들면 Content-Type입니다.
    • STANDARD_METADATA_VALUE는 추가하거나 수정할 메타데이터의 값입니다. 예를 들면 image/png입니다.

    커스텀 메타데이터를 추가하거나 수정하려면 다음 형식을 사용하세요.

    {
      "metadata": {
        "CUSTOM_METADATA_KEY": "CUSTOM_METADATA_VALUE"
      }
    }

    각 항목의 의미는 다음과 같습니다.

    • CUSTOM_METADATA_KEY는 추가하거나 수정할 커스텀 메타데이터 키입니다. 예를 들면 dogbreed입니다.
    • CUSTOM_METADATA_VALUE는 커스텀 메타데이터 키에 연결할 값입니다. 예를 들면 shibainu입니다.

    커스텀 메타데이터 항목을 삭제하려면 다음 형식을 사용하세요.

    {
      "metadata": {
        "CUSTOM_METADATA_KEY": null
      }
    }

    각 항목의 의미는 다음과 같습니다.

    • CUSTOM_METADATA_KEY는 삭제할 커스텀 메타데이터의 키입니다. 예를 들면 dogbreed입니다.
  3. cURL을 사용하여 PATCH 객체 요청으로 JSON API를 호출합니다.

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME"

    각 항목의 의미는 다음과 같습니다.

    • JSON_FILE_NAME은 2단계에서 만든 파일의 경로입니다.
    • OAUTH2_TOKEN은 1단계에서 생성한 액세스 토큰의 이름입니다.
    • BUCKET_NAME은 메타데이터를 수정하려는 객체가 포함된 버킷의 이름입니다. 예를 들면 my-bucket입니다.
    • OBJECT_NAME은 메타데이터를 수정하려는 객체의 URL로 인코딩된 이름입니다. 예를 들어 pets/dog.pngpets%2Fdog.png로 URL 인코딩됩니다.

UPDATE 객체 요청을 사용하여 객체의 메타데이터를 변경할 수도 있습니다. 이 방법을 사용하면 요청에 명시적으로 지정되지 않은 모든 메타데이터가 객체의 메타데이터에서 삭제됩니다.

XML API

XML API를 사용할 때는 객체를 업로드, 이동 또는 교체할 때처럼 객체를 쓰는 시점에만 메타데이터를 설정할 수 있습니다. 다음 가이드라인과 더불어 객체 업로드와 같은 안내를 따르세요.

  • 설정 중인 각 메타데이터 값의 요청 헤더에 -H "METADATA_KEY:METADATA_VALUE"를 추가하세요. 예를 들면 -H "Content-Type:image/png"입니다.

  • 모든 커스텀 메타데이터 값에 프리픽스 x-goog-meta-를 추가하세요. 커스텀 "METADATA_KEY:METADATA_VALUE"의 예시는 "x-goog-meta-dogbreed:shibainu"입니다.

자세한 내용은 XML용 객체 업로드를 참조하세요.

다음 단계