Bird
Raised Fist0
Terraformcloud~30 mins

Terraform in GitLab CI - Mini Project: Build & Apply

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
Terraform in GitLab CI
📖 Scenario: You are working as a cloud engineer who wants to automate infrastructure deployment using Terraform. Your team uses GitLab for version control and CI/CD pipelines. You want to create a GitLab CI pipeline that runs Terraform commands to plan and apply infrastructure changes automatically.
🎯 Goal: Build a GitLab CI configuration file .gitlab-ci.yml that initializes Terraform, runs terraform plan, and applies the plan with terraform apply in a safe and automated way.
📋 What You'll Learn
Create a GitLab CI pipeline with three stages: init, plan, and apply
Use the official Terraform Docker image for all jobs
Initialize Terraform in the init stage
Run terraform plan in the plan stage and save the plan output
Run terraform apply in the apply stage using the saved plan
Use environment variables for Terraform backend configuration
Ensure the apply stage only runs after a successful plan
💡 Why This Matters
🌍 Real World
Automating Terraform deployments in GitLab CI saves time and reduces errors by running infrastructure commands automatically on code changes.
💼 Career
Cloud engineers and DevOps professionals use GitLab CI pipelines to manage infrastructure as code with Terraform in real projects.
Progress0 / 4 steps
1
Create the basic GitLab CI pipeline structure
Create a file named .gitlab-ci.yml with a stages section that lists the stages init, plan, and apply in that order.
Terraform
Hint

Define the stages key as a list with the three stages in order.

2
Add the init job to initialize Terraform
Add a job named terraform_init that runs in the init stage. Use the image hashicorp/terraform:latest. The job should run the command terraform init. Use environment variables TF_BACKEND_CONFIG for backend configuration by passing -backend-config=${TF_BACKEND_CONFIG} to terraform init.
Terraform
Hint

Define the job with the correct name, stage, image, and script command using the environment variable.

3
Add the plan job to create a Terraform plan
Add a job named terraform_plan that runs in the plan stage. Use the same Terraform image. The job should run terraform init -backend-config=${TF_BACKEND_CONFIG} followed by terraform plan -out=tfplan to save the plan output to a file named tfplan. Make sure this job depends on the terraform_init job by using needs. Also, add artifacts to save the tfplan file for the next stage.
Terraform
Hint

Use needs to depend on the init job and artifacts to pass the plan file.

4
Add the apply job to apply the Terraform plan
Add a job named terraform_apply that runs in the apply stage. Use the Terraform image. This job should depend on terraform_plan using needs. It should run terraform init -backend-config=${TF_BACKEND_CONFIG} followed by terraform apply -auto-approve tfplan to apply the saved plan without manual approval.
Terraform
Hint

Use needs to depend on the plan job and run terraform apply with the saved plan file.

Practice

(1/5)
1. What is the main purpose of using Terraform in a GitLab CI pipeline?
easy
A. To write application code
B. To automate the creation and management of cloud resources
C. To monitor server performance
D. To manage user access permissions

Solution

  1. Step 1: Understand Terraform's role

    Terraform is a tool designed to automate cloud infrastructure setup and changes.
  2. Step 2: Understand GitLab CI's role

    GitLab CI automates running tasks like Terraform commands in a pipeline.
  3. Final Answer:

    To automate the creation and management of cloud resources -> Option B
  4. Quick Check:

    Terraform automates cloud resource management = B [OK]
Hint: Terraform manages infrastructure automatically in CI pipelines [OK]
Common Mistakes:
  • Confusing Terraform with application code tools
  • Thinking GitLab CI monitors servers directly
  • Mixing user access management with infrastructure automation
2. Which GitLab CI stage is typically used to check Terraform configuration syntax before planning?
easy
A. deploy
B. apply
C. validate
D. build

Solution

  1. Step 1: Identify Terraform stages in GitLab CI

    Common stages are validate, plan, and apply.
  2. Step 2: Match stage to syntax check

    The validate stage checks Terraform files for syntax errors before any changes.
  3. Final Answer:

    validate -> Option C
  4. Quick Check:

    Syntax check stage = validate [OK]
Hint: Validate stage checks syntax before planning [OK]
Common Mistakes:
  • Confusing apply with validation
  • Using deploy which is not a Terraform stage
  • Thinking build is related to Terraform syntax
3. Given this GitLab CI snippet:
stages:
  - validate
  - plan
  - apply

validate:
  script:
    - terraform validate

plan:
  script:
    - terraform plan -out=tfplan

apply:
  script:
    - terraform apply tfplan
  when: manual

What happens when the pipeline reaches the apply stage?
medium
A. Terraform waits for manual approval before applying changes
B. Terraform apply is skipped because of manual trigger
C. Terraform plan is rerun before applying
D. Terraform applies changes automatically without user input

Solution

  1. Step 1: Understand the 'when: manual' keyword

    This setting means the apply job waits for a user to start it manually.
  2. Step 2: Check apply stage behavior

    Apply will not run automatically; it requires manual approval to proceed.
  3. Final Answer:

    Terraform waits for manual approval before applying changes -> Option A
  4. Quick Check:

    Manual apply means wait for approval = D [OK]
Hint: 'when: manual' means manual approval needed [OK]
Common Mistakes:
  • Assuming apply runs automatically
  • Thinking manual means skip permanently
  • Confusing plan rerun with apply stage
4. You have this GitLab CI job:
apply:
  script:
    - terraform apply tfplan
  when: manual
  only:
    - main

But the apply job runs on every branch, not just main. What is the likely cause?
medium
A. The 'only' keyword is deprecated and ignored; use 'rules' instead
B. The 'when: manual' overrides branch filtering
C. The job name 'apply' is reserved and runs always
D. The pipeline is misconfigured and needs a restart

Solution

  1. Step 1: Recognize GitLab CI syntax changes

    GitLab deprecated 'only' in favor of 'rules' for better control.
  2. Step 2: Understand effect on job filtering

    Using 'only' may not filter branches correctly, causing job to run everywhere.
  3. Final Answer:

    The 'only' keyword is deprecated and ignored; use 'rules' instead -> Option A
  4. Quick Check:

    Use 'rules' not 'only' for branch filters [OK]
Hint: 'only' is deprecated; use 'rules' for branch filters [OK]
Common Mistakes:
  • Thinking 'when: manual' affects branch filtering
  • Believing job names control execution
  • Restarting pipeline without fixing config
5. You want to ensure Terraform plans only run on merge requests and applies only happen after manual approval on the main branch. Which GitLab CI configuration snippet achieves this?
hard
A.
plan:
  script:
    - terraform plan
  only:
    - merge_requests

apply:
  script:
    - terraform apply
  only:
    - main
  when: manual
B.
plan:
  script:
    - terraform plan
  only:
    - main

apply:
  script:
    - terraform apply
  when: manual
C.
plan:
  script:
    - terraform plan
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: always

apply:
  script:
    - terraform apply
  rules:
    - if: '$CI_MERGE_REQUEST_ID'
      when: manual
D.
plan:
  script:
    - terraform plan
  rules:
    - if: '$CI_MERGE_REQUEST_ID'
      when: always
    - when: never

apply:
  script:
    - terraform apply
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'
      when: manual
    - when: never

Solution

  1. Step 1: Configure plan job for merge requests only

    Using rules with '$CI_MERGE_REQUEST_ID' ensures plan runs only on MRs.
  2. Step 2: Configure apply job for manual approval on main branch

    Rules with branch check and 'when: manual' ensure manual apply on main only.
  3. Step 3: Confirm why other configurations fail

    Other configurations either use the deprecated 'only' keyword or reverse the conditions (plan on main and apply on merge requests).
  4. Final Answer:

    The configuration using rules with $CI_MERGE_REQUEST_ID for plan and $CI_COMMIT_BRANCH == "main" for manual apply -> Option D
  5. Quick Check:

    Use 'rules' with MR and branch checks for plan/apply [OK]
Hint: Use 'rules' with MR and branch checks for plan/apply [OK]
Common Mistakes:
  • Using deprecated 'only' keyword
  • Mixing up branch and merge request conditions
  • Forgetting 'when: manual' for apply