问题:如何在 Jenkinsfile 中进行用户输入以进行 terraform 应用?

我正在使用Jenkinsfile运行 Jenkins 管道作业。主要目的是运行 terraform <plan|apply>,根据 choice 参数 选择planapply,如下所示:

stages {
  stage('tf_run') {
    steps { 
      sh '''#!/usr/bin/env bash
        terragrunt ${Action} --terragrunt-source "/var/temp/tf_modules//${tfm}"
      '''
    }
  }
}

其中Action是选择参数变量,这对 plan 来说都是好的,但对于 apply 来说却失败了,因为它要求确认是否继续,并且工作立即下降。我可以在这里做什么,以便用户输入yes/no(或从列表中选择),然后可以将其传递给terraform apply?

我被困在中间,如果有人能把我引向正确的方向,我将不胜感激。感谢您提供的任何帮助。

-S

解答

为了适应用例,Jenkins Pipeline 将包含三个步骤:

  • 生成计划文件

  • 查询用户输入进行审图

  • 如果批准,应用计划文件

假设:您声称plan的管道是成功的,这对我来说意味着Actiontfm是环境变量(即env.Action),因为否则sh步骤方法的 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 映像作为容器运行,那么计划输出文件也需要在阶段之间保留。

Logo

CI/CD社区为您提供最前沿的新闻资讯和知识内容

更多推荐