使用 gsutil 列出与存储桶标签匹配的存储桶

List buckets that match a bucket label with gsutil

我有我的 google 云存储桶标记

我在文档中找不到有关如何执行 gsutil ls 的任何内容,但只能过滤具有特定标签的存储桶 - 这可能吗?

现在不可能一步到位。您可以通过 3 个步骤完成:

  1. 正在获取您的 GCP 项目的所有存储桶。
  2. 获取每个桶的标签。
  3. 对满足您标准的每个存储桶执行 gsutil ls

这是我为你做的 python 3 代码。

import subprocess
out = subprocess.getoutput("gsutil ls")


for line in out.split('\n'):
    label = subprocess.getoutput("gsutil label get "+line)
    if "YOUR_LABEL" in str(label):
        gsout = subprocess.getoutput("gsutil ls "+line)
        print("Files in "+line+":\n")
        print(gsout)

一个bash唯一的解决方案:

function get_labeled_bucket {
  # list all of the buckets for the current project
  for b in $(gsutil ls); do
    # find the one with your label
    if gsutil label get "${b}" | grep -q '"key": "value"'; then
      # and return its name
      echo "${b}"
    fi
  done
}

'"key": "value"' 部分只是一个字符串,请用您的键和值替换。使用 LABELED_BUCKET=$(get_labeled_bucket)

调用函数

在我看来,让一个 bash 函数 return 多于一个值是比它值得的麻烦多了。如果您需要使用多个存储桶,那么我会将 echo 替换为需要 运行.

的代码
from google.cloud import storage

client = storage.Client()
for blob in client.list_blobs('bucketname', prefix='xjc/folder'):
  print(str(blob))

刚刚有一个用例,我想列出所有带有特定标签的存储桶。使用子流程接受的答案对我来说明显很慢。这是我使用云存储的 Python 客户端库的解决方案:

from google.cloud import storage


def list_buckets_by_label(label_key, label_value):
    # List out buckets in your default project
    client = storage.Client()
    buckets = client.list_buckets() # Iterator

    # Only return buckets where the label key/value match inputs
    output = list()
    for bucket in buckets:
        if bucket.labels.get(label_key) == label_value:
            output.append(bucket.name)
    return output