Jenkins With Terraform and Ansible: Plan, Approve and Apply Infrastructure From a Pipeline
Infrastructure Needs a Pipeline Too
When infrastructure is code (Terraform, Ansible), changes deserve the same review, test and approval as application code. Running terraform apply from a laptop is risky: no review, no history, wrong environment by mistake. A pipeline makes every change visible, checked and logged.
text
pull request ─► fmt + validate + lint + policy scan ─► terraform plan (shown in the PR)
merge to main ─► plan again ─► [human approval] ─► apply the SAME plan file ─► verify
Terraform Pipeline
groovy
pipeline {
agent { docker { image 'hashicorp/terraform:1.9'; args '--entrypoint=""' } }
parameters { choice(name: 'ENV', choices: ['dev', 'staging', 'prod'], description: 'Target environment') }
environment {
TF_IN_AUTOMATION = 'true'
TF_INPUT = 'false'
TF_DIR = "envs/${params.ENV}"
}
options { disableConcurrentBuilds(); timeout(time: 1, unit: 'HOURS') }
stages {
stage('Init') {
steps {
dir(env.TF_DIR) {
withCredentials([aws(credentialsId: 'aws-terraform', accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY')]) {
sh 'terraform init -backend-config=backend.hcl -lockfile=readonly'
}
}
}
}
stage('Format and validate') {
steps { dir(env.TF_DIR) { sh 'terraform fmt -check -recursive && terraform validate' } }
}
stage('Policy scan') {
steps { sh 'docker run --rm -v "$PWD:/src" aquasec/tfsec:latest /src/envs --soft-fail=false || true' }
}
stage('Plan') {
steps {
dir(env.TF_DIR) {
withCredentials([aws(credentialsId: 'aws-terraform', accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY')]) {
sh 'terraform plan -out=tfplan -detailed-exitcode || [ $? -eq 2 ]'
sh 'terraform show -no-color tfplan > plan.txt'
}
}
archiveArtifacts artifacts: "${env.TF_DIR}/plan.txt", fingerprint: true
}
}
stage('Approve') {
when { allOf { branch 'main'; expression { params.ENV != 'dev' } } }
steps {
timeout(time: 1, unit: 'DAYS') {
input message: "Apply plan to ${params.ENV}? Review plan.txt in the artifacts.", submitter: 'infra-approvers'
}
}
}
stage('Apply') {
when { branch 'main' }
steps {
dir(env.TF_DIR) {
withCredentials([aws(credentialsId: 'aws-terraform', accessKeyVariable: 'AWS_ACCESS_KEY_ID', secretKeyVariable: 'AWS_SECRET_ACCESS_KEY')]) {
sh 'terraform apply -input=false tfplan'
}
}
}
}
}
}
-out=tfplan saves the plan; apply tfplan applies exactly what was reviewed
-detailed-exitcode returns 2 when changes exist; the line || [ $? -eq 2 ] treats that as success
TF_IN_AUTOMATION and -input=false stop prompts that would hang the job
-lockfile=readonly fails if provider versions differ from the committed lock file
- Plan on pull requests, apply only on
main
- Archive
plan.txt so approvers can read it. The plan can contain secrets, so restrict who can read artifacts
Remote State and Locking
hcl
# backend.tf
terraform {
backend "s3" {}
}
# backend.hcl for env dev
bucket = "mycompany-tf-state"
key = "shop/dev/terraform.tfstate"
region = "eu-west-1"
dynamodb_table = "tf-locks"
encrypt = true
- State must be remote, encrypted, versioned and locked: never in the Jenkins workspace
- Locking blocks two applies at once. Use the backend's lock mechanism (and
disableConcurrentBuilds)
- One state per environment and per component limits the blast radius
- State can contain secrets: restrict access to the bucket
Environments
| Approach | Notes |
Folders per environment (envs/dev, envs/prod) with shared modules | Clear, easy to review, safe. Recommended |
| Terraform workspaces | One code, many states. Easy to apply to the wrong one. Use with care |
| Separate repos or accounts | Strongest isolation for production |
Cloud Credentials Without Long-Lived Keys
- Use an IAM role on the agent (instance profile, IRSA on Kubernetes) so no key is stored
- Or use OIDC federation or
sts assume-role to get temporary credentials per build
- Give the pipeline role only the permissions Terraform needs. Separate roles for plan (read-only) and apply
groovy
withAWS(role: 'terraform-apply', roleAccount: '123456789012', duration: 3600, roleSessionName: "jenkins-${env.BUILD_NUMBER}") {
sh 'terraform apply -input=false tfplan'
}
Policy and Security Checks
| Tool | Checks |
terraform fmt, validate | Format and syntax |
| tflint | Provider-specific errors, naming, deprecated syntax |
| tfsec / Trivy config / Checkov | Open security groups, unencrypted storage, public buckets |
| OPA / Sentinel / Conftest | Company rules: required tags, allowed regions, cost limits |
| Infracost | Estimate the price change of a plan |
groovy
stage('Checkov') {
steps { sh 'docker run --rm -v "$PWD:/tf" bridgecrew/checkov -d /tf --quiet --compact' }
}
Ansible From Jenkins
groovy
stage('Configure servers') {
agent { docker { image 'cytopia/ansible:latest-tools' } }
steps {
withCredentials([
sshUserPrivateKey(credentialsId: 'ansible-ssh', keyFileVariable: 'SSH_KEY', usernameVariable: 'SSH_USER'),
string(credentialsId: 'ansible-vault-pass', variable: 'VAULT_PASS')
]) {
sh '''
echo "$VAULT_PASS" > .vault_pass && chmod 600 .vault_pass
ansible-lint playbooks/site.yml
ansible-playbook playbooks/site.yml -i inventories/${ENV}/hosts.ini \
--private-key "$SSH_KEY" -u "$SSH_USER" --vault-password-file .vault_pass --check --diff
rm -f .vault_pass
'''
}
}
}
- Run with
--check --diff first (dry run), then approve and run for real
- Keep inventories per environment and secrets in Ansible Vault or an external vault
- Use
--limit to roll out gradually (one group at a time)
- Make playbooks idempotent and test them with Molecule
- Delete temporary secret files at the end (
rm -f), also on failure: put it in post { always { ... } }
Dynamic Inventory
After Terraform creates machines, Ansible can discover them with a dynamic inventory plugin (for example amazon.aws.aws_ec2) using tags. This avoids copying IP addresses by hand.
yaml
# inventories/prod/aws_ec2.yml
plugin: amazon.aws.aws_ec2
regions: [eu-west-1]
filters:
tag:Environment: prod
keyed_groups:
- key: tags.Role
prefix: role
Drift Detection
Someone may change infrastructure by hand. A scheduled pipeline can detect this.
groovy
pipeline {
agent any
triggers { cron('H 6 * * 1-5') }
stages {
stage('Drift check') {
steps {
script {
def rc = sh(script: 'cd envs/prod && terraform init -input=false && terraform plan -detailed-exitcode -input=false', returnStatus: true)
if (rc == 2) { slackSend channel: '#infra', color: 'warning', message: "Terraform drift in prod: ${env.BUILD_URL}"; currentBuild.result = 'UNSTABLE' }
else if (rc != 0) { error 'terraform plan failed' }
}
}
}
}
}
Rules for Safe Infrastructure Pipelines
- Only main applies; pull requests only plan
- Review the plan, not just the code
- Apply the saved plan
- One apply at a time per state
- Use separate credentials per environment; production approvers are different people
- Protect destroy: require a dedicated job, extra approval, and
prevent_destroy lifecycle on critical resources
- Keep modules versioned and pinned
Practice Tasks
- Create a small Terraform project (one storage bucket or one VM) with remote state
- Write the pipeline: init, fmt, validate, plan, approval, apply
- Run tfsec or Checkov and fix one finding
- Run an Ansible playbook with
--check --diff from Jenkins
- Add a nightly drift check and change a resource by hand to trigger it
Conclusion
Treat infrastructure like application code: plan on pull requests, require approval, and apply the saved plan from main using remote locked state and short-lived cloud access. Scan policies, run Ansible with check mode first, detect drift on a schedule, and protect production and destroy actions.
Quick Summary: plan -out + apply tfplan; remote state + locks; env folders; role/OIDC creds; fmt/validate/tfsec/Checkov; Ansible check/diff + vault; dynamic inventory; drift job; safety rules.