Linked Questions

Popular Questions

I create the python file to save the data to firestore and code cloud build to write CICD.

I can run python file in local successfully. But, it failed in cloud build.

It shows error

403 Missing or insufficient permissions.

enter image description here

cloudbuild.yaml

  - name: 'python:3.9'
    entrypoint: /bin/sh
    args:
      - '-c'
      - 'pip install -r ./functions/requirements.txt && python3 ./functions/main.py'
      #- 'python3 ./tools/main.py'
    env:
      - 'env=${_ENV}'

main.py

from google.cloud import firestore
import json
import os
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

def tmp():
    # Initialize Firestore client
    env = os.environ.get("env", "local")
    print("env: ", env)
    filename = "config-sit.json"
    project_id = "x-A"
    if env == "uat":
        filename = "config-uat.json"
        project_id = "x-dev-A"
    elif env == "production":
        filename = "config-prod.json"
        project_id = "u-dev-A"

    cred = credentials.ApplicationDefault()
    firebase_admin.initialize_app(cred, {
            'projectId': project_id, # prod
    })
    try:
        #with open(f"../functions/config/{filename}", "r") as f:
        with open(f"./functions/config/{filename}", "r") as f:
            data = json.load(f)
    except Exception as e:
        error_message = f"Error reading {filename}: {str(e)}"
        print(error_message)
        return {"error": error_message}

    # Initialize Firestore client
    try:
        #client = firestore.Client(project=project_id, credentials=creds)
        client = firestore.client()
    except Exception as e:
        error_message = f"Error initializing Firestore client: {str(e)}"
        print(error_message)
        return {"error": error_message}

    # Update Firestore with the config data
    for item in data:
        try:
            doc_ref = client.collection("test").document(item["id"])
            doc_ref.set(item["data"])
        except Exception as e:
            error_message = f"Error updating Firestore with {item['id']}: {str(e)}"
            print(error_message)
            return {"error": error_message}

    # Return a response
    response_data = {"message": "Update complete."}
    print("response_data",response_data)
    return response_data

tmp()

Related Questions