【发布时间】:2019-06-17 07:21:18
【问题描述】:
我标记了我的谷歌云存储桶
我在文档中找不到任何关于如何执行 gsutil ls 但只能过滤具有特定标签的存储桶的内容 - 这可能吗?
【问题讨论】:
-
这样的痛苦。您通过具有高级过滤功能的 gcloud 与之交互的所有其他 gcp 资源
标签: google-cloud-platform gsutil
我标记了我的谷歌云存储桶
我在文档中找不到任何关于如何执行 gsutil ls 但只能过滤具有特定标签的存储桶的内容 - 这可能吗?
【问题讨论】:
标签: google-cloud-platform gsutil
刚刚有一个用例,我想列出所有带有特定标签的存储桶。使用 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
【讨论】:
现在不可能一步完成你想做的事情。您可以分 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 函数返回多个值比它的价值更麻烦。如果您需要使用多个存储桶,那么我会将 echo 替换为需要运行的代码。
【讨论】: