zyo zyo
zyo zyo

Reputation: 5

How to change the metadata of all specific file of exist objects in Google Cloud Storage?

I have uploaded thousands of files to google storage, and i found out all the files miss content-type,so that my website cannot get it right.

i wonder if i can set some kind of policy like changing all the files content-type at the same time, for example, i have bunch of .html files inside the bucket

a/b/index.html
a/c/a.html
a/c/a/b.html
a/a.html
.
.
.

is that possible to set the content-type of all the .html files with one command in the different place?

Upvotes: 0

Views: 1125

Answers (2)

Mike Schwartz
Mike Schwartz

Reputation: 12145

You could do:

gsutil -m setmeta -h Content-Type:text/html gs://your-bucket/**.html

Upvotes: 1

Mayeru
Mayeru

Reputation: 1094

There's no a unique command to achieve the behavior you are looking for (one command to edit all the object's metadata) however, there's a command from gcloud to edit the metadata which you could use on a bash script to make a loop through all the objects inside the bucket.

1.- Option (1) is to use a the gcloud command "setmeta" on a bash script:

# kinda pseudo code here.

# get the list with all your object's names and iterate over the metadata edition command.

for OUTPUT in $(get_list_of_objects_names)
do

gsutil setmeta -h "[METADATA_KEY]:[METADATA_VALUE]" gs://[BUCKET_NAME]/[OBJECT_NAME]
# the "gs://[BUCKET_NAME]/[OBJECT_NAME]" would be your object name.

done

2.- You could also create a C++ script to achieve the same thing:

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name,
   std::string key, std::string value) {

# you would need to find list all the objects, while on the loop, you can edit the metadata of the object.

for (auto&& object_metadata : client.ListObjects(bucket_name)) {

  string bucket_name=object_metadata->bucket(), object_name=object_metadata->name();

  StatusOr<gcs::ObjectMetadata> object_metadata =
      client.GetObjectMetadata(bucket_name, object_name);

  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()))
}

}

Upvotes: 0

Related Questions