Search code examples
jenkinsgroovyterraformjenkins-pipeline

Running Terraform from Jenkins Groovy pipeline


I have this simple groovy pipeline:

pipeline {
    agent any
    stages {
        stage("Checkout") {
            ...
        }
        stage("Terraform init") {
            steps {
                sh 'terraform init'
            }
        }
        ...
    }
}

When I run it I get this in the output console:

...
[Pipeline] { (Terraform init)
[Pipeline] sh
+ terraform init
/var/jenkins_home/workspace/groovy-hello-world@tmp/durable-26b77be9/script.sh: 1: terraform: not found
[Pipeline] }
[Pipeline] // stage
...

I believe I have configured terraform correctly in Jenkins:

But when I exec on my jenkins server (a Pod running K8) I see this:

jenkins@jenkins-5498fbb866-7sgp4:/$ apt list --installed  | grep terra

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

jenkins@jenkins-5498fbb866-7sgp4:/$

So I don't think terraform got installed. Is there something else I need to do?


Solution

  • I'll put the solution I came up with in case I run into this problem again.

    enter image description here

    Also I needed to add a little bit of Groovy code.

    pipeline {
        agent any
        environment {
            TERRAFORM_HOME = tool name: 'terraform', type: 'org.jenkinsci.plugins.terraform.TerraformInstallation'
            PATH = "${TERRAFORM_HOME}:${env.PATH}"
        ...