GitLab CI Terraform Pipeline
Automated Terraform Planning and Manual Apply
This GitLab CI configuration automates the process of managing your infrastructure as code using Terraform. It defines stages for validation, planning, and applying infrastructure changes, ensuring a controlled and repeatable deployment workflow.
The pipeline is designed to work with different branches, providing flexibility for development and production deployments. By leveraging Terraform's plan and apply commands within GitLab CI, you can maintain a clear audit trail and reduce the risk of manual errors.
Pipeline Stages Overview
The pipeline is structured into three main stages:
- validate: This stage runs
terraform validate
to check the syntax and integrity of your Terraform configuration files. - plan: In this stage,
terraform plan
is executed to generate an execution plan. This plan outlines the changes that will be made to your infrastructure. Different jobs are configured for regular branches and the main branch. - apply: This stage is responsible for applying the infrastructure changes. The
terraform apply
command is used, and for the main branch, it's set to run manually, providing an extra layer of control before changes are deployed.
Configuration Details
The pipeline uses the official hashicorp/terraform:1.2.5
Docker image. Key configurations include:
- Artifacts: Terraform plan files (
deploy.tfplan
) and lock files (.terraform.lock.hcl
) are saved as artifacts for later use and auditing. - Environment Variables: The pipeline assumes a variable
$TERRAFORM_VARS_FILE
is set for specifying Terraform variable files. - Branching Strategy: Jobs are configured to run on specific branches using
only
andexcept
keywords, differentiating between development branches and themain
branch. - Manual Apply: The
apply-dev
job is set towhen: manual
, requiring explicit user intervention to proceed with applying changes to the development environment.
For more information on Terraform and GitLab CI, refer to the official documentation:
# terraform pipeline to plan automatically and manual apply
image:
name: hashicorp/terraform:1.2.5
entrypoint: [""]
stages:
- validate
- plan
- apply
.terraform:
artifacts:
paths:
- '**/deploy.tfplan'
- '**/.terraform.lock.hcl'
before_script:
- cd environments/dev
- terraform --version
- terraform init
validate:
stage: validate
script:
- terraform validate
only:
- branches
except:
- main
plan-branch:
environment:
name: dev
action: prepare
extends: .terraform
stage: plan
script:
- terraform plan --var-file $TERRAFORM_VARS_FILE -input=false
only:
- branches
except:
- main
plan-dev:
environment:
name: dev
action: prepare
extends: .terraform
stage: plan
script:
- terraform plan --var-file $TERRAFORM_VARS_FILE -input=false -out deploy.tfplan
only:
- main
apply-dev:
extends: .terraform
environment:
name: dev
action: start
stage: apply
script:
- terraform apply -input=false -auto-approve deploy.tfplan
when: manual
allow_failure: false
only:
- main