Skip to content

Instantly share code, notes, and snippets.

@andymotta
Created December 28, 2018 21:26
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save andymotta/5484f1d2a8f6d8eb3b18f5d415ef3de5 to your computer and use it in GitHub Desktop.
Save andymotta/5484f1d2a8f6d8eb3b18f5d415ef3de5 to your computer and use it in GitHub Desktop.
Use Terraform latest docker image in Declarative Jenkins Pipeline
pipeline {
agent {
docker {
image 'hashicorp/terraform:latest'
label 'LINUX-SLAVE'
args '--entrypoint="" -u root -v /opt/jenkins/.aws:/root/.aws'
}
}
options {
ansiColor('xterm')
}
parameters {
choice(
choices: ['preview' , 'apply' , 'show', 'preview-destroy' , 'destroy'],
description: 'Terraform action to apply',
name: 'action')
string(defaultValue: "default", description: 'Which AWS Account (Boto profile) do you want to target?', name: 'AWS_PROFILE')
}
stages {
stage('init') {
steps {
sh 'terraform version'
sh 'terraform init -backend-config="bucket=${ACCOUNT}-tfstate" -backend-config="key=${TF_VAR_stack_name}/terraform.tfstate" -backend-config="region=us-west-2"'
}
}
stage('validate') {
when {
expression { params.action == 'preview' || params.action == 'apply' || params.action == 'destroy' }
}
steps {
sh 'terraform validate -var aws_profile=${AWS_PROFILE}'
}
}
stage('preview') {
when {
expression { params.action == 'preview' }
}
steps {
sh 'terraform plan -var aws_profile=${AWS_PROFILE}'
}
}
stage('apply') {
when {
expression { params.action == 'apply' }
}
steps {
sh 'terraform plan -out=plan -var aws_profile=${AWS_PROFILE}'
sh 'terraform apply -auto-approve plan'
}
}
stage('show') {
when {
expression { params.action == 'show' }
}
steps {
sh 'terraform show'
}
}
stage('preview-destroy') {
when {
expression { params.action == 'preview-destroy' }
}
steps {
sh 'terraform plan -destroy -var aws_profile=${AWS_PROFILE}'
}
}
stage('destroy') {
when {
expression { params.action == 'destroy' }
}
steps {
sh 'terraform destroy -force -var aws_profile=${AWS_PROFILE}'
}
}
}
}
@ebwang
Copy link

ebwang commented Feb 17, 2020

Very Nice, tks a lote

@Blazar1000
Copy link

Hi,
from where does the pipeline get the terraform code ?

@samrakshak
Copy link

Hi,
from where does the pipeline get the terraform code ?

Did you figure it out?

@alanreynosov
Copy link

Hi, from where does the pipeline get the terraform code ?

When you create Jenkins Job, should be explicitly defined in the the pipeline definition

image

@gelfandbein
Copy link

If you got 'typical symptom is the Git executable not being run inside a designated container' - put path to git executable in Global Tools

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment