Jenkins 凭据使用

时间:2022-07-22
本文章向大家介绍Jenkins 凭据使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

原文链接:https://blog.spiritling.cn/posts/6b626a8a/

环境变量

jenkinsfile 使用环境变量

代码:

pipeline {
  agent {
    docker {
      image 'spiritling/node:10.15.3'
    }

  }
  stages {
    stage('get') {
      environment {
        VERSION = sh(script: 'node script/auto-versioning.js', , returnStdout: true)
      }
      steps {
        sh 'echo "VERSION: "$VERSION'
    }
  }
}

将 auto-versioning.js 执行后返回的文本或数字存入到 VERSION 环境变量中去

steps 中使用 $VERSION 来获取环境变量

凭据

账号密码凭据管理

创建凭据,以下为例子:

类型:Username with password 范围:全局 用户名:root 密码:rootxxxx ID:BIRRARY_ID 描述:随意填写

在 jenkinsfile 中使用

pipeline {
  agent {
    docker {
      image 'spiritling/node:10.15.3'
    }

  }
  stages {
    stage('get') {
      steps {
        withCredentials([usernamePassword(credentialsId: 'BIRRARY_ID', passwordVariable: 'password', usernameVariable: 'username')]) {
          sh 'git remote set-url origin https://${username}:${password}@github.com/spiritling/blog.git'
        }
        sh 'echo "获取凭据"'
    }
  }
}

可以在 jenkinsfile 文件的构建过程中获取到 username 和 password 的凭据,并且可以在后续将其插入进去

加密文本凭据管理

创建凭据,以下为例子:

类型:Secret text 范围:全局 Secret:rootxxxx ID:BIRRARY_ID 描述:随意填写

在 jenkinsfile 中使用

pipeline {
  agent {
    docker {
      image 'spiritling/node:10.15.3'
    }

  }
  stages {
    stage('get') {
      steps {
        withCredentials([string(credentialsId: 'ID:BIRRARY_ID', variable: 'secret')]) { //set SECRET with the credential content
          sh 'echo -e "registry=https://npmjs.org/spiritling/n_auth = ${secret}nemail = spirit_ling_cn@163.comnalways-auth = truen$PATH" > .npmrc'
        }
        sh 'echo "获取凭据"'
    }
  }
}

可以在 jenkinsfile 文件的构建过程中获取到 secret 的凭据,并且可以在后续将其插入进去