I am running terraform from a jenkins pipeline with parameter “apply” and “destroy”, but If I run the job for the first time for apply, it works but if I run the job 2nd time for destroy, it gives me the below error
No changes.e[0me[1m No objects need to be destroyed.e[0m
e[0mEither you have not created any objects yet or the existing objects were
already deleted outside of Terraform.
e[0me[1me[32m
Destroy complete! Resources: 0 destroyed."
Below is my jenkins script
pipeline {
agent any
parameters {
choice(name: ‘action’, choices: [‘apply’, ‘destroy’], description: ‘Select the action to perform’)
}
environment {
AZURE_SUBSCRIPTION_ID = credentials(‘azure_subscription_id’)
AZURE_CREDENTIAL_ID = credentials(‘azure_credential_id’)
AZURE_CLIENT_SECRET_KEY = credentials(‘azure_client_secret_key’)
AZURE_TENANT_ID = credentials(‘azure_tenant_id’)
}
stages {
stage(‘Checkout’) {
steps {
sh ‘echo “Preparation and checkout”’
checkout ([$class: ‘GitSCM’,branches: [[name: ‘*/s3_tf’]],
extensions: [],
userRemoteConfigs: [[credentialsId: ‘gitlab-credential’,url: “${GITREPO_URL}”]]])
}
}
stage(‘Install Dep’) {
agent any
steps {
script{
sh “cd /tmp”
sh “curl -o terraform.zip https://releases.hashicorp.com/terraform/1.7.4/terraform_1.7.4_linux_amd64.zip”
sh “unzip terraform.zip”
sh “mv terraform /usr/bin”
sh “rm -rf terraform.zip”
}
}
}
stage(‘Terraform apply’){
when{
expression{
return params.action == ‘apply’
}
}
steps{
sh ‘terraform init’
sh ‘az login --service-principal -u $AZURE_CREDENTIAL_ID -p $AZURE_CLIENT_SECRET_KEY --tenant $AZURE_TENANT_ID’
sh ‘terraform plan --out=tfplan’
sh ‘terraform apply --auto-approve’
}
}
}
}`