Deploying to Google Cloud Run with Terraform
To make it easy for you to get started with GitLab, here’s a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? Use the template at the bottom!
cd existing_repo
git remote add origin https://gitlab.com/574n13y/gcp-microservices-iac.git
git branch -M main
git push -uf origin main
Use the built-in continuous integration in GitLab.
### Prerequisites To follow this tutorial you will need:
Start by authenticating the SDK to Google Cloud:
Create a new project where your Cloud Run service will be deployed. Replace PROJECT_ID and PROJECT_NAME with the desired values:
terraform {
required_version = ">= 0.14"
required_providers {
# Cloud Run support was added on 3.3.0
google = ">= 3.3"
}
}
provider "google" {
# Replace `PROJECT_ID` with your project
project = "vivesh-405513"
}
resource "google_project_service" "run_api" {
service = "run.googleapis.com"
disable_on_destroy = true
}
resource "google_cloud_run_service" "run_service" {
name = "app"
location = "us-central1"
template {
spec {
containers {
image = "gcr.io/google-samples/hello-app:1.0"
}
}
}
traffic {
percent = 100
latest_revision = true
}
# Waits for the Cloud Run API to be enabled
depends_on = [google_project_service.run_api]
}
resource "google_cloud_run_service_iam_member" "run_all_users" {
service = google_cloud_run_service.run_service.name
location = google_cloud_run_service.run_service.location
role = "roles/run.invoker"
member = "allUsers"
}
resource "google_storage_bucket" "auto-expire" {
name = "stanley_bucket_iac"
location = "US"
force_destroy = true
public_access_prevention = "enforced"
}
output "service_url" {
value = google_cloud_run_service.run_service.status[0].url
}
name: the name of your service. It will be displayed in the public URL.
location: the region where your service will run. See all the options here.
image: The Docker image that will be used to create the container. Cloud Run has direct support for images from the Container Registry and Artifact Registry.
traffic: controls the traffic for this revision. The percent property indicates how much traffic will be redirected to this revision. latest_revision specifies that this traffic configuration needs to be used for the latest revision.
depends_on: waits for a resource to be ready, in this case, the Cloud Run API.
Deploying the infrastructure
terraform init
terraform plan
terrafrom apply
Updating the service image = "gcr.io/google-samples/hello-app:2.0"
Run terraform apply to deploy the changes:
To delete all resources created with Terraform, run the following command and confirm the prompt:
This will disable the Cloud Run API, delete the Cloud Run service and its permissions.