Created
June 3, 2022 15:27
-
-
Save Neutrollized/34c9cb189ed25739b91f62b77d53d121 to your computer and use it in GitHub Desktop.
Medium: Managing your GCP inventory with Cloud Asset API (export_assets)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
from google.cloud import asset_v1 | |
def export_assets(event, context): | |
# create client | |
client = asset_v1.AssetServiceClient() | |
print("""This Function was triggered by messageId {} published at {} to {} | |
""".format(context.event_id, context.timestamp, context.resource["name"])) | |
# bq partition spec | |
# PARTITION_KEY_UNSPECIFIED = 0 | |
# READ_TIME = 1 | |
# REQUEST_TIME = 2 | |
partition_spec = asset_v1.PartitionSpec() | |
partition_spec.partition_key = 1 | |
# init request | |
output_config = asset_v1.OutputConfig() | |
output_config.bigquery_destination.dataset = "projects/myproject-123/datasets/cloud_assets" | |
output_config.bigquery_destination.table = "data" | |
output_config.bigquery_destination.force = True | |
output_config.bigquery_destination.parition_spec = partition_spec | |
request = asset_v1.ExportAssetsRequest( | |
parent = "projects/myproject-123", | |
content_type = "RESOURCE", | |
asset_types = [ | |
".*.googleapis.com.*Cluster", | |
".*.googleapis.com.*Instance", | |
"cloudfunctions.googleapis.com/CloudFunction", | |
"compute.googleapis.com/ForwardingRule", | |
"compute.googleapis.com/VpnTunnel", | |
"container.googleapis.com.*", | |
"iam.googleapis.com.*", | |
"storage.googleapis.com/Bucket", | |
], | |
output_config = output_config, | |
) | |
# make request | |
operation = client.export_assets(request=request) | |
msg_body = base64.b64decode(event['data']).decode('utf-8') | |
print('Exporting: {}'.format(msg_body)) | |
response = operation.result() | |
# handle response | |
print(response) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment