Skip to main content
GitHub Actions
CHAPTER 18

Infrastructure as Code Automation

Updated: May 15, 2026
25 min read

# CHAPTER 18

Infrastructure as Code Automation

1. Introduction

In traditional IT, when a team needed a new server, they submitted a ticket. An administrator would log into the AWS console, click 20 different buttons to create a server, manually configure firewalls, and hand it over a week later. This manual process is slow, prone to human error, and impossible to replicate perfectly. The DevOps solution is Infrastructure as Code (IaC). We write scripts that define our hardware, and we use GitHub Actions to execute those scripts, spinning up entire data centers in minutes. In this chapter, we will integrate GitHub Actions with Terraform, the industry titan of IaC.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define Infrastructure as Code (IaC) and its operational benefits.
  • Understand how GitHub Actions orchestrates the execution of IaC tools.
  • Utilize the hashicorp/setup-terraform marketplace action.
  • Configure a declarative pipeline to plan and apply Terraform changes.
  • Implement manual approvals for infrastructure deployments.

3. Beginner-Friendly Explanation

Imagine building a hotel.
  • Terraform (The Architect & Construction Crew): Terraform looks at a blueprint (Code) and builds the physical structure. It pours the concrete, builds the walls, and installs the plumbing. (In the cloud, it creates the raw Linux server, the database, and the firewall).
  • GitHub Actions (The General Contractor): GitHub Actions is the boss. GitHub Actions reads the master plan, downloads the Terraform tool, securely fetches the AWS keys, and commands Terraform: "Build the hotel exactly like the blueprint says."

4. Terraform Basics in CI/CD

Terraform is a declarative language. You write .tf files describing the *desired state* of your cloud environment. A standard Terraform deployment requires three sequential terminal commands:
  1. 1. terraform init: Downloads cloud provider plugins (like AWS or Azure packages).
  1. 2. terraform plan: Reads the code and calculates exactly what it is about to create, modify, or destroy.
  1. 3. terraform apply: Actually executes the changes against the live cloud account.

GitHub Actions simply automates typing these three commands into a terminal.

5. Mini Project: Deploy Infrastructure using GitHub Actions

Let's write a pipeline that acts as the General Contractor, using Terraform to automatically provision an AWS environment.

Step-by-Step Pipeline Concept:

yaml
1234567891011121314151617181920212223242526272829303132333435363738
name: Deploy Infrastructure (Terraform)
on:
  push:
    branches: [ main ]

jobs:
  terraform-deploy:
    runs-on: ubuntu-latest
    
    # We use an Environment to force a manual human approval step!
    environment: production-infrastructure
    
    steps:
      - name: Checkout Code
        uses: actions/checkout@v4

      # Step 1: Install Terraform on the Runner
      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3

      # Step 2: Authenticate securely with AWS via OIDC (Chapter 12)
      - name: Configure AWS Credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::12345:role/GitHubTerraformRole
          aws-region: us-east-1

      # Step 3: Run Terraform Initialization
      - name: Terraform Init
        run: terraform init

      # Step 4: Preview the changes
      - name: Terraform Plan
        run: terraform plan -out=tfplan

      # Step 5: Execute the changes (Runs automatically after Environment Approval)
      - name: Terraform Apply
        run: terraform apply -auto-approve tfplan

6. Manual Approvals (GitHub Environments)

In the script above, what if a developer made a typo and terraform plan says "I am going to delete the production database"? We don't want GitHub Actions to blindly execute that! By utilizing the environment: production-infrastructure keyword, GitHub Actions will pause the workflow immediately before the job starts. It will email the designated manager. The workflow sits in a suspended state until the manager logs into GitHub, reviews the Terraform Plan logs, and clicks "Approve."

7. Real-World Scenarios

A company experienced a catastrophic database failure, and their entire primary AWS region (us-east-1) went offline. Because their infrastructure was built manually over five years via clicking buttons in the AWS console, they had no idea how to rebuild it in a new region. It took them a week to manually piece the architecture back together. Following the disaster, they adopted IaC. They defined their entire network in Terraform and managed the deployments through GitHub Actions. A year later, during a similar outage, they simply changed one variable in their repository from us-east-1 to us-west-2, opened a Pull Request, and GitHub Actions rebuilt their entire multi-tier architecture from scratch in 12 minutes.

8. Best Practices

  • Plan in PR, Apply in Main: The best Terraform workflow utilizes two triggers. When a developer opens a Pull Request, GitHub Actions runs terraform plan and posts the output as a comment on the PR. Reviewers can see exactly what *will* happen. Once the PR is merged to main, a separate workflow runs terraform apply to actually make the changes.

9. Security Recommendations

  • State File Security: Terraform relies on a "State File" (terraform.tfstate) to remember what it built. This file often contains highly sensitive data, including plaintext database passwords generated during infrastructure creation. Never commit the state file to Git. Your Terraform code must be configured to store this file in a secure, encrypted remote backend (like an AWS S3 bucket).

10. Troubleshooting Tips

  • Lock Errors: If your pipeline fails with Error acquiring the state lock, it means another GitHub Action (or another developer) is currently running Terraform at the exact same time. Terraform locks the state file to prevent corruption. Wait for the other run to finish and try again.

11. Exercises

  1. 1. Explain the operational workflow of validating infrastructure changes using terraform plan within a Pull Request.
  1. 2. Why is the environment: keyword critical for safety when deploying infrastructure via automation?

12. FAQs

Q: Can GitHub Actions manage infrastructure across multiple cloud providers at once? A: Yes! Because Terraform is cloud-agnostic, a single GitHub Actions workflow can execute a Terraform script that creates a database in AWS, a web server in Azure, and a DNS record in Cloudflare, all simultaneously.

13. Interview Questions

  • Q: Describe a secure, automated CI/CD pipeline architecture for Infrastructure as Code (IaC) utilizing Terraform and GitHub Actions. How do you implement human-in-the-loop approvals before infrastructure mutation?
  • Q: A pipeline runs terraform apply successfully, but the terraform.tfstate file is discarded because the GitHub Runner is ephemeral. What catastrophic failure does this cause on the next pipeline run, and how is it mitigated architecturally?

14. Summary

In Chapter 18, we elevated GitHub Actions from an application deployer to a true infrastructure orchestrator. We defined Infrastructure as Code (IaC), eliminating the fragile, undocumented manual cloud configuration processes of the past. We integrated GitHub Actions with Terraform to mathematically define and provision cloud resources. By leveraging GitHub Environments for manual approvals, we ensured that our automation remains safely governed, giving us the power to conjure, modify, and destroy entire data centers safely through version-controlled Pull Requests.

15. Next Chapter Recommendation

You understand the theory, the syntax, and the architecture. It is time to prove you can build it. Proceed to Chapter 19: Real-World GitHub Actions Projects.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·