set_env.sh
Overview
set_env.sh is a shell script designed to initialize and export essential Google Cloud environment variables required for deploying and managing services within a Google Cloud project. Its primary role is to verify authentication status, read and set the active Google Cloud project, and export several key environment variables such as project ID, project number, default service account, region, and identity tokens. The script must be sourced rather than executed directly to ensure that the exported variables persist in the current shell session.
This script is a critical component in the Environment Initialization phase within the Cloud Run Deployment Automation workflow, providing a consistent and authenticated environment context for subsequent deployment and operational scripts.
Purpose and Functionality
Authentication Verification: Checks if the
gcloudCLI is currently authenticated by attempting to print an access token. If authentication is missing, it prompts the user to log in.Project Configuration: Reads the Google Cloud project ID from a predefined file (
~/project_id.txt), validates its existence, and sets it as the active project ingcloud.Environment Variable Export: Exports core environment variables including:
PROJECT_ID,GOOGLE_CLOUD_PROJECT: Active Google Cloud project ID.PROJECT_NUMBER: Numeric project identifier.SERVICE_ACCOUNT_NAME: Default service account linked to the project.GOOGLE_CLOUD_LOCATIONandREGION: Geographic region settings.ID_TOKEN: Identity token for authentication purposes.GOOGLE_GENAI_USE_VERTEXAI: Feature flag for enabling Vertex AI integration.
By exporting these variables, set_env.sh prepares the shell environment for deployment scripts like cloudrun.sh or cloudrun-secure.sh and runtime components that rely on consistent project and authentication context.
Detailed Breakdown
Script Configuration Section
PROJECT_FILE="~/project_id.txt"
GOOGLE_CLOUD_LOCATION="europe-west1"
PROJECT_FILE: Path to the file containing the Google Cloud project ID. It supports tilde expansion.GOOGLE_CLOUD_LOCATION: Default Google Cloud region to use for services and deployments.
Authentication Check
if gcloud auth print-access-token > /dev/null 2>&1; then
echo "gcloud is authenticated."
else
echo "Error: gcloud is not authenticated."
echo "Please log in by running: gcloud auth login"
return 1
fi
Attempts to retrieve an access token using
gcloud auth print-access-token.If unsuccessful, outputs an error and instructs the user to authenticate.
Uses
return 1instead ofexitbecause the script is intended to be sourced.
Project File Validation and Setting
PROJECT_FILE_PATH=$(eval echo $PROJECT_FILE) # Expands ~
if [ ! -f "$PROJECT_FILE_PATH" ]; then
echo "Error: Project file not found at $PROJECT_FILE_PATH"
echo "Please create $PROJECT_FILE_PATH containing your Google Cloud project ID."
return 1
fi
PROJECT_ID_FROM_FILE=$(cat "$PROJECT_FILE_PATH")
gcloud config set project "$PROJECT_ID_FROM_FILE" --quiet
Expands the tilde in the project file path.
Validates the existence of the project ID file.
Reads the project ID and sets it as the active project in
gcloud.If the file is missing, it aborts with an error message.
Exporting Core Google Cloud Variables
export PROJECT_ID=$(gcloud config get project)
export GOOGLE_CLOUD_PROJECT=$(gcloud config get project)
export PROJECT_NUMBER=$(gcloud projects describe ${PROJECT_ID} --format="value(projectNumber)")
export SERVICE_ACCOUNT_NAME=$(gcloud compute project-info describe --format="value(defaultServiceAccount)")
PROJECT_IDandGOOGLE_CLOUD_PROJECT: Set to the current project ID fromgcloudconfig.PROJECT_NUMBER: Numeric identifier retrieved viagcloud projects describe.SERVICE_ACCOUNT_NAME: Default service account tied to the project, used for compute and other services.
The script echoes the exported values for user confirmation.
Exporting Location and Region
export GOOGLE_CLOUD_LOCATION="$GOOGLE_CLOUD_LOCATION"
export REGION="$GOOGLE_CLOUD_LOCATION"
Both
GOOGLE_CLOUD_LOCATIONandREGIONvariables are set to the configured region string.This ensures consistent region usage across deployment and runtime environments.
Exporting Application-Specific Variables
export ID_TOKEN=$(gcloud auth print-identity-token)
export GOOGLE_GENAI_USE_VERTEXAI="TRUE"
ID_TOKEN: Identity token generated viagcloudfor authenticating requests against secured endpoints.GOOGLE_GENAI_USE_VERTEXAI: Flag enabling Vertex AI features, likely consumed by downstream services or scripts.
Usage Notes
Must be sourced: The script requires sourcing (
source ./set_env.sh) to export variables into the current shell session.Prerequisite: The
project_id.txtfile must exist and contain a valid Google Cloud project ID.Authentication: The user must have an active
gcloudauthentication session.The script is idempotent and safe to run multiple times, re-exporting the environment variables each time.
Interaction with Other Components
set_env.shis invoked as part of the environment initialization step within the Cloud Run Deployment Automation process.It provides environment variables utilized by:
Deployment scripts such as
cloudrun.sh(for unauthenticated deployment) andcloudrun-secure.sh(for authenticated deployment).Runtime components of the Zoo Animal MCP server that require project context or authentication tokens.
It depends on the presence of the project ID file created during initial setup handled by
init.sh.Authentication status checked here ensures that subsequent deployment commands using the
gcloudCLI have valid credentials.
Example Usage
source ./set_env.sh
# Output:
# --- Setting Google Cloud Environment Variables ---
# Checking gcloud authentication status...
# gcloud is authenticated.
# Setting gcloud config project to: your-project-id
# Exported PROJECT_ID=your-project-id
# Exported PROJECT_NUMBER=123456789012
# Exported SERVICE_ACCOUNT_NAME=your-project-number-compute@developer.gserviceaccount.com
# Exported GOOGLE_CLOUD_PROJECT=your-project-id
# Exported GOOGLE_CLOUD_LOCATION=europe-west1
# Exported REGION=europe-west1
# Exported GOOGLE_GENAI_USE_VERTEXAI=TRUE
#
# --- Environment setup complete ---
After sourcing, the environment variables like PROJECT_ID, REGION, and ID_TOKEN are available for the current shell session.
Implementation Details and Algorithms
Authentication Verification: Uses a simple token print command to verify active authentication.
File Path Expansion: Uses
eval echoto expand tilde (~) in file paths, ensuring compatibility with user home directories.Environment Variable Export: Uses
exportto make variables available to child processes and scripts.Silent Project Configuration: Uses
--quietflag withgcloud config set projectto suppress prompts during automated execution.Identity Token Generation: Calls
gcloud auth print-identity-tokento generate tokens for secured service access.Error Handling: Uses
return 1to gracefully abort when errors occur, suitable for sourcing context.
Mermaid Flowchart: Script Workflow
flowchart TD
A[Start: source set_env.sh] --> B[Check gcloud Authentication]
B -->|Authenticated| C[Expand and Verify project_id.txt]
B -->|Not Authenticated| E[Print error and return]
C -->|File Exists| D[Set gcloud project from file]
C -->|File Missing| F[Print error and return]
D --> G[Export PROJECT_ID, PROJECT_NUMBER, SERVICE_ACCOUNT_NAME]
G --> H[Export REGION and GOOGLE_CLOUD_LOCATION]
H --> I[Export ID_TOKEN and VertexAI flag]
I --> J[Print success messages]
J --> K[End: Environment ready]
The flow begins with sourcing the script.
Authentication verification is mandatory.
Project ID file must exist and be valid.
Environment variables are exported sequentially.
Error conditions return early with messages.
On success, environment is fully configured.
References to Related Topics
This script is part of the Environment Initialization subtopic Environment Initialization, which addresses project setup, API enabling, IAM assignment, and environment variable export.
It supports the deployment automation scripts described in Cloud Run Deployment Automation, enabling streamlined MCP server deployment.
The exported identity token (
ID_TOKEN) is used in secure deployments as explained in Secure Deployment.The consistent project and region variables aid in monitoring and operational management, tying into Operational Monitoring & Environment Management.
This documentation covers all critical aspects of set_env.sh, providing detailed insight into its purpose, usage, and role within the broader Google Cloud deployment automation framework.