Automate Terraform infrastructure deployment using a robust CI/CD pipeline with Jenkins, GitHub Actions, or GitLab CI. Ensure all infrastructure changes are version-controlled, reviewed via pull requests (PRs), and deployed automatically.
terraform fmt
)terraform validate
)terraform plan
).main
branch.terraform fmt
, terraform validate
, and terraform plan
.main
branchterraform fmt
, terraform validate
)terraform plan
)terraform apply
)pipeline {
agent any
environment {
AWS_ACCESS_KEY_ID = credentials('aws-access-key')
AWS_SECRET_ACCESS_KEY = credentials('aws-secret-key')
}
stages {
stage('Checkout Code') {
steps {
git 'https://github.com/org/repo.git'
}
}
stage('Terraform Init') {
steps {
sh 'terraform init'
}
}
stage('Terraform Validate') {
steps {
sh 'terraform validate'
}
}
stage('Terraform Plan') {
steps {
sh 'terraform plan'
}
}
stage('Terraform Apply') {
when {
branch 'main'
}
steps {
sh 'terraform apply -auto-approve'
}
}
}
}
Create .github/workflows/terraform.yml:
name: Terraform Deployment
on:
pull_request:
branches:
- main
push:
branches:
- main
jobs:
terraform:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Setup Terraform
uses: hashicorp/setup-terraform@v2
- name: Terraform Init
run: terraform init
- name: Terraform Validate
run: terraform validate
- name: Terraform Plan
run: terraform plan
- name: Terraform Apply
if: github.ref == 'refs/heads/main'
run: terraform apply -auto-approve
Add .gitlab-ci.yml:
stages:
- validate
- plan
- apply
variables:
TF_IN_AUTOMATION: "true"
validate:
stage: validate
script:
- terraform init
- terraform validate
only:
- merge_requests
plan:
stage: plan
script:
- terraform plan
only:
- merge_requests
apply:
stage: apply
script:
- terraform apply -auto-approve
only:
- main