Run Terraform in GitHub Actions, use Terraform Cloud for remote state, and implement plan-on-PR, apply-on-merge.
name: Terraform
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
terraform:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
with:
terraform_version: 1.7.0
cli_config_credentials_token: ${{ secrets.TF_API_TOKEN }}
- name: Terraform Init
run: terraform init
- name: Terraform Plan
run: terraform plan -no-color
# On PRs, plan output is posted as a comment
- name: Terraform Apply
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: terraform apply -auto-approve# 1. Create account at app.terraform.io
# 2. Create organization and workspace
# 3. Add backend config:
terraform {
cloud {
organization = "your-org"
workspaces {
name = "production"
}
}
}
# 4. Store AWS credentials as workspace variables
# 5. Generate API token → store as GitHub secret TF_API_TOKENterraform plan on every PR = infrastructure changes reviewed before merge.terraform apply -auto-approve on main merge = automatic deployment.TF_API_TOKEN secret authenticates the CI runner to Terraform Cloud.