How to Use Terraform with GitHub Actions - CICD Pipeline Guide
Set up Terraform CI-CD with GitHub Actions. Covers plan on PR, apply on merge, state locking, secrets management, and environment protection.
Terraform
Configure Terraform backends for remote state. Complete guide for S3 + DynamoDB, Azure Blob, GCS, Terraform Cloud, and Consul with encryption and locking.
Choose your backend based on your cloud provider: S3 + DynamoDB for AWS, Azure Blob Storage for Azure, GCS for GCP, or Terraform Cloud for multi-cloud. All support encryption and state locking.
| Feature | S3 | Azure Blob | GCS | TF Cloud |
|---|---|---|---|---|
| Locking | DynamoDB | Native | Native | Native |
| Encryption | KMS/AES-256 | AES-256 | KMS/CMEK | Built-in |
| Versioning | S3 versioning | Blob versioning | Object versioning | Built-in |
| Cost | ~$1/mo | ~$1/mo | ~$1/mo | Free (up to 500 resources) |
| Multi-cloud | ❌ | ❌ | ❌ | ✅ |
terraform {
backend "s3" {
bucket = "mycompany-terraform-state"
key = "prod/app/terraform.tfstate"
region = "us-east-1"
dynamodb_table = "terraform-locks"
encrypt = true
}
}terraform {
backend "azurerm" {
resource_group_name = "terraform-state-rg"
storage_account_name = "tfstatemycompany"
container_name = "tfstate"
key = "prod/app/terraform.tfstate"
}
}terraform {
backend "gcs" {
bucket = "mycompany-terraform-state"
prefix = "prod/app"
}
}terraform {
cloud {
organization = "mycompany"
workspaces {
name = "app-production"
}
}
}# From local to S3
# 1. Add backend config
# 2. Run init with migration
terraform init -migrate-state
# From one backend to another
terraform init -migrate-state
# Force reconfigure (discard current state location)
terraform init -reconfigure# By environment and component
bucket/
├── prod/
│ ├── networking/terraform.tfstate
│ ├── compute/terraform.tfstate
│ └── database/terraform.tfstate
├── staging/
│ └── app/terraform.tfstate
└── shared/
└── iam/terraform.tfstateEvery team project needs a remote backend. Pick the one matching your cloud provider, enable encryption and versioning, and organize state files by environment and component. Terraform Cloud works best for multi-cloud teams.
Set up Terraform CI-CD with GitHub Actions. Covers plan on PR, apply on merge, state locking, secrets management, and environment protection.
Master Terraform workspaces for managing dev, staging, and production environments. Covers workspace commands, state isolation, and CI/CD integration.
Understand the Terraform state file, its purpose, and best practices for managing it. Learn remote state, locking, and recovery techniques for teams.
Master Terraform variables with practical examples. Learn input, output, local, and environment variables for flexible infrastructure as code configurations.