Skip to content

Instantly share code, notes, and snippets.

@chrisj-au
Forked from gazoakley/Jenkinsfile
Last active December 23, 2020 06:28
Show Gist options
  • Save chrisj-au/2f7799c5ca7f3c17f61f854744e0afaa to your computer and use it in GitHub Desktop.
Save chrisj-au/2f7799c5ca7f3c17f61f854744e0afaa to your computer and use it in GitHub Desktop.
Jenkinsfile for running Terraform
pipeline {
agent any
parameters {
string(name: 'environment', defaultValue: 'default', description: 'Workspace/environment file to use for deployment')
string(name: 'version', defaultValue: '', description: 'Version variable to pass to Terraform')
booleanParam(name: 'autoApprove', defaultValue: false, description: 'Automatically run apply after generating plan?')
}
environment {
AWS_ACCESS_KEY_ID = credentials('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = credentials('AWS_SECRET_ACCESS_KEY')
TF_IN_AUTOMATION = '1'
}
stages {
stage('Validate') {
sh 'terraform fmt --check'
sh 'terraform init -input=false'
}
post {
failure {
// Notify - email, web hook etc
}
}
stage('Plan') {
steps {
script {
currentBuild.displayName = params.version
}
sh 'terraform workspace select ${environment}'
sh "terraform plan -input=false -out tfplan -var 'version=${params.version}' --var-file=environments/${params.environment}.tfvars"
sh 'terraform show -no-color tfplan > tfplan.txt'
}
}
stage('Approval') {
when {
not {
equals expected: true, actual: params.autoApprove
}
}
steps {
script {
def plan = readFile 'tfplan.txt'
input message: "Do you want to apply the plan?",
parameters: [text(name: 'Plan', description: 'Please review the plan', defaultValue: plan)]
}
}
}
stage('Apply') {
steps {
sh "terraform apply -input=false tfplan"
}
}
}
post {
always {
archiveArtifacts artifacts: 'tfplan.txt'
}
}
}
@chrisj-au
Copy link
Author

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