Jenkins流水线脚本引用密钥的方式

使用Jenkins搭建自定义的流水线任务,通常是编写groovy脚本来实现,可以在脚本中调用现有的job,也可以直接在脚本中写shell命令,发送http请求或者执行某个应用程序的操作。

但是部分场景需要用到一些密钥信息来访问应用程序,否在无法被授权。此时在groove脚本中如何引用Jenkins配置的密钥显得尤为重要。

假设Jenkins已经配置好了全局密钥,密钥id为sonar-token,这里提供两种引用Jenkins密钥的方式,一种是通过 withCredentials 绑定变量,另一种是通过 credentials 结合 environment 创建环境变量:

pipeline {
    
    
  agent any
  stages {
    
    
    stage('Print Secret') {
    
    
        steps {
    
    
            withCredentials([string(credentialsId: 'sonar-token', variable: 'token')]) {
    
    
                echo "secret is ${token}"
            }
        }
    }
  }
}
pipeline {
    
    
  agent any
  environment {
    
    
    TOKEN = credentials('sonar-token')
  }
  stages {
    
    
    stage('Print Secret') {
    
    
      steps {
    
    
          echo "secret is ${TOKEN}"
      }
    }
  }
}

猜你喜欢

转载自blog.csdn.net/mryang125/article/details/121803498
今日推荐