0
0
Terraformcloud~5 mins

Terraform in GitLab CI - Commands & Configuration

Choose your learning style9 modes available
Introduction
Terraform helps you create and change cloud resources automatically. GitLab CI runs Terraform commands in a pipeline to apply these changes safely and repeatedly.
When you want to automatically create cloud servers every time you update your code.
When you need to check if your cloud setup is correct before making changes.
When you want to share your cloud setup steps with your team in a repeatable way.
When you want to keep track of changes to your cloud resources in your code repository.
When you want to avoid manual mistakes by automating cloud resource updates.
Config File - .gitlab-ci.yml
.gitlab-ci.yml
stages:
  - validate
  - plan
  - apply

variables:
  TF_ROOT: "terraform"
  TF_STATE_BUCKET: "my-terraform-state"
  TF_STATE_KEY: "example/terraform.tfstate"
  TF_BACKEND_CONFIG: "bucket=${TF_STATE_BUCKET} key=${TF_STATE_KEY} region=us-east-1"

validate:
  stage: validate
  image: hashicorp/terraform:1.5.7
  script:
    - cd $TF_ROOT
    - terraform init -backend-config="$TF_BACKEND_CONFIG"
    - terraform validate

plan:
  stage: plan
  image: hashicorp/terraform:1.5.7
  script:
    - cd $TF_ROOT
    - terraform init -backend-config="$TF_BACKEND_CONFIG"
    - terraform plan -out=tfplan
  artifacts:
    paths:
      - $TF_ROOT/tfplan

apply:
  stage: apply
  image: hashicorp/terraform:1.5.7
  script:
    - cd $TF_ROOT
    - terraform init -backend-config="$TF_BACKEND_CONFIG"
    - terraform apply -auto-approve tfplan
  when: manual
  dependencies:
    - plan

This GitLab CI file defines three stages: validate, plan, and apply.

Variables set the Terraform folder and backend state storage details.

Each job uses the official Terraform Docker image version 1.5.7.

The validate job checks the Terraform files for errors.

The plan job creates a plan file showing what changes Terraform will make.

The apply job applies the changes from the plan file and is set to run manually to avoid accidental changes.

Commands
Push your Terraform code and GitLab CI file to the main branch to start the pipeline.
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 2), reused 0 (delta 0) remote: Resolving deltas: 100% (2/2), completed with 2 local objects. To https://gitlab.com/yourusername/yourrepo.git abc1234..def5678 main -> main
Initialize Terraform in the terraform folder with backend config to store state remotely in S3-compatible storage.
Terminal
terraform init -backend-config="bucket=my-terraform-state key=example/terraform.tfstate region=us-east-1"
Expected OutputExpected
Initializing the backend... Successfully configured the backend "s3"! Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes.
-backend-config - Specifies backend storage details for Terraform state.
Check the Terraform files for syntax errors and correctness before planning or applying.
Terminal
terraform validate
Expected OutputExpected
Success! The configuration is valid.
Create a plan file that shows what changes Terraform will make to the cloud resources.
Terminal
terraform plan -out=tfplan
Expected OutputExpected
Refreshing Terraform state in-memory prior to plan... An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_instance.example will be created + resource "aws_instance" "example" { + ami = "ami-12345678" + instance_type = "t2.micro" } Plan: 1 to add, 0 to change, 0 to destroy. ------------------------------------------------------------------------ This plan was saved to: tfplan To perform exactly these actions, run the following command to apply: terraform apply "tfplan"
-out - Saves the plan to a file for later apply.
Apply the changes from the saved plan file automatically without asking for confirmation.
Terminal
terraform apply -auto-approve tfplan
Expected OutputExpected
aws_instance.example: Creating... aws_instance.example: Still creating... [10s elapsed] aws_instance.example: Creation complete after 20s [id=i-0abcd1234efgh5678] Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
-auto-approve - Skips interactive approval before applying.
Key Concept

If you remember nothing else from this pattern, remember: automate Terraform commands in GitLab CI stages to safely validate, plan, and apply cloud changes.

Common Mistakes
Running terraform apply without a saved plan file.
This can cause unexpected changes because the apply runs a new plan without review.
Always run terraform plan -out=tfplan first and then terraform apply tfplan.
Not initializing Terraform with the correct backend config in each job.
Terraform won't know where to store or read the state, causing errors or state conflicts.
Run terraform init with the same backend-config in every job before plan or apply.
Setting apply job to run automatically without manual approval.
This risks unintended changes to cloud resources on every pipeline run.
Set apply job to manual trigger to review plan before applying.
Summary
Push Terraform code and GitLab CI config to trigger the pipeline.
Use terraform init with backend config to set up remote state storage.
Run terraform validate to check code correctness.
Run terraform plan to create a change plan and save it.
Run terraform apply manually using the saved plan to update cloud resources safely.