Ir al contenido

Google Cloud Functions Cheat Sheet

Overview

Google Cloud Functions is a serverless execution environment for building and connecting cloud services. Functions are triggered by events from Google Cloud services, HTTP requests, or Pub/Sub messages, and scale automatically from zero to handle incoming load without provisioning or managing servers.

Cloud Functions supports Node.js, Python, Go, Java, .NET, Ruby, and PHP runtimes. It offers two generations: 1st gen (original) and 2nd gen (built on Cloud Run, with longer timeouts, larger instances, concurrency, and traffic splitting). Cloud Functions integrates with Eventarc for event-driven triggers from 90+ Google Cloud sources.

Installation

gcloud CLI Setup

# Install gcloud CLI
curl https://sdk.cloud.google.com | bash

# Initialize and authenticate
gcloud init
gcloud auth login

# Enable Cloud Functions API
gcloud services enable cloudfunctions.googleapis.com
gcloud services enable cloudbuild.googleapis.com
gcloud services enable run.googleapis.com  # for 2nd gen

Function Templates

HTTP Function (Node.js)

// index.js
const functions = require('@google-cloud/functions-framework');

functions.http('helloHttp', (req, res) => {
  const name = req.query.name || req.body.name || 'World';
  res.json({ message: `Hello, ${name}!` });
});
{
  "name": "my-function",
  "version": "1.0.0",
  "dependencies": {
    "@google-cloud/functions-framework": "^3.0.0"
  }
}

HTTP Function (Python)

# main.py
import functions_framework

@functions_framework.http
def hello_http(request):
    name = request.args.get('name', 'World')
    return f'Hello, {name}!'
# requirements.txt
functions-framework==3.*

Pub/Sub Triggered Function (Python)

import base64
import functions_framework
from cloudevents.http import CloudEvent

@functions_framework.cloud_event
def process_pubsub(cloud_event: CloudEvent):
    data = base64.b64decode(cloud_event.data["message"]["data"]).decode()
    print(f"Received message: {data}")

Cloud Storage Triggered Function (Node.js)

const functions = require('@google-cloud/functions-framework');

functions.cloudEvent('processFile', (cloudEvent) => {
  const file = cloudEvent.data;
  console.log(`File: ${file.name}`);
  console.log(`Bucket: ${file.bucket}`);
  console.log(`Event: ${cloudEvent.type}`);
});

Deployment Commands

Deploy 2nd Gen Functions

# Deploy HTTP function
gcloud functions deploy my-function \
  --gen2 \
  --runtime=nodejs20 \
  --region=us-central1 \
  --source=. \
  --entry-point=helloHttp \
  --trigger-http \
  --allow-unauthenticated \
  --memory=256MB \
  --timeout=60s

# Deploy Pub/Sub triggered function
gcloud functions deploy process-messages \
  --gen2 \
  --runtime=python312 \
  --region=us-central1 \
  --source=. \
  --entry-point=process_pubsub \
  --trigger-topic=my-topic \
  --memory=512MB

# Deploy Cloud Storage triggered function
gcloud functions deploy process-uploads \
  --gen2 \
  --runtime=nodejs20 \
  --region=us-central1 \
  --source=. \
  --entry-point=processFile \
  --trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
  --trigger-event-filters="bucket=my-bucket"

Deploy from Source Repository

gcloud functions deploy my-function \
  --gen2 \
  --runtime=python312 \
  --source=https://source.developers.google.com/projects/my-project/repos/my-repo \
  --entry-point=main \
  --trigger-http

CLI Commands

CommandDescription
gcloud functions listList all functions
gcloud functions describe <name> --gen2 --region=<region>Get function details
gcloud functions logs read <name>Read function logs
gcloud functions call <name> --data '{}'Invoke function directly
gcloud functions delete <name> --gen2 --region=<region>Delete function
gcloud functions deploy <name> --update-env-vars KEY=valUpdate env vars

Configuration

Environment Variables

# Set during deployment
gcloud functions deploy my-function \
  --set-env-vars DB_HOST=10.0.0.1,DB_PORT=5432 \
  --set-secrets 'API_KEY=my-secret:latest'

# Update env vars
gcloud functions deploy my-function \
  --update-env-vars NEW_VAR=value

# Use Secret Manager
gcloud functions deploy my-function \
  --set-secrets 'DB_PASSWORD=projects/my-project/secrets/db-pass:latest'

Resource Configuration

gcloud functions deploy my-function \
  --gen2 \
  --memory=1024MB \
  --cpu=1 \
  --timeout=300s \
  --min-instances=1 \
  --max-instances=100 \
  --concurrency=80 \
  --service-account=my-sa@project.iam.gserviceaccount.com \
  --vpc-connector=projects/my-project/locations/us-central1/connectors/my-vpc \
  --ingress-settings=internal-only

VPC and Networking

# Create a VPC connector
gcloud compute networks vpc-access connectors create my-connector \
  --region=us-central1 \
  --subnet=my-subnet \
  --min-instances=2 \
  --max-instances=10

# Deploy with VPC connector
gcloud functions deploy my-function \
  --vpc-connector=my-connector \
  --egress-settings=all

Local Development

# Node.js local testing
npx @google-cloud/functions-framework --target=helloHttp --port=8080

# Python local testing
functions-framework --target=hello_http --port=8080 --debug

# Test locally
curl http://localhost:8080?name=Test

# Run with environment variables
DB_HOST=localhost functions-framework --target=main --port=8080

Advanced Usage

Concurrency (2nd Gen)

# Enable concurrency (multiple requests per instance)
gcloud functions deploy my-function \
  --gen2 \
  --concurrency=80 \
  --cpu=1 \
  --memory=512MB

Traffic Splitting

# Deploy new revision
gcloud functions deploy my-function --gen2 --source=.

# Split traffic (canary deployment)
gcloud run services update-traffic my-function \
  --region=us-central1 \
  --to-revisions=my-function-00001-abc=90,my-function-00002-xyz=10

Eventarc Triggers

# Trigger on Firestore document change
gcloud functions deploy on-document-change \
  --gen2 \
  --trigger-event-filters="type=google.cloud.firestore.document.v1.written" \
  --trigger-event-filters="database=(default)" \
  --trigger-event-filters-path-pattern="document=users/{userId}"

# Trigger on Cloud Audit Log
gcloud functions deploy on-vm-create \
  --gen2 \
  --trigger-event-filters="type=google.cloud.audit.log.v1.written" \
  --trigger-event-filters="serviceName=compute.googleapis.com" \
  --trigger-event-filters="methodName=v1.compute.instances.insert"

Monitoring

# View logs
gcloud functions logs read my-function --limit=50

# View logs with filter
gcloud functions logs read my-function \
  --filter="severity>=ERROR" \
  --limit=20

# Metrics available in Cloud Monitoring:
# cloudfunctions.googleapis.com/function/execution_count
# cloudfunctions.googleapis.com/function/execution_times
# cloudfunctions.googleapis.com/function/active_instances
# cloudfunctions.googleapis.com/function/user_memory_bytes

Troubleshooting

IssueSolution
Deploy fails with permission errorEnable Cloud Build API; check IAM roles for service account
Function timeoutIncrease --timeout (max 60m for 2nd gen); optimize function code
Cold start latencySet --min-instances=1; use lighter dependencies; choose smaller runtime
Out of memoryIncrease --memory; check for memory leaks; reduce payload size
Cannot reach VPC resourcesConfigure VPC connector; set --egress-settings=all
Pub/Sub messages redeliveredEnsure function returns success; check for unhandled exceptions
Secret Manager access deniedGrant secretAccessor role to function service account
CORS errors on HTTP functionSet CORS headers in function response; handle OPTIONS preflight