google-cloud-functionsgoogle-secret-manager

Event based cloud function(python) in accessing the secrets


I need to implement pubsub event based cloud function along with secrets. Secret contains database password. I need to use the db credentials in processing the data received in pubsub.

I am trying to access the db password from secret and to be used in hello_pubsub. I am new to secrets topic and here is my code. It's not working.

import base64
import json
import os
import datetime
from google.cloud import secretmanager

client = secretmanager.SecretManagerServiceClient()
secret_name = "my_db_password"
project_id = "project_id"
request = {"name": f"projects/{project_id}/secrets/{secret_name}/versions/latest"}
response = client.access_secret_version(request)
secret_string = response.payload.data.decode("UTF-8")

def secret_hello(request):
    return secret_string
    
def hello_pubsub(event, context):
    """Triggered from a message on a Cloud Pub/Sub topic.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for the event.
    """
    print("""This Function was triggered by messageId {} published at {} to {}
    """.format(
            context.event_id, context.timestamp, context.resource["name"]
        )
    )
    print(event)
    print(context)
:

Solution

  • Here is my working code. I can access my secret value in hello_pubsub function.

    from google.cloud import storage
    import base64
    import json
    import os
    import datetime
    from google.cloud import secretmanager
    
    def hello_pubsub(event, context):
        """Triggered from a message on a Cloud Pub/Sub topic.
        Args:
             event (dict): Event payload.
             context (google.cloud.functions.Context): Metadata for the event.
        """
        client = secretmanager.SecretManagerServiceClient()
        secret_name = "my_secret"
        project_id = "997217777776"
        request = {"name": f"projects/{project_id}/secrets/{secret_name}/versions/latest"}
        response = client.access_secret_version(request)
        secret_string = response.payload.data.decode("UTF-8")
        print(secret_string)
        
        pubsub_message = base64.b64decode(event['data']).decode('utf-8')
        #print(pubsub_message)
    :