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
CodePudding user response:
You can use terraform apply -auto-approve
within your Jenkins Job.
Tip: You can add condition in Jenkins stage() when a user choose parameter plan than there will be no -auto-approve option added automatically, else the command will append -auto-approve option.
stage(plan&apply){
if ${USER_INPUT} == "plan"{
terraform plan
}
else{
terraform apply -auto-approve
}
}
Note: Above Jenkins code might not match to proper Ans but can be taken as example.
CodePudding user response:
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:
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//${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 Plan',
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.