Skip to content

Instantly share code, notes, and snippets.

@mbaitelman
Created November 2, 2020 02:47
Show Gist options
  • Select an option

  • Save mbaitelman/a7f1ab858e75b7035555564b62ccd3e0 to your computer and use it in GitHub Desktop.

Select an option

Save mbaitelman/a7f1ab858e75b7035555564b62ccd3e0 to your computer and use it in GitHub Desktop.

Revisions

  1. mbaitelman created this gist Nov 2, 2020.
    96 changes: 96 additions & 0 deletions jenkinsfile
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,96 @@
    pipeline {
    agent {
    docker {
    image 'hashicorp/terraform:0.12.29'
    args '--entrypoint=""'
    }
    }
    parameters {
    choice choices: ['us-west-2', 'us-east-2'], description: '', name: 'region'
    choice choices: ['Plan', 'Apply', 'Destroy'], description: '', name: 'action'
    string defaultValue: '', description: '', name: 'target', trim: true
    }

    triggers {
    pollSCM 'H/5 * * * *'
    }

    options {
    timeout(15)
    timestamps()
    ansiColor('xterm')
    disableConcurrentBuilds()
    lock('terraform')
    }

    stages {
    stage('Init') {
    steps {
    script {
    def changesExist = -1
    def target = "${params.target}"
    env.targetString = ""
    if (target != '') {
    target.split(",").each { moduleName ->
    env.targetString += "-target ${moduleName} "
    }
    }
    }
    sh 'terraform version'
    withAWS(credentials: 'aws-credentials', region: 'us-west-2') {
    sh 'terraform init'
    }
    }
    }
    stage('Validate') {
    steps {
    withAWS(region: 'us-west-2') {
    sh 'terraform validate'
    }
    }
    }
    stage('Format') {
    steps {
    sh 'terraform fmt --recursive'
    }
    }
    stage('Plan') {
    steps {
    withAWS(credentials: 'aws-credentials', region: 'us-west-2') {
    script{
    changesExist = sh label: 'terraform plan', returnStatus: true, script: "terraform plan ${env.targetString ?: ''} -detailed-exitcode" // 0 is no changes, 1 is error, 2 is changes to apply
    if(changesExist == 1){
    error('Error in terraform plan')
    }
    }
    }
    }
    }
    stage('Apply') {
    steps {
    withAWS(credentials: 'aws-credentials', region: 'us-west-2') {
    script {
    if(params.action == 'Destroy'){
    sh "terraform destroy -input=false -auto-approve -force -parallelism 10 ${env.targetString ?: ''}"
    } else {
    sh "terraform apply -input=false -auto-approve -parallelism 10 ${env.targetString ?: ''}"
    }
    }
    }
    }
    when {
    allOf{
    expression { env.BRANCH_NAME == "master"}
    expression { return (changesExist == 2) }
    expression { return (action == 'Apply') }
    }
    }
    }
    }

    post {
    always {
    cleanWs()
    }
    }
    }