Search code examples
pythongoogle-cloud-platformtagsgoogle-iampolicies

How to programmatically add tags to a GCP dataset


Have no ideas how to programmatically add tags to a GCP dataset Ad Tag. I can create and manage tagKeys&tagValues, can add conditions to policies but I can't get how to add tags to dataset using Python:

Can't find any information in GCP documentation


Solution

  • You have to use the CloudResourceManager API to manage the TAGS. By API, you can do like that

    My dataset is in multiregion US

    curl -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json" -X POST \
     -d '{"parent":"//bigquery.googleapis.com/projects/gdglyon-cloudrun/datasets/dlp_test","tagValue":"tagValues/252755946221"}' \
     "https://us-cloudresourcemanager.googleapis.com/v3/tagBindings"
    

    I tried to use the CloudResourceManager client library. And it's not very easy (and I'm bad at Python). But that piece of code works

        from google.cloud import resourcemanager_v3
    
        location = "us"
        # Create a client
        api_endpoint, _ = resourcemanager_v3.TagBindingsClient.get_mtls_endpoint_and_cert_source()    
        client = resourcemanager_v3.TagBindingsClient(client_options={"api_endpoint": location + "-" + api_endpoint})
    
    
        # Initialize request argument(s)
        request = resourcemanager_v3.CreateTagBindingRequest()
        request.tag_binding.parent = "//bigquery.googleapis.com/projects/gdglyon-cloudrun/datasets/dlp_test"
        request.tag_binding.tag_value = "tagValues/252755946221"
    
        # Make the request
        operation = client.create_tag_binding(request=request)
    
        print("Waiting for operation to complete...")
    
        response = operation.result()
    
        # Handle the response
        print(response)
    

    Note that I had to get the API endpoint from the client, and then create the client with a hack on the api-endpoint. Indeed, for local resources, you have to use the cloud resource manager API in that same location. But I didn't find a clean way to achieve that with the client library!