Collaboration and CI/CD for Terraform
7 min read
Hello, Developer! π Welcome to Level 10 of your Terraform journey.
Up until now, you've likely been the "Lone Wolf" πΊβwriting code on your laptop, running terraform apply locally, and feeling powerful. But in the real world, infrastructure is a team sport.
Imagine if you and a coworker both try to update the same database at the exact same time from your own laptops. Who wins? Nobody. Your state file gets corrupted, the database cries, and you both spend the weekend debugging. π±
This module is about moving from "It works on my machine" to "It works for the Team." We are going to professionalize your workflow with Version Control, Automation, and Remote Operations.
1. Version Control for Terraform: Git Best Practices and .gitignore π€
The Definition
Version Control is the practice of tracking and managing changes to software code. Git is the industry standard tool for this.
The Problem
You write a cool Terraform configuration. Your teammate, Bob, wants to add a load balancer. You email him the file. He changes it and emails it back. You overwrite your file. Suddenly, the firewall rules you added yesterday are gone. Also, you accidentally uploaded your AWS Secret Keys to a public repo and now Bitcoin miners are running on your credit card. πΈ
The Solution
We use Git to track changes, merge work, and keep secrets safe.
π Crucial Practice: The .gitignore File
In Terraform, there are files you MUST commit and files you MUST NOT commit.
Do Commit:
.tffiles (configuration).tfvars(ONLY if they contain non-sensitive data, likeenvironment="dev")
Do NOT Commit:
.terraform/folder (These are plugins and modules downloaded specifically for your OS. It's huge and useless to others).terraform.tfstateandterraform.tfstate.backup(This file contains the "truth" of your infrastructure. It often contains passwords and keys in plain text. Committing this is a security disaster).terraform.tfvars(If it contains secrets likedb_password).
Hands-on: Setting up your .gitignore
Create a file named .gitignore in your root directory and paste this standard industry configuration:
# Local .terraform directories
**/.terraform/*
# .tfstate files
*.tfstate
*.tfstate.*
# Crash log files
crash.log
crash.*.log
# Exclude all .tfvars files, which are likely to contain sensitive data,
# such as password, private keys, and other secrets.
*.tfvars
*.tfvars.json
# Ignore override files as they are usually local customizations
override.tf
override.tf.json
*_override.tf
*_override.tf.json
# Ignore CLI configuration files
.terraformrc
terraform.rcπ§ Fun Fact
In 2019, a report showed that over 100,000 public GitHub repositories contained leaked API keys. Don't let your Terraform repo be one of them!
2. Automated Code Formatting and Validation (fmt & validate) π§Ή
The Definition
terraform fmt: A command that rewrites Terraform configuration files to a canonical format and style.terraform validate: A command that checks whether a configuration is syntactically valid and internally consistent.
The Problem
You like using 2 spaces for indentation. Bob likes 4 spaces. Sarah puts her braces on the next line. Your code reviews turn into arguments about aesthetics instead of functionality. Furthermore, you push code that looks right but has a typo in a resource name, breaking the build for everyone.
The Solution
Let the robots do the cleaning. π€
Hands-on: terraform fmt
This is the "Prettifier." It aligns equal signs, fixes indentation, and standardizes spacing.
Run this in your terminal:
terraform fmtOutput:
main.tf
variables.tf(It lists the files it modified. If nothing is returned, your code was already perfect!)
Real-world usage: Most teams run this automatically right before committing code (using a "pre-commit hook") so nobody ever sees messy code.
Hands-on: terraform validate
This checks for syntax errors (like missing quotes) and consistency (like referencing a variable that doesn't exist) without talking to the cloud provider. It's fast.
Run this:
terraform validateSuccess Output:
Success! The configuration is valid.Failure Output:
Error: Reference to undeclared input variable
on main.tf line 12, in resource "aws_instance" "web":
12: instance_type = var.instance_type
Did you mean "var.instance_type"?(It catches your typos before you embarrass yourself in production!)
3. Integrating Terraform into GitHub Actions / GitLab CI βοΈ
The Definition
CI/CD (Continuous Integration/Continuous Deployment) is a method to frequently deliver apps to customers by introducing automation into the stages of app development.
The Problem
You run terraform apply from your laptop. It works. You go on vacation. The site crashes. Your boss tries to fix it but doesn't have your specific Terraform version installed or access to the keys on your laptop. Panic ensues. π₯
The Solution
We move the execution of Terraform off your laptop and into a centralized pipeline (GitHub Actions, GitLab CI, Jenkins).
The Golden Workflow:
- Pull Request (PR): You propose a change.
- CI (Plan): The robot runs
terraform planand posts the output as a comment on the PR. You review what will happen. - Merge: You approve the PR.
- CD (Apply): The robot runs
terraform applyautomatically.
Hands-on: GitHub Actions Example
Here is a simplified standard workflow file (.github/workflows/terraform.yml).
Prerequisites: You must add your cloud credentials (like AWS_ACCESS_KEY_ID) to your GitHub Repository Secrets.
name: "Terraform CI/CD"
on:
push:
branches:
- main
pull_request:
jobs:
terraform:
name: "Terraform"
runs-on: ubuntu-latest
# Use the official HashiCorp action
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
with:
terraform_version: 1.5.0
- name: Terraform Init
id: init
run: terraform init
env:
# Assuming you are using an S3 backend or similar
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
- name: Terraform Format
id: fmt
run: terraform fmt -check
- name: Terraform Plan
id: plan
if: github.event_name == 'pull_request'
run: terraform plan -no-color
continue-on-error: true
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
- name: Terraform Apply
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: terraform apply -auto-approve
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}π§ Industry Insight
In high-security environments, companies don't store long-lived AWS keys in GitHub Secrets. They use OIDC (OpenID Connect). This lets GitHub ask AWS for a temporary "badge" to do the work, which expires immediately after. It's like a guest pass instead of giving GitHub a key to your house.
4. Terraform Cloud Basics: Remote Operations and Run Triggers βοΈ
The Definition
Terraform Cloud (HCP Terraform) is HashiCorp's managed service. It acts as a specialized backend that stores your state file, locks it to prevent conflicts, and runs the apply commands on their servers.
The Problem
Setting up the GitHub Action above is great, but you still have to manage where the state file lives (e.g., configuring an S3 bucket + DynamoDB for locking). It's a lot of boilerplate. Also, seeing the "Plan" output in a text log in GitHub is ugly and hard to read.
The Solution
Terraform Cloud handles the "Plumbing" (State & Locking) and the "Execution" (Running the code).
Key Concept: The cloud Block
Formerly known as the remote backend, modern Terraform uses the cloud block to connect to HCP Terraform.
Hands-on: Connecting to Terraform Cloud
- Create a free account on app.terraform.io.
- Create an Organization and a Workspace (e.g.,
my-app-prod). - Add this to your
terraform.tffile:
terraform {
cloud {
organization = "my-company-org"
workspaces {
name = "my-app-prod"
}
}
}Now, when you run terraform apply on your laptop:
- Your code is zipped up. π¦
- It is sent to HashiCorp's servers. βοΈ
- The
applyruns there, not on your laptop. - The logs stream back to your terminal terminal and appear in a beautiful UI on the web.
Run Triggers (The "Domino Effect")
Imagine you have a Network Workspace (VPC) and an App Workspace (EC2). If you change the VPC, you might break the App.
Run Triggers allow you to link workspaces. "If Workspace A updates successfully, automatically start a plan in Workspace B to make sure nothing broke." This ensures consistency across massive systems.
π Summary Checklist
- Git: Add
.terraformand.tfstateto.gitignoreimmediately. - Format: Run
terraform fmtbefore you push. - Validate: Run
terraform validateto catch syntax errors. - CI/CD: Automate
planon Pull Requests andapplyon Merge using GitHub Actions or GitLab CI. - State: Never store state locally for teams. Use a remote backend (S3/DynamoDB) or Terraform Cloud.
π References & Further Reading
- GitIgnore Templates for Terraform
- GitHub Actions: Setup Terraform
- Terraform Cloud: The `cloud` block
- Best Practices for Terraform CI/CD
Congratulations! You are no longer a lone wolf. You are a DevOps Engineer. π·ββοΈπ
Challenge
You have been tasked with setting up a new Terraform project for your team, ensuring it follows professional best practices for collaboration, security, and automation. Your goal is to create the content for three separate configuration files within the editor below, using the provided markers to separate your code.
.gitignore: Create the content for a.gitignorefile. It must prevent the Terraform state file, any backup state files, the local.terraformdirectory containing provider plugins, and any files with a.tfvarsextension from being committed to version control.main.tf: Configure the project to use Terraform Cloud for remote state management. In aterraformblock, add acloudblock. Configure it for an organization named"my-pro-company"and a workspace named"production-web-app".GitHub Actions Workflow (
.github/workflows/terraform.yml): Define a CI/CD pipeline that implements the "Golden Workflow".- Name the workflow
Terraform CI/CD. - It must trigger on pull requests targeting the
mainbranch and on pushes to themainbranch. - Define a single job named
terraformthat runs onubuntu-latest. - For pull request triggers, the job should run
terraform fmt --check,terraform validate, andterraform plan. - For push triggers to
main, the job should runterraform apply -auto-approve.
- Name the workflow
Expected result
Your solution should consist of three distinct configuration blocks corresponding to the files requested.
.gitignore: The file content should include patterns to ignore.terraform/,terraform.tfstate,terraform.tfstate.*, and*.tfvars.main.tf: This section should contain aterraformconfiguration block. Inside it, acloudblock must be defined with theorganizationattribute set to"my-pro-company"and aworkspacesblock containing anameattribute set to"production-web-app"..github/workflows/terraform.yml: This should be a valid YAML structure for a GitHub Actions workflow. It must have the nameTerraform CI/CD, triggers forpush(branches:main) andpull_request(branches:main), and a job namedterraform. The job must contain conditional steps: one set of steps (fmt,validate,plan) that runsif: github.event_name == 'pull_request', and another step (apply) that runsif: github.event_name == 'push'.