在sh脚本中使用环境变量

时间:2020-09-16 02:49:30

标签: jenkins jenkins-pipeline terraform jenkins-groovy

我正在尝试在env脚本中访问sh,但是无法访问它们。我想将env的值附加到sh脚本。因为我想运行一个特定的Terraform模块,所以我想将该值附加在terraform apply和terraform输出前面

pipeline {
    agent any
    parameters {
        choice(
                choices: 'first\nsecond\n',
                description: 'number',
                name: 'name'
        )
    }
    stages {
        stage("set env variable"){
            steps{
                script{
                    if ( params.name== 'first'){
                        env.output = "first_dns"
                        env.module = "module.first"
                    }
                    else if (params.name == 'second'){
                        env.output = "second_dns"
                        env.module = "module.second"
                    }
                }
            }
        }
        stage('Deployment') {
            steps {
                script {
                  sh '''#!/bin/bash
                    terraform apply -target=${env.module} -auto-approve
                    terraform output {env.output}
                    '''
                    }
                }
            }      
        }
    }
}

1 个答案:

答案 0 :(得分:1)

问题在于Jenkins正在注入环境变量,但是您需要像在普通Shell脚本中那样访问它们。 由于使用单引号,因此变量将在Shell脚本的运行时进行评估,因此无法找到这些变量。 这应该起作用:

stage('Deployment') {
  steps {
     script {
       sh '''#!/bin/bash
       echo ${module}
       echo ${output}
       '''
     }
  }
}  

或者,如果使用双引号,则您编写的内容也将起作用。 这样,詹金斯将在执行之前替换这些值。

stage('Deployment') {
  steps {
     script {
       sh """#!/bin/bash
       echo ${env.module}
       echo ${env.output}
       """
     }
  }
}