Bird
Raised Fist0
Terraformcloud~10 mins

Terraform in GitLab CI - Step-by-Step Execution

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
Process Flow - Terraform in GitLab CI
Start: GitLab CI Pipeline Triggered
Checkout Code with Terraform Files
Initialize Terraform (terraform init)
Plan Infrastructure Changes (terraform plan)
Apply Changes (terraform apply -auto-approve)
Output Results (terraform output) and End Pipeline
This flow shows how GitLab CI runs Terraform commands step-by-step to manage infrastructure automatically.
Execution Sample
Terraform
stages:
  - terraform

terraform_apply:
  stage: terraform
  script:
    - terraform init
    - terraform plan
    - terraform apply -auto-approve
    - terraform output
This GitLab CI YAML runs Terraform init, plan, apply, and output commands in order to deploy infrastructure.
Process Table
StepGitLab CI Job ActionTerraform CommandResultNext Step
1Checkout codeN/ATerraform files availableterraform init
2Initialize Terraformterraform initBackend and providers configuredterraform plan
3Plan changesterraform planShows planned infrastructure changesterraform apply
4Apply changesterraform apply -auto-approveInfrastructure created/updatedOutput results
5Output resultsterraform outputOutputs displayedPipeline ends
6Pipeline endsN/AInfrastructure deployed successfullyEND
💡 Pipeline ends after successful Terraform apply and output steps.
Status Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
Terraform FilesNot checked outChecked outChecked outChecked outChecked out
Terraform StateEmptyInitialized backendPlanned changes readyUpdated with applied changesUpdated
InfrastructureNoneNonePlanned changes identifiedCreated/UpdatedCreated/Updated
OutputsNoneNoneNoneGeneratedDisplayed
Key Moments - 3 Insights
Why do we run 'terraform init' before 'terraform plan'?
'terraform init' sets up backend and providers needed for Terraform to work. Without it, 'terraform plan' cannot run properly. See execution_table step 2.
What happens if 'terraform apply' is run without '-auto-approve' in GitLab CI?
GitLab CI will wait for manual approval which blocks the pipeline. Using '-auto-approve' allows automatic apply without manual input. See execution_table step 4.
Why do we checkout code first in the pipeline?
Terraform files must be available locally to run commands. Without checkout, Terraform commands fail. See execution_table step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result after running 'terraform plan' at step 3?
ABackend and providers configured
BShows planned infrastructure changes
CInfrastructure created/updated
DOutputs displayed
💡 Hint
Check the 'Result' column for step 3 in execution_table.
At which step does the GitLab CI pipeline apply infrastructure changes automatically?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look for 'terraform apply -auto-approve' in the 'Terraform Command' column.
If the 'terraform init' command fails, what will happen to the pipeline according to the flow?
APipeline continues to 'terraform plan'
BPipeline skips to output results
CPipeline stops and reports error
DPipeline applies changes anyway
💡 Hint
Refer to the logical flow where each step depends on the previous successful step.
Concept Snapshot
Terraform in GitLab CI:
- Checkout code with Terraform files
- Run 'terraform init' to setup
- Run 'terraform plan' to preview changes
- Run 'terraform apply -auto-approve' to deploy
- Output results and finish pipeline
- Each step depends on success of previous
Full Transcript
This visual execution shows how GitLab CI automates Terraform infrastructure deployment. First, the pipeline checks out the code containing Terraform files. Then it runs 'terraform init' to configure backend and providers. Next, 'terraform plan' previews infrastructure changes. If all is good, 'terraform apply -auto-approve' deploys the changes automatically without manual approval. Finally, outputs are displayed and the pipeline ends. Each step must succeed for the next to run. This ensures safe, automated infrastructure management in GitLab CI.

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