Learn Terraform Β· 10/11

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:

  • .tf files (configuration)
  • .tfvars (ONLY if they contain non-sensitive data, like environment="dev")

Do NOT Commit:

  • .terraform/ folder (These are plugins and modules downloaded specifically for your OS. It's huge and useless to others).
  • terraform.tfstate and terraform.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 like db_password).

Hands-on: Setting up your .gitignore

Create a file named .gitignore in your root directory and paste this standard industry configuration:

gitignore
# 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:

bash
terraform fmt

Output:

text
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:

bash
terraform validate

Success Output:

text
Success! The configuration is valid.

Failure Output:

text
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:

  1. Pull Request (PR): You propose a change.
  2. CI (Plan): The robot runs terraform plan and posts the output as a comment on the PR. You review what will happen.
  3. Merge: You approve the PR.
  4. CD (Apply): The robot runs terraform apply automatically.

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.

yaml
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

  1. Create a free account on app.terraform.io.
  2. Create an Organization and a Workspace (e.g., my-app-prod).
  3. Add this to your terraform.tf file:
hcl
terraform {
  cloud {
    organization = "my-company-org"

    workspaces {
      name = "my-app-prod"
    }
  }
}

Now, when you run terraform apply on your laptop:

  1. Your code is zipped up. πŸ“¦
  2. It is sent to HashiCorp's servers. ☁️
  3. The apply runs there, not on your laptop.
  4. 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

  1. Git: Add .terraform and .tfstate to .gitignore immediately.
  2. Format: Run terraform fmt before you push.
  3. Validate: Run terraform validate to catch syntax errors.
  4. CI/CD: Automate plan on Pull Requests and apply on Merge using GitHub Actions or GitLab CI.
  5. State: Never store state locally for teams. Use a remote backend (S3/DynamoDB) or Terraform Cloud.

πŸ”— References & Further Reading

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.

  1. .gitignore: Create the content for a .gitignore file. It must prevent the Terraform state file, any backup state files, the local .terraform directory containing provider plugins, and any files with a .tfvars extension from being committed to version control.

  2. main.tf: Configure the project to use Terraform Cloud for remote state management. In a terraform block, add a cloud block. Configure it for an organization named "my-pro-company" and a workspace named "production-web-app".

  3. 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 main branch and on pushes to the main branch.
    • Define a single job named terraform that runs on ubuntu-latest.
    • For pull request triggers, the job should run terraform fmt --check, terraform validate, and terraform plan.
    • For push triggers to main, the job should run terraform apply -auto-approve.

Expected result

Your solution should consist of three distinct configuration blocks corresponding to the files requested.

  1. .gitignore: The file content should include patterns to ignore .terraform/, terraform.tfstate, terraform.tfstate.*, and *.tfvars.

  2. main.tf: This section should contain a terraform configuration block. Inside it, a cloud block must be defined with the organization attribute set to "my-pro-company" and a workspaces block containing a name attribute set to "production-web-app".

  3. .github/workflows/terraform.yml: This should be a valid YAML structure for a GitHub Actions workflow. It must have the name Terraform CI/CD, triggers for push (branches: main) and pull_request (branches: main), and a job named terraform. The job must contain conditional steps: one set of steps (fmt, validate, plan) that runs if: github.event_name == 'pull_request', and another step (apply) that runs if: github.event_name == 'push'.

hcl

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.