我正在使用 .js 運行 Jenkins 管道作業Jenkinsfile。主要目的是運行 terraform <plan|apply>,根據選擇引數選擇plan或apply,如下所示:
stages {
stage('tf_run') {
steps {
sh '''#!/usr/bin/env bash
terragrunt ${Action} --terragrunt-source "/var/temp/tf_modules//${tfm}"
'''
}
}
}
Action選擇引數變數在哪里,對計劃都很好,但申請失敗,因為它要求確認是否繼續進行,并且作業立即下降。我可以在這里做什么以便用戶輸入yes/ no(或從串列中選擇),然后可以將其傳遞給terraform apply?
我被卡在了中間,如果有人能讓我朝著正確的方向前進,我將不勝感激。感謝您提供的任何幫助。
-S
uj5u.com熱心網友回復:
為了適應用例,Jenkins Pipeline 將分為三個步驟:
- 生成計劃檔案
- 查詢用戶輸入以進行計劃批準
- 如果批準,則應用計劃檔案
假設:您聲稱管道成功用于plan,這對我來說意味著Action并且tfm是環境變數(即env.Action),因為否則shstep 方法的 String 引數無效。鑒于該假設:
(現在根據要求修改答案以演示tfm為管道引數并且不再在env物件中)
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'
)
}
}
}
您可能還需要相當于添加env.TF_IN_AUTOMATION = true到environment指令。在管道中執行 Terraform 時,這會很有幫助。
如果您還將管道修改agent為例如作為容器運行的 Terraform CLI 映像,則還需要在階段之間保留計劃輸出檔案。
uj5u.com熱心網友回復:
您可以terraform apply -auto-approve在 Jenkins 作業中使用。
查看檔案
提示:您可以在 Jenkins stage() 中添加條件,當用戶選擇引數計劃時,不會自動添加 -auto-approve 選項,否則該命令將附加 -auto-approve 選項。
stage(plan&apply){
if ${USER_INPUT} == "plan"{
terraform plan
}
else{
terraform apply -auto-approve
}
}
注意:上面的 Jenkins 代碼可能與正確的 Ans 不匹配,但可以作為示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/399844.html
