필터를 사용해 애셋 그룹화

애셋을 유형별로 필터링하고 그룹화하는 방법을 보여줍니다.

코드 샘플

Java

Security Command Center에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

static ImmutableList<GroupResult> groupAssetsWithFilter(OrganizationName organizationName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // Start setting up a request to filter all assets by type and group them by project in an
    // organization.
    // You can also use a project or folder as a parent resource and filter assets in them
    // respectively.
    GroupAssetsRequest.Builder request =
        GroupAssetsRequest.newBuilder()
            .setFilter(
                "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"")
            .setGroupBy("security_center_properties.resource_project")
            .setParent(organizationName.toString());

    // Call the API.
    GroupAssetsPagedResponse response = client.groupAssets(request.build());

    // This creates one list for all assets.  If your organization has a large number of assets
    // this can cause out of memory issues.  You can process them batches by returning
    // the Iterable returned response.iterateAll() directly.
    ImmutableList<GroupResult> results = ImmutableList.copyOf(response.iterateAll());
    System.out.println("All assets:");
    System.out.println(results);
    return results;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Python

Security Command Center에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import securitycenter

client = securitycenter.SecurityCenterClient()

# 'organization_id' is the numeric ID of the organization.
# organization_id = "1234567777"
org_name = f"organizations/{organization_id}"

group_by_type = "security_center_properties.resource_type"
only_projects = (
    "security_center_properties.resource_type="
    + '"google.cloud.resourcemanager.Project"'
)
# You can also use a project/ folder as a parent resource and filter assets in them
# respectively.
result_iterator = client.group_assets(
    request={"parent": org_name, "group_by": group_by_type, "filter": only_projects}
)
for i, result in enumerate(result_iterator):
    print((i + 1), result)

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.