Professional CI/CD Pipeline with Terraform
Below is a comprehensive CI/CD pipeline implementation using Terraform to manage infrastructure as code. This pipeline includes stages for planning, applying, testing, and deploying infrastructure changes.
Pipeline Overview
- Plan Stage: Validates and generates an execution plan
- Apply Stage: Applies the Terraform configuration
- Test Stage: Runs automated tests against the deployed infrastructure
- Deploy Stage: Promotes changes to production (if applicable)
Terraform Configuration
First, let's create a basic Terraform configuration structure:
terraform/
├── main.tf # Main infrastructure definition
├── variables.tf # Input variables
├── outputs.tf # Output values
├── versions.tf # Terraform and provider versions
└── modules/ # Reusable modules
Example main.tf:
terraform {
required_version = ">= 1.0.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = var.aws_region
}
module "vpc" {
source = "./modules/vpc"
# module-specific variables
}
module "ec2" {
source = "./modules/ec2"
# module-specific variables
}
CI/CD Pipeline Implementation
1. GitHub Actions Workflow (.github/workflows/terraform.yml)
name: Terraform CI/CD Pipeline
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
env:
TF_VERSION: "1.5.7"
TF_WORKING_DIR: "./terraform"
AWS_REGION: "us-east-1"
jobs:
terraform:
name: Terraform
runs-on: ubuntu-latest
environment: production
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
with:
terraform_version: ${{ env.TF_VERSION }}
- name: Configure AWS Credentials
uses: aws-actions/configure-aws-credentials@v2
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: ${{ env.AWS_REGION }}
- name: Terraform Init
id: init
run: terraform init
working-directory: ${{ env.TF_WORKING_DIR }}
- name: Terraform Format Check
id: fmt
run: terraform fmt -check -diff -recursive
working-directory: ${{ env.TF_WORKING_DIR }}
- name: Terraform Validate
id: validate
run: terraform validate
working-directory: ${{ env.TF_WORKING_DIR }}
- name: Terraform Plan
id: plan
if: github.event_name == 'pull_request'
run: |
terraform plan -no-color -input=false -out=tfplan \
-var="environment=${{ github.event.pull_request.title }}" \
-var-file="terraform.tfvars"
terraform show -json tfplan > tfplan.json
working-directory: ${{ env.TF_WORKING_DIR }}
- name: Terraform Apply
id: apply
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: |
terraform apply -auto-approve -input=false \
-var="environment=production" \
-var-file="terraform.tfvars"
working-directory: ${{ env.TF_WORKING_DIR }}
- name: Run Infrastructure Tests
id: test
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
run: |
# Example test command - replace with your actual test framework
terraform test
working-directory: ${{ env.TF_WORKING_DIR }}
- name: Upload Terraform Plan Artifact
if: always() && github.event_name == 'pull_request'
uses: actions/upload-artifact@v3
with:
name: tfplan
path: ${{ env.TF_WORKING_DIR }}/tfplan
if-no-files-found: error
- name: Upload Terraform Plan JSON Artifact
if: always() && github.event_name == 'pull_request'
uses: actions/upload-artifact@v3
with:
name: tfplan-json
path: ${{ env.TF_WORKING_DIR }}/tfplan.json
if-no-files-found: error
2. GitLab CI/CD Pipeline (.gitlab-ci.yml)
stages:
- init
- validate
- plan
- apply
- test
variables:
TF_VERSION: "1.5.7"
TF_WORKING_DIR: "terraform"
AWS_REGION: "us-east-1"
before_script:
- terraform --version
- cd $TF_WORKING_DIR
init:
stage: init
script:
- terraform init
artifacts:
paths:
- $TF_WORKING_DIR/.terraform
expire_in: 1 hour
validate:
stage: validate
script:
- terraform validate
- terraform fmt -check -diff -recursive
plan:
stage: plan
script:
- terraform plan -no-color -input=false -out=tfplan -var="environment=staging" -var-file="terraform.tfvars"
artifacts:
paths:
- $TF_WORKING_DIR/tfplan
expire_in: 1 hour
when: manual
only:
- merge_requests
apply:
stage: apply
script:
- terraform apply -auto-approve -input=false -var="environment=production" -var-file="terraform.tfvars"
when: manual
only:
- main
test:
stage: test
script:
- terraform test
when: on_success
only:
- main
3. Azure DevOps Pipeline (azure-pipelines.yml)
trigger:
branches:
include:
- main
pr:
branches:
include:
- main
variables:
TF_VERSION: '1.5.7'
TF_WORKING_DIR: '$(System.DefaultWorkingDirectory)/terraform'
AWS_REGION: 'us-east-1'
pool:
vmImage: 'ubuntu-latest'
steps:
- task: UsePythonVersion@0
inputs:
versionSpec: '3.x'
addToPath: true
- script: |
python -m pip install --upgrade pip
pip install terraform
displayName: 'Install Terraform'
- task: TerraformInstaller@0
inputs:
terraformVersion: '$(TF_VERSION)'
- task: TerraformInit@0
inputs:
command: 'init'
workingDirectory: '$(TF_WORKING_DIR)'
backendType: 'azurerm'
backendServiceArm: 'AzureServiceConnection'
backendAzureRmResourceGroupName: 'tfstate-rg'
backendAzureRmStorageAccountName: 'tfstatestorage'
backendAzureRmStorageAccountSku: 'Standard_LRS'
backendAzureRmContainerName: 'tfstate'
backendAzureRmKey: 'prod.terraform.tfstate'
- task: TerraformValidate@0
inputs:
command: 'validate'
workingDirectory: '$(TF_WORKING_DIR)'
- task: TerraformPlan@0
inputs:
command: 'plan'
workingDirectory: '$(TF_WORKING_DIR)'
environmentServiceNameAzureRM: 'AzureServiceConnection'
commandOptions: '-var="environment=staging" -var-file="terraform.tfvars"'
publishPlanResults: 'TerraformPlan'
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
- task: TerraformApply@0
inputs:
command: 'apply'
workingDirectory: '$(TF_WORKING_DIR)'
environmentServiceNameAzureRM: 'AzureServiceConnection'
commandOptions: '-var="environment=production" -var-file="terraform.tfvars" -auto-approve'
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
- task: TerraformTest@0
inputs:
command: 'test'
workingDirectory: '$(TF_WORKING_DIR)'
condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
Best Practices for Terraform CI/CD
-
State Management:
- Use remote state storage (S3, Azure Blob, etc.)
- Enable state locking
- Consider using Terraform Cloud for advanced features
-
Security:
- Use secrets management for credentials
- Implement least privilege access
- Scan for secrets in your Terraform files
-
Testing:
- Implement pre-apply testing (e.g., with Terratest)
- Include post-deployment validation tests
- Consider using OPA/Policy as Code for compliance checks
-
Workflow:
- Plan on PRs, apply on main branch
- Implement approval gates for production deployments
- Use separate workspaces for different environments
-
Monitoring:
- Track Terraform runs and changes
- Set up alerts for drift detection
- Monitor cost implications of changes
This pipeline provides a solid foundation that you can customize based on your specific requirements and cloud provider.