Deploy To Cloud Run Using Cloud Build And Terraform
This article demonstrates use of Cloud Build and Terraform to deploy python backend service on Google Cloud Run.
Terraform is an “infrastructure as a code” tool that allows for reuse of similar and consistent set of instructions to provision Cloud services (Cloud Run, Compute etc) across projects.
As an example, we will deploy existing python application built in previous article.
Step 1: Install tools
- Setup Google Cloud (GCP) account
- Download VS Code
- Download Terraform
Step 2: Cloud Build application
- VS Code folder structure
- Create cloudbuild.yaml as below
# create empty repository kmtestrepo in Artifact Registry before # running cloud build
#
# below command will create a docker image and push to artifact
# registry> gcloud builds submit --config cloudbuild.yaml ./src
Step 3: Provision resources (terraform files to create)
- create main.tf as below
- create variables.tf as below
- create outputs.tf as below
- create mediatype.tf as below
- create project.tf as below
- create service.tf as below
- create kms.tf as below (note: Once created this key will not be removed by terraform destroy command)
Step 4: Apply terraform and test application
#run terraform init> terraform init# run terraform plan and confirm changes to outputs> terraform plan# run terraform apply> terraform apply
Notes: If below error received for IAM role then perform a manual update to project
Error: Error applying IAM policy for service account 'projects/terraform2022/serviceAccounts/kmstestsa@terraform2022.iam.gserviceaccount.com': Error setting IAM policy for service account 'projects/terraform2022/serviceAccounts/kmstestsa@terraform2022.iam.gserviceaccount.com': googleapi: Error 400: Service account kmstestsa@terraform2022.iam.gserviceaccount.com does not exist., badRequest
Step 5:
Manual update of “google_service_account_iam_binding” and “google_kms_crypto_key_iam_binding” for newly created service account “kmstestsa@terraform2022.iam.gserviceaccount.com”
- In IAM Add Principal “kmstestsa@terraform2022.iam.gserviceaccount.com”
- Role: Editor
- In Security => Key Management for “kmstestprojkeyring” Add Principal “kmstestsa@terraform2022.iam.gserviceaccount.com”
- Role: Cloud KMS Cryptokey Encrypter/Decrypter
Step 6: Test
Terraform apply will output service_url = “https://kmstest-kacqer3rca-ue.a.run.app"
In browser view list
Step 7: remove resources
#Terraform commands #remove all resources
> terraform destroy # Note: Certain services such as KMS or
# AppEngine Firestore will still remain#Review what is in Terraform state
> Terraform state list# To remove item from state (in case of mismatch with Cloud service)
> Terraform state rm <listitem># To refresh
> Terraform refresh
Step 8: Delete the project along with all resources (optional)
gcloud projects delete terraform2022