Sample Code

Sample Code

This code uses Google Cloud APIs to illustrate how you can ensure labeling on every persistent disk created for your project, applying principles from Chapter 11.


import googleapiclient.discovery
import logging
import base64
import json

def set_datatype_label_as_pii(client, labels,
    fingerprint, project, zone, resource):
    # update current label set to include our specific key/value pair
    labels["datatype"] = "pii"
    # build request body for setLabels API
    label={
        "labels": labels,
        "labelFingerprint": fingerprint
    }
    logging.warn("Adding datatype label to disk: "+resource)
    request = client.disks().setLabels(project=project, zone=zone,
        resource=resource, body=label)
    response = request.execute()

def check_disk_label(event, context):
    """
    On receipt of an GCE Disk audit log fragment (received via log
    sink + pub/sub), this function applies continuous compliance
    by confirming a "datatype" label has been applied with the
    value of "pii" or "no_pii".
    """
    body = json.loads(base64.b64decode(event['data']).decode('utf-8'))
    if "resource" in body:
        disk_id = body["resource"]["labels"]["disk_id"]
        zone = body["resource"]["labels"]["zone"]
        project = body["resource"]["labels"]["project_id"]
        # build API to communicate with GCE
        service = googleapiclient.discovery.build('compute', 'v1')
        # request full disk information, including labels
        disk = service.disks().get(project=project, zone=zone,
            disk=disk_id).execute()
        # save labelFingerprint as we will need to provide them it to the API ...

Get A Practical Guide to Cloud Migration now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.