【问题标题】:List buckets that match a bucket label with gsutil使用 gsutil 列出与存储桶标签匹配的存储桶
【发布时间】:2019-06-17 07:21:18
【问题描述】:

我标记了我的谷歌云存储桶

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

【问题讨论】:

  • 这样的痛苦。您通过具有高级过滤功能的 gcloud 与之交互的所有其他 gcp 资源

标签: google-cloud-platform gsutil


【解决方案1】:

刚刚有一个用例,我想列出所有带有特定标签的存储桶。使用 subprocess 接受的答案对我来说明显很慢。这是我使用 Cloud Storage 的 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

【讨论】:

    【解决方案2】:

    现在不可能一步完成你想做的事情。您可以分 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)
    

    【讨论】:

      【解决方案3】:

      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 函数返回多个值比它的价值更麻烦。如果您需要使用多个存储桶,那么我会将 echo 替换为需要运行的代码。

      【讨论】:

        【解决方案4】:
        from google.cloud import storage
        
        client = storage.Client()
        for blob in client.list_blobs('bucketname', prefix='xjc/folder'):
          print(str(blob))
        

        【讨论】:

          猜你喜欢
          • 2020-07-22
          • 2018-11-04
          • 2021-01-19
          • 2017-10-30
          • 2021-02-05
          • 1970-01-01
          • 1970-01-01
          • 2019-01-07
          • 2020-02-25
          相关资源
          最近更新 更多