在 GCP 中使用 asset_v1 Python 客户端“searching_all_resources”查找 SA 密钥时指定 keyType

问题描述 投票:0回答:1

我正在尝试利用 python 检索我的组织中的所有用户管理的服务帐户密钥,以下代码片段来自此文档

from google.cloud import asset_v1
import google.auth
import json

credentials, project = google.auth.default() 

asset = asset_v1.AssetServiceClient(credentials=credentials)
keys = asset.search_all_resources(
    scope="organizations/<your_organization_number>", 
    query="(createTime > 2024-03-20)",
    asset_types = ["iam.googleapis.com/ServiceAccountKey"], 
    )
for key in keys:
    print(key.display_name) 

以上运行成功。但是,它会返回 Google 提供的密钥,并且不会在此 API 调用的响应中区分用户管理的密钥和 Google 提供的密钥。您实际上可以通过运行以下代码片段来验证它们是 Google 提供的密钥:

import os
import google.auth
import googleapiclient.discovery

credentials, project = google.auth.default() 
service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)

keys = (
    service.projects()
    .serviceAccounts()
    .keys()
    .list(name="projects/-/serviceAccounts/<YOUR_SA_WITH_SA_KEYS>")
    .execute()
)
for key in keys["keys"]:
    print(key)
{'name': 'projects/-/serviceAccounts/your_sa.iam.gserviceaccount.com/keys/key0', 'validAfterTime': 'xxxx-xx-xxTxx:xx:xxZ', 'validBeforeTime': 'xxxx-xx-xxTxx:xx:xxZ', 'keyAlgorithm': 'KEY_ALG_RSA_2048', 'keyOrigin': 'GOOGLE_PROVIDED', 'keyType': 'SYSTEM_MANAGED'}
{'name': 'projects/-/serviceAccounts/your_sa.iam.gserviceaccount.com/keys/key1', 'validAfterTime': 'xxxx-xx-xxTxx:xx:xxZ', 'validBeforeTime': "xxxx-xx-xxTxx:xx:xxZ', 'keyAlgorithm': 'KEY_ALG_RSA_2048', 'keyOrigin': 'GOOGLE_PROVIDED', 'keyType': 'SYSTEM_MANAGED'}
{'name': 'projects/-/serviceAccounts/your_sa.iam.gserviceaccount.com/keys/key2', 'validAfterTime': 'xxxx-xx-xxTxx:xx:xxZ', 'validBeforeTime': 'xxxx-xx-xxTxx:xx:xxZ', 'keyOrigin': 'USER_PROVIDED', 'keyType': 'USER_MANAGED'}

是否有办法利用 查询参数在 search_all_resources 调用中排除 GOOGLE_PROVIDED keyOrigin 值以避免多个请求?

python google-cloud-platform google-api-python-client
1个回答
0
投票

我不知道这是否是您想要做的,但您可以尝试使用下面的代码。

import os
import google.auth
import googleapiclient.discovery

credentials, project = google.auth.default() 
service = googleapiclient.discovery.build("iam", "v1", credentials=credentials)

keys = (
    service.projects()
    .serviceAccounts()
    .keys()
    .list(name="projects/-/.list(name="projects/-/serviceAccounts/<YOUR_SA_WITH_SA_KEYS>")")
    .execute()
)
 
for key in keys['keys']:
    if key['keyType'] == 'USER_MANAGED':
            print(key['name'])
© www.soinside.com 2019 - 2024. All rights reserved.