Issue
I'm running a Jenkins pipeline job using Jenkinsfile
. The primary purpose is to run terraform <plan|apply>
, based on the choice parameter to select either plan
or apply
, like this:
stages {
stage('tf_run') {
steps {
sh '''#!/usr/bin/env bash
terragrunt ${Action} --terragrunt-source "/var/temp/tf_modules//${tfm}"
'''
}
}
}
Where Action
is the choice-parameter variable, it's all good for the plan but failing for apply as it asks for the confirmation whether to proceed or not, and the job is falling instantly. What can I do here so that users get to type yes
/no
(or select from the list), which then can be passed on to the terraform apply
?
I got stuck in the middle, and I'd appreciate it if anyone could put me in the right direction. I appreciate any help you can provide.
-S
Solution
To fit the use case, the Jenkins Pipeline will have three steps:
- Generate the plan file
- Query user input for plan approval
- Apply the plan file if approved
Assumption: you claim the pipeline is successful for plan
, which implies to me that Action
and tfm
are environment variables (i.e. env.Action
), because otherwise the String argument to the sh
step method is invalid. Given that assumption:
(answer now modified upon request to demonstrate tfm
as a pipeline parameter and no longer is in the env
object)
parameters {
string(name: 'tfm', description: 'Terraform module to act upon.')
}
stages {
stage('TF Plan') {
steps {
// execute plan and capture plan output
sh(
label: 'Terraform Plan',
script: "terragrunt plan -out=plan.tfplan -no-color --terragrunt-source '/var/temp/tf_modules//${params.tfm}'"
)
}
}
stage('TF Apply') {
// only execute stage if apply is desired
when { expression { return env.Action == 'apply' } }
steps {
// query for user approval of plan
input(message: 'Click "proceed" to approve the above Terraform Plan')
// apply the plan if approved
sh(
label: 'Terraform Apply',
script: 'terraform apply -auto-approve -input=false -no-color plan.tfplan'
)
}
}
}
You may also want to add the equivalent of env.TF_IN_AUTOMATION = true
to the environment
directive. This can be helpful when executing Terraform in a pipeline.
If you also modify the pipeline agent
to be e.g. the Terraform CLI image running as a container, then the plan output file will also need to be preserved between stages.
Answered By - Matt Schuchard
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)