Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Step-by-step setup of Google Cloud function connecting to Redis with Serverless VPC Connector
#!/usr/bin/env bash
# Reference:
# enable APIs
gcloud services enable
gcloud services enable
gcloud services enable
# set these to your specific environment
export PROJECT_ID=db-cluster-tests
export REDIS_INSTANCE=myinstance
export REDIS_VERSION="redis_4_0"
export GCP_REGION=us-central1
export GCP_NETWORK=default
export VPC_CONNECTOR=redis-vpc-conn
export VPC_RANGE=""
export FUNCTION_NAME=visit_count
export STORAGE_ROLE=simpleStorageRole
# create redis cluster
gcloud redis instances create $REDIS_INSTANCE --size=2 --region=$GCP_REGION \
# confirm redis installation
gcloud redis instances describe $REDIS_INSTANCE --region=$GCP_REGION
# fetch the authorizedNetwork (if not 'default' then change vars above)
export REDIS_NETWORK=$(gcloud redis instances describe $REDIS_INSTANCE --region=$GCP_REGION --format="value(authorizedNetwork)")
export REDIS_HOST=$(gcloud redis instances describe $REDIS_INSTANCE --region=$GCP_REGION --format="value(host)")
export REDIS_PORT=$(gcloud redis instances describe $REDIS_INSTANCE --region=$GCP_REGION --format="value(port)")
echo "Redis network: $REDIS_NETWORK, host: $REDIS_HOST, port: $REDIS_PORT"
# create VPC connector (use the network name [not full path] and region from above)
gcloud compute networks vpc-access connectors create $VPC_CONNECTOR \
--network $GCP_NETWORK \
--region $GCP_REGION \
--range $VPC_RANGE
# verify connector
gcloud compute networks vpc-access connectors describe $VPC_CONNECTOR --region $GCP_REGION
# fetch the project number to use in IAM bindings
export PROJECT_NUM=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
echo "Project number: $PROJECT_NUM"
# create custom role for storage permissions
gcloud iam roles create $STORAGE_ROLE \
--project $PROJECT_ID \
--title $STORAGE_ROLE \
--description "get and create storage objects" \
--permissions "storage.objects.create,storage.objects.get"
export STORAGE_ROLE_NAME=$(gcloud iam roles describe $STORAGE_ROLE --project $PROJECT_ID --format="value(name)")
echo "Storage role: $STORAGE_ROLE_NAME"
# add IAM bindings (replace project number with one you fetched)
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member=serviceAccount:service-$ \
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member=serviceAccount:service-$ \
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member=serviceAccount:service-$ \
# download sample function
git clone
cd python-docs-samples/functions/memorystore/redis
# deploy function with your VPC connector
gcloud beta functions deploy $FUNCTION_NAME \
--runtime python37 \
--trigger-http \
--region $GCP_REGION \
--vpc-connector projects/$PROJECT_ID/locations/$GCP_REGION/connectors/$VPC_CONNECTOR \
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment