How to deploy Terraform code using Google Cloud Build in an automated manner on Google Cloud Platform (GCP).
Step-1
1 min readJun 8, 2024
Provider.tf
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = ">= 4.0" # Update version as needed
}
}
}
gcs.tf or main.tf
resource "google_storage_bucket" "bucket_dev" {
project = var.project # Use variables for environment-specific values
location = "us-east4"
name = "bucket_dev"
}
If you have not SA you have to create one SA to perform this activities
Step -2
Cloud Build Configuration (build.yaml):
- Define Cloud Build steps to execute Terraform commands
steps:
- name: 'gcloud auth activate-service-account'
args: ['--key-file=/credentials/service_account.json']
env:
CREDENTIALS: /path/to/service_account.json # Adjust path based on your setup
- name: 'Install Terraform'
# ... (steps to install Terraform)
- name: 'Initialize Terraform'
run: 'terraform init -backend-config=backend.tfvars' # Initialize Terraform with backend configuration
- name: 'Plan Terraform changes (optional)'
run: 'terraform plan' # Run a plan-only Terraform operation
- name: 'Apply Terraform changes'
run: 'terraform apply -auto-approve' # Apply Terraform changes (use with caution)
- name: 'Optional: Terraform destroy'
# ... (steps to destroy infrastructure using Terraform destroy)