Skip to content

Instantly share code, notes, and snippets.

@gazoakley
Last active April 16, 2024 12:00
Show Gist options
  • Save gazoakley/87dcc16d28fd05acda4ba0a4be5ac387 to your computer and use it in GitHub Desktop.
Save gazoakley/87dcc16d28fd05acda4ba0a4be5ac387 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('Plan') {
steps {
script {
currentBuild.displayName = params.version
}
sh 'terraform init -input=false'
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'
}
}
}
@mickleissa
Copy link

Hello,
I have an issue to automate TF in Jenkinsfile to Apply terraform.tfstae from the backend S3. how I can write the correct command?
////////////////////////////////////////////////////////////////////////////////////

pipeline {
// Jenkins AWS Access & Secret key
environment {
AWS_ACCESS_KEY_ID = credentials('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = credentials('AWS_SECRET_ACCESS_KEY')
}

options {
// Only keep the 5 most recent builds
buildDiscarder(logRotator(numToKeepStr:'5'))
}

agent any
tools {
terraform 'terraform'
}

stages {
   // Check out from GIT, Snippet Generato from pipeline Syntax --> Checkout: Check out from version control 
    stage ("Check from GIT") {
        steps {
           git branch: 'master', credentialsId: 'Jenkins_terraform_ssh_repo', url: 'git@github.com:mickleissa/kobai.git'
              }
       }
       // Terraform Init Stage
    stage ("Terraform init") {
        steps {
            // sh 'terraform -chdir="./v.14/test_env" init -upgrade'
             // terraform init -backend-config="bucket=kobai-s3-backend-terraform-state" -backend-config="key=stage-test-env/terraform.tfstate"
                 sh 'terraform -chdir="./v.14/test_env" init -migrate-state' 
              }
    }
    // Terraform fmt Stage
    stage ("Terraform fmt") {
        steps {
            sh 'terraform fmt'
        }
    }
    // Terraform Validate Stage
    stage ("Terraform validate") {
        steps {
            sh 'terraform validate'
        }
    }

    // Terraform Plan Stage
    stage ("Terraform plan") {
        steps {
              sh 'terraform -chdir="./v.14/test_env" plan -var-file="stage.tfvars"'
           // sh 'terraform -chdir="./v.14/test_env" plan'
            
        }
    }

    //  Terraform Apply Stage
    stage ("Terraform apply") {
        steps {
             sh 'terraform -chdir="./v.14/test_env" apply -var-file="stage.tfvars" --auto-approve'
            //   sh 'terraform -chdir="./v.14/test_env" apply --auto-approve'
           
        }
    }
   // Approvel stage 
   stage ("DEV approval Destroy") {
        steps {
           echo "Taking approval from DEV Manager for QA Deployment"
           timeout(time: 7, unit: 'DAYS') {
           input message: 'Do you want to Destroy the Infra', submitter: 'admin'
           }
        }
    }
   // Destroy stage
      stage ("Terraform Destroy") {
         steps {
            sh 'terraform -chdir="./v.14/test_env" destroy -var-file="stage.tfvars" --auto-approve'
            // sh 'terraform -chdir="./v.14/test_env" destroy --auto-approve'
        }
     }
}
post {
    always {
        echo 'This will always run'
    }
    success {
        echo 'This will run only if successful'
    }
    failure {
        echo 'This will run only if failed'
    }
    unstable {
        echo 'This will run only if the run was marked as unstable'
    }
    changed {
        echo 'This will run only if the state of the Pipeline has changed'
        echo 'For example, if the Pipeline was previously failing but is now successful'
    }
      }

}

@himavanthkj
Copy link

Thanks @gazoakley it's very helpful..I have a doubt if we can add a stage in pipeline to import existing resources into terraform code..I mean is there any chance if we can have a stage where we can import resources in Jenkins pipeline.

@amit4257
Copy link

Hey, where can I find variables.tf file and other dependencies? Please share them it will be a great help.

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