상태 변경으로 애셋을 나열하는 방법을 보여줍니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
Go
Security Command Center에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
import (
"context"
"fmt"
"io"
"time"
securitycenter "cloud.google.com/go/securitycenter/apiv1"
"cloud.google.com/go/securitycenter/apiv1/securitycenterpb"
"github.com/golang/protobuf/ptypes"
"google.golang.org/api/iterator"
)
// listAllProjectAssetsAndStateChange lists all current GCP project assets in
// orgID and prints the projects and there change from a day ago out to w.
// orgID is the numeric // organization ID of interest.
func listAllProjectAssetsAndStateChanges(w io.Writer, orgID string) error {
// orgID := "12321311"
// Instantiate a context and a security service client to make API calls.
ctx := context.Background()
client, err := securitycenter.NewClient(ctx)
if err != nil {
return fmt.Errorf("securitycenter.NewClient: %w", err)
}
defer client.Close() // Closing the client safely cleans up background resources.
req := &securitycenterpb.ListAssetsRequest{
// Parent must be in one of the following formats:
// "organizations/{orgId}"
// "projects/{projectId}"
// "folders/{folderId}"
Parent: fmt.Sprintf("organizations/%s", orgID),
Filter: `security_center_properties.resource_type="google.cloud.resourcemanager.Project"`,
CompareDuration: ptypes.DurationProto(24 * time.Hour),
}
assetsFound := 0
it := client.ListAssets(ctx, req)
for {
result, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return fmt.Errorf("ListAssets: %w", err)
}
asset := result.Asset
properties := asset.SecurityCenterProperties
fmt.Fprintf(w, "Asset Name: %s,", asset.Name)
fmt.Fprintf(w, "Resource Name %s,", properties.ResourceName)
fmt.Fprintf(w, "Resource Type %s", properties.ResourceType)
fmt.Fprintf(w, "State Change %s\n", result.StateChange)
assetsFound++
}
return nil
}
Java
Security Command Center에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
static ImmutableList<ListAssetsResult> listAssetAndStatusChanges(
OrganizationName organizationName, Duration timeSpan, Instant asOf) {
try (SecurityCenterClient client = SecurityCenterClient.create()) {
// Start setting up a request to search for all assets in an organization, project, or folder.
//
// Parent must be in one of the following formats:
// OrganizationName organizationName = OrganizationName.of("organization-id");
// ProjectName projectName = ProjectName.of("project-id");
// FolderName folderName = FolderName.of("folder-id");
ListAssetsRequest.Builder request =
ListAssetsRequest.newBuilder()
.setParent(organizationName.toString())
.setFilter(
"security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");
request
.getCompareDurationBuilder()
.setSeconds(timeSpan.getSeconds())
.setNanos(timeSpan.getNano());
// Set read time to either the instant passed in or now.
asOf = MoreObjects.firstNonNull(asOf, Instant.now());
request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano());
// Call the API.
ListAssetsPagedResponse response = client.listAssets(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 incrementally by returning
// the Iterable returned response.iterateAll() directly.
ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
System.out.println("Projects:");
System.out.println(results);
return results;
} catch (IOException e) {
throw new RuntimeException("Couldn't create client.", e);
}
}
Node.js
Security Command Center에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');
// Creates a new client.
const client = new SecurityCenterClient();
// organizationId is the numeric ID of the organization.
/*
* TODO(developer): Uncomment the following lines
*/
// parent: must be in one of the following formats:
// `organizations/${organization_id}`
// `projects/${project_id}`
// `folders/${folder_id}`
const parent = `organizations/${organizationId}`;
// Call the API with automatic pagination.
async function listAssetsAndChanges() {
const [response] = await client.listAssets({
parent: parent,
compareDuration: {seconds: 30 * /*Second in Day=*/ 86400, nanos: 0},
filter:
'security_center_properties.resource_type="google.cloud.resourcemanager.Project"',
});
let count = 0;
Array.from(response).forEach(result =>
console.log(
`${++count} ${result.asset.name} ${
result.asset.securityCenterProperties.resourceName
} ${result.stateChange}`
)
);
}
listAssetsAndChanges();
Python
Security Command Center에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
from datetime import timedelta
from google.cloud import securitycenter
client = securitycenter.SecurityCenterClient()
# 'parent' must be in one of the following formats:
# "organizations/{organization_id}"
# "projects/{project_id}"
# "folders/{folder_id}"
parent = f"organizations/{organization_id}"
project_filter = (
"security_center_properties.resource_type="
+ '"google.cloud.resourcemanager.Project"'
)
# List assets and their state change the last 30 days
compare_delta = timedelta(days=30)
# Call the API and print results.
asset_iterator = client.list_assets(
request={
"parent": parent,
"filter": project_filter,
"compare_duration": compare_delta,
}
)
for i, asset in enumerate(asset_iterator):
print(i, asset)
다음 단계
다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.