Deploy Google Cloud Run with Terraform: Full Guide
Tags: googlecloud, terraform
Published: 2024-05-11 18:08:05

Learn how to deploy a Google Cloud Run instance using Terraform, complete with a connection to a Cloud SQL instance, open IAM permissions, health checks, specified resource allocations, and environment variables.

## **What You'll Need**

Before you start, ensure you have the following:

- **A Google Cloud account** with billing enabled.
- **Terraform installed** on your local machine. If not, download it from [Terraform's official site](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli#install-terraform).
- **Google Cloud CLI** configured on your machine. Install and configure the Google Cloud CLI [here](https://cloud.google.com/sdk/docs/install#installation_instructions).

## **Setting Up Your Terraform Configuration**

### **Step 1: Initialize Your Terraform Project**

Create a new directory for your Terraform configuration:

```bash
mkdir terraform-cloudrun
cd terraform-cloudrun
```

Now, create your **`main.tf`** file:

```go
terraform {
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 5.28.0"
    }
  }

  required_version = ">= 1.0"
}

provider "google" {
  project = "your-gcp-project-id"
  region  = "your-gcp-region"
}
```

Replace **`your-gcp-project-id`** and **`your-gcp-region`** with your actual Google Cloud project ID and region. This setup uses the environment variable **`GOOGLE_APPLICATION_CREDENTIALS`** for authentication, which should be set on the runner.

### **Step 2: Define Your Infrastructure**

### **Cloud SQL Instance**

Ensure your Cloud SQL instance is defined, either in Terraform or already existing:

```go
resource "google_sql_database_instance" "default" {
  name             = "example-instance"
  database_version = "POSTGRES_15"
  region           = "us-central1"

  settings {
    tier = "db-f1-micro"
  }
}
```

### **Retrieving Secrets**

Retrieve the database password securely from Google Secrets Manager:

```go
data "google_secret_manager_secret_version" "db_pass" {
  secret = "db-password"
}
```

Ensure that the secret **`db-password`** exists in Google Secrets Manager with the appropriate permissions set for the service account used by Terraform.

### **Cloud Run Service**

Define your Cloud Run service:

```go
resource "google_cloud_run_service" "default" {
  name     = "example-service"
  location = "us-central1"

  template {
    spec {
      containers {
        image = "gcr.io/your-project-id/example-image"

        resources {
          limits {
            cpu    = "1000m"
            memory = "512Mi"
          }
        }

        env {
          name  = "DATABASE_URL"
          value = "postgres://username:${data.google_secret_manager_secret_version.db_pass.secret_data}@${google_sql_database_instance.default.private_ip}/dbname"
        }
      }

      service_account_name = google_service_account.default.email
    }
  }

  traffic {
    percent         = 100
    latest_revision = true
  }

  autogenerate_revision_name = true
}
```

### **IAM Permissions**

Open IAM permissions for all users:

```go
resource "google_cloud_run_service_iam_policy" "public" {
  location    = google_cloud_run_service.default.location
  project     = google_cloud_run_service.default.project
  service     = google_cloud_run_service.default.name

  policy_data = jsonencode({
    bindings = [
      {
        role    = "roles/run.invoker"
        members = ["allUsers"]
      },
    ]
  })
}

```

### **Step 3: Initialize and Apply Your Terraform Configuration**

Run the following commands in your terminal:

```bash
terraform init
terraform plan
terraform apply -auto-approve
```

With these steps, you've successfully deployed a Google Cloud Run instance connected to a Cloud SQL instance with comprehensive configurations. This setup includes open IAM permissions, detailed health checks, specific resource allocations, and environment variables, all managed efficiently with Terraform.