Bird
Raised Fist0
Terraformcloud~5 mins

Terraform in GitHub Actions - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Terraform helps you create and change cloud resources automatically. GitHub Actions lets you run these Terraform steps whenever you update your code, so your cloud setup stays up to date without manual work.
When you want to automatically create or update cloud resources after changing your code.
When you want to keep your cloud setup consistent and avoid manual mistakes.
When you want to share your infrastructure setup with your team and track changes in one place.
When you want to test your infrastructure changes safely before applying them.
When you want to save time by automating cloud resource management.
Config File - terraform.yml
terraform.yml
name: Terraform CI

on:
  push:
    branches:
      - main

jobs:
  terraform:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v2
        with:
          terraform_version: 1.5.6

      - name: Terraform Init
        run: terraform init

      - name: Terraform Validate
        run: terraform validate

      - name: Terraform Plan
        run: terraform plan

      - name: Terraform Apply
        if: github.ref == 'refs/heads/main' && github.event_name == 'push'
        run: terraform apply -auto-approve

This GitHub Actions workflow runs Terraform commands automatically when you push to the main branch.

  • Checkout repository: Gets your code so Terraform can use it.
  • Setup Terraform: Installs the right Terraform version.
  • Terraform Init: Prepares Terraform to work with your cloud provider.
  • Terraform Validate: Checks your Terraform files for mistakes.
  • Terraform Plan: Shows what changes Terraform will make.
  • Terraform Apply: Applies the changes automatically on the main branch.
Commands
Clone your repository locally to add the GitHub Actions workflow file.
Terminal
git clone https://github.com/example-user/example-repo.git
Expected OutputExpected
Cloning into 'example-repo'... remote: Enumerating objects: 10, done. remote: Counting objects: 100% (10/10), done. remote: Compressing objects: 100% (8/8), done. remote: Total 10 (delta 1), reused 10 (delta 1), pack-reused 0 Receiving objects: 100% (10/10), 2.34 KiB | 2.34 MiB/s, done. Resolving deltas: 100% (1/1), done.
Add the Terraform workflow file to the staging area to prepare for commit.
Terminal
git add .github/workflows/terraform.yml
Expected OutputExpected
No output (command runs silently)
Commit the workflow file with a clear message describing the change.
Terminal
git commit -m "Add Terraform GitHub Actions workflow"
Expected OutputExpected
[main abc1234] Add Terraform GitHub Actions workflow 1 file changed, 20 insertions(+) create mode 100644 .github/workflows/terraform.yml
Push your changes to the main branch to trigger the GitHub Actions workflow.
Terminal
git push origin main
Expected OutputExpected
Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Delta compression using up to 8 threads Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), 350 bytes | 350.00 KiB/s, done. Total 3 (delta 0), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (1/1), done. To https://github.com/example-user/example-repo.git def5678..abc1234 main -> main
Check the status of the GitHub Actions runs to see if the Terraform workflow ran successfully.
Terminal
gh run list --repo example-user/example-repo
Expected OutputExpected
ID NAME STATUS CONCLUSION WORKFLOW BRANCH EVENT CREATED AT 12345 Terraform CI completed success Terraform CI main push 2024-06-01T12:00:00Z
--repo - Specify the repository to check workflow runs
Key Concept

If you remember nothing else from this pattern, remember: automating Terraform with GitHub Actions keeps your cloud setup safe, consistent, and up to date without manual steps.

Common Mistakes
Not setting the Terraform version in the setup step.
This can cause the workflow to use an unexpected Terraform version, leading to errors or unexpected behavior.
Always specify the Terraform version explicitly in the setup-terraform action.
Running terraform apply on every branch push.
This can cause unintended changes in your cloud environment from experimental branches.
Limit terraform apply to run only on the main branch or protected branches.
Not committing the workflow file to the correct directory.
GitHub Actions only runs workflows in the .github/workflows directory.
Place workflow YAML files inside .github/workflows before committing.
Summary
Create a GitHub Actions workflow file to run Terraform commands automatically.
Use steps to checkout code, setup Terraform, initialize, validate, plan, and apply changes.
Push changes to the main branch to trigger the workflow and update cloud resources safely.

Practice

(1/5)
1. What is the main purpose of using Terraform in GitHub Actions workflows?
easy
A. To store Terraform state files in GitHub issues
B. To manually edit cloud resources from GitHub
C. To automatically run Terraform commands when code changes
D. To replace Terraform CLI with GitHub commands

Solution

  1. Step 1: Understand Terraform automation

    Terraform automates cloud resource management by running commands like plan and apply.
  2. Step 2: Role of GitHub Actions

    GitHub Actions can trigger these Terraform commands automatically when code changes happen.
  3. Final Answer:

    To automatically run Terraform commands when code changes -> Option C
  4. Quick Check:

    Terraform automation = automatic runs [OK]
Hint: Terraform in GitHub Actions automates runs on code changes [OK]
Common Mistakes:
  • Thinking GitHub Actions replaces Terraform CLI
  • Believing Terraform state is stored in GitHub issues
  • Assuming manual edits happen inside GitHub
2. Which syntax correctly defines a GitHub Actions step to run terraform init?
easy
A. - name: Terraform Init command: terraform init
B. - run: terraform init name: Terraform Init
C. - step: terraform init run: true
D. - name: Terraform Init run: terraform init

Solution

  1. Step 1: Check GitHub Actions step syntax

    Steps use name and run keys to describe and execute commands.
  2. Step 2: Validate correct order and keys

    - name: Terraform Init run: terraform init uses name then run with the correct command string.
  3. Final Answer:

    - name: Terraform Init run: terraform init -> Option D
  4. Quick Check:

    Step keys = name + run [OK]
Hint: GitHub Actions steps use 'name' then 'run' keys [OK]
Common Mistakes:
  • Using 'command' instead of 'run'
  • Swapping order of keys causing confusion
  • Using invalid keys like 'step'
3. Given this GitHub Actions snippet, what will happen when a push occurs?
jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Terraform Init
        run: terraform init
      - name: Terraform Plan
        run: terraform plan
medium
A. The workflow will fail due to missing apply step
B. Terraform will initialize and then create a plan for changes
C. Terraform will only checkout the code without running commands
D. Terraform will apply changes automatically

Solution

  1. Step 1: Analyze the steps in the workflow

    The workflow checks out code, runs terraform init, then runs terraform plan.
  2. Step 2: Understand Terraform commands effect

    terraform init prepares the environment; terraform plan shows what changes would happen but does not apply them.
  3. Final Answer:

    Terraform will initialize and then create a plan for changes -> Option B
  4. Quick Check:

    Init + Plan = prepare and preview [OK]
Hint: Init prepares, Plan previews changes, Apply makes changes [OK]
Common Mistakes:
  • Confusing plan with apply
  • Assuming apply runs automatically
  • Ignoring checkout step importance
4. You wrote this GitHub Actions step but it fails:
- name: Terraform Apply
  run: terraform apply -auto-approve
What is a common reason for failure in this context?
medium
A. Missing terraform init before apply
B. Using -auto-approve flag incorrectly
C. GitHub Actions does not support terraform apply
D. The step name must be 'Apply Terraform' exactly

Solution

  1. Step 1: Check Terraform command requirements

    Terraform requires terraform init to run first to set up backend and providers.
  2. Step 2: Identify missing initialization

    If terraform init is missing, terraform apply will fail due to uninitialized state.
  3. Final Answer:

    Missing terraform init before apply -> Option A
  4. Quick Check:

    Init must run before apply [OK]
Hint: Always run 'terraform init' before 'terraform apply' [OK]
Common Mistakes:
  • Thinking -auto-approve causes failure
  • Believing GitHub Actions blocks apply commands
  • Assuming step name affects execution
5. You want to securely store Terraform state remotely and run terraform apply only after manual approval in GitHub Actions. Which setup is best?
hard
A. Use a remote backend like AWS S3 for state and add a manual approval job before apply
B. Store state in GitHub repo and run apply automatically after plan
C. Keep state local and run apply in the same job as plan
D. Use GitHub Secrets to store state file content and apply immediately

Solution

  1. Step 1: Secure state storage best practice

    Remote backends like AWS S3 keep Terraform state safe and shared among users.
  2. Step 2: Implement manual approval in workflow

    GitHub Actions supports manual approval jobs to pause before applying changes.
  3. Step 3: Combine both for safe, controlled deployment

    Using remote state plus manual approval ensures safety and control over apply.
  4. Final Answer:

    Use a remote backend like AWS S3 for state and add a manual approval job before apply -> Option A
  5. Quick Check:

    Remote state + manual approval = safe apply [OK]
Hint: Remote state + manual approval = secure, controlled apply [OK]
Common Mistakes:
  • Storing state in repo risking conflicts
  • Running apply automatically without checks
  • Using secrets to store entire state file