如何在Python代码中使用google-cloud-os-config类获取VM合规状态
实现方案修正
方案1:使用官方原生 google-cloud-os-config 客户端库
你第一版代码的问题有3处:
- 没有正确实例化客户端对象,直接导入的
client是模块不是可调用的客户端实例 parent参数拼接时变量名错误,你定义的变量是project_id,但格式化字符串里写的是project- 没有处理分页逻辑,单页返回结果上限默认是100条,超过的结果会丢失
修正后的可运行代码如下:
from google.cloud.osconfig_v1alpha.services.os_config_zonal_service import OsConfigZonalServiceClient from google.cloud.osconfig_v1alpha.types import ListInstanceOSPoliciesCompliancesRequest import logging import os logger = logging.getLogger(__name__) def handler(request): try: project_id = os.environ["PROJECT_ID"] location = os.environ["ZONE"] client = OsConfigZonalServiceClient() all_compliance_records = [] page_token = "" # 分页拉取所有合规记录 while True: request = ListInstanceOSPoliciesCompliancesRequest( parent=f"projects/{project_id}/locations/{location}", page_size=1000, page_token=page_token ) response = client.list_instance_os_policies_compliances(request) all_compliance_records.extend(response.instance_os_policies_compliances) if not response.next_page_token: break page_token = response.next_page_token # 按需处理返回字段,比如转为字典格式 return {"compliance_records": [dict(record) for record in all_compliance_records]} except Exception as e: logger.error(f"获取合规状态失败: {str(e)}") return {"error": str(e)}, 500
你需要在requirements.txt中添加依赖:google-cloud-os-config>=1.13.0
方案2:使用 googleapiclient 通用客户端库
你第二版的代码逻辑是通顺的,只需做适配云函数、分页、错误处理的优化即可:
from googleapiclient.discovery import build import logging import os logger = logging.getLogger(__name__) def handler(request): project_id = os.environ["PROJECT_ID"] zone = os.environ["ZONE"] all_compliance_records = [] page_token = "" try: service = build('osconfig', 'v1alpha', cache_discovery=False) while True: response = service.projects().locations().instanceOsPoliciesCompliances().list( parent=f'projects/{project_id}/locations/{zone}', pageSize=1000, pageToken=page_token ).execute() if "instanceOsPoliciesCompliances" in response: all_compliance_records.extend(response["instanceOsPoliciesCompliances"]) page_token = response.get("nextPageToken") if not page_token: break return {"compliance_records": all_compliance_records} except Exception as e: logger.error(f"获取合规状态失败: {str(e)}") return {"error": str(e)}, 500
你需要在requirements.txt中添加依赖:google-api-python-client>=2.80.0
注意事项
- 云函数绑定的服务账号需要授予
OS Config Viewer角色,否则会报权限拒绝错误 - 当前使用的
v1alpha版本是预览版接口,后续正式版发布后可能会有字段或方法的调整 - 如果你只需要过滤特定状态的合规记录,可以在请求参数中添加
filter字段,比如筛选不合规的记录:filter="state=NON_COMPLIANT"
内容的提问来源于stack exchange,提问作者Kishori
相关产品推荐
相关产品推荐

