'Jenkinsfile is failing with error @tmp/durable-df843027/script.sh: line 1: terraform: command not found

I'm trying to run a terraform commands from Jenkinsfile stage. The code I'm using is as below:

node {

    checkout(scm)       
        stage ('Templates Deployment'){
            sh "terraform init"
        }
}

This fails with the error as :

+terraform init
/var/lib/jenkins/workspace/Terraform-Code/@tmp/durable-df843027/script.sh: line 1: terraform: command not found

Terraform is installed on the Jenkins server. When I execute the terraform init command from the server(CLI), it works fine. But while running it from the Jenkinsfile(console) it's throwing this error.

Can someone please suggest how this error can be resolved? Any help to execute terraform commands via Jenkinsfile is highly appreciated.



Solution 1:[1]

Configure Terraform

Go to Manage Jenkins > Global Tool Configuration > It will display Terraform on the list.

enter image description here

Solution 2:[2]

give full path of terraform binary or set PATH before terraform init

`node {

checkout(scm)       
    stage ('Templates Deployment'){
        sh """
          PATH=/bin/terraform
          terraform init"
    }

}`

Solution 3:[3]

You can set the PATH inside the environment block:

pipeline {
    agent any
    environment {
        PATH = "/usr/local/bin/:$PATH"
    }
    stages{
        stage("first stage"){
            steps{
                sh "cd /Users/<user>/Terraform/proj1"
                sh "pwd"
                sh "terraform"
            }  
        }
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Thanh Nguyen Van
Solution 2 naresh bandari
Solution 3 Noam Helmer