Create a Cloud Functions trigger that reads the data in the Cloud Pub/Sub topic and that stops any Shielded VM instance that fails integrity validation.
-
The following code defines the Cloud Functions trigger. Copy it into a file named main.py.
import base64
import json
import googleapiclient.discovery
def shutdown_vm(data, context):
"""A Cloud Function that shuts down a VM on failed integrity check."""
log_entry = json.loads(base64.b64decode(data['data']).decode('utf-8'))
payload = log_entry.get('jsonPayload', {})
entry_type = payload.get('@type')
if entry_type != 'type.googleapis.com/cloud_integrity.IntegrityEvent':
raise TypeError("Unexpected log entry type: %s" % entry_type)
report_event = (payload.get('earlyBootReportEvent')
or payload.get('lateBootReportEvent'))
if report_event is None:
# We received a different event type, ignore.
return
policy_passed = report_event['policyEvaluationPassed']
if not policy_passed:
print('Integrity evaluation failed: %s' % report_event)
print('Shutting down the VM')
instance_id = log_entry['resource']['labels']['instance_id']
project_id = log_entry['resource']['labels']['project_id']
zone = log_entry['resource']['labels']['zone']
# Shut down the instance.
compute = googleapiclient.discovery.build(
'compute', 'v1', cache_discovery=False)
# Get the instance name from instance id.
list_result = compute.instances().list(
project=project_id,
zone=zone,
filter='id eq %s' % instance_id).execute()
if len(list_result['items']) != 1:
raise KeyError('unexpected number of items: %d'
% len(list_result['items']))
instance_name = list_result['items'][0]['name']
result = compute.instances().stop(project=project_id,
zone=zone,
instance=instance_name).execute()
print('Instance %s in project %s has been scheduled for shut down.'
% (instance_name, project_id))
-
In the same location as main.py, create a file named requirements.txt and copy in the following dependencies:
google-api-python-client==1.6.6
google-auth==1.4.1
google-auth-httplib2==0.0.3
-
Open a terminal window and navigate to the directory containing main.py and requirements.txt.
-
Run the gcloud beta functions deploy command to deploy the trigger:
gcloud beta functions deploy shutdown_vm --project YOUR_PROJECT_ID \
--runtime python37 --trigger-resource integrity-monitoring \
--trigger-event google.pubsub.topic.publish
replacing YOUR_PROJECT_ID with the ID of your project.
Hope this helped!!
To know more about Google Cloud, It is recommended to go for Google Cloud Certification training today.
Thank you!