Jenkins管道 - 在nodejs构建中访问环境变量

时间:2018-04-11 14:22:40

标签: node.js jenkins environment-variables jenkins-pipeline

我的Jenkins管道需要一些帮助。 我想要做的是按特定顺序触发一些构建以登录平台,部署应用程序并再次注销 构建实现为nodejs脚本,并使用环境变量存储数据并访问先前构建的数据 我的问题是,当我尝试从我的nodejs脚本中访问环境变量时,我总是收到未定义的。例如:在'LoginToPlatform'构建中,我使用process.env.username来接收用户名,但即使我在管道的环境块中设置环境变量,我也会收到未定义的。

所以我的问题是如何从我的构建(nodejs脚本)中访问环境变量?

以下是构建顺序:

1. 'LoginToPlatform'
Uses process.env.username and process.env.password
Sets process.env.session

2. 'DeployOnPlatform'
Uses process.env.session

3. 'LogoutFromPlatform'
Uses process.env.session

我的Jenkins管道:

pipeline {
agent any

environment {
    username = 'abc'
    password = 'asdf'
}
stages {
    stage ('Login') {
        steps {
            echo 'Login.'
            build job: 'LoginToPlatform'
        }
    }
    stage ('Deployment') {
        steps {
            echo 'Deployment.'
            build job: 'DeployOnPlatform'
        }
    }
    stage ('Logout') {
        steps {
            echo 'Logout.'
            build job: 'LogoutFromPlatform'
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

以下是访问env变量的方法之一。

Jenkinsfile

pipeline {
    agent {
        docker {
            image 'node:6-alpine' 
        }
    }

    environment {
        VARIABLE_1="10"
        VARIABLE_2="7"
    }

    stages {
        stage('Build') { 
            steps {
                sh 'node main.js' 
            }
        }
    }
}

main.js

const envOne = process.env.VARIABLE_1;
const envTwo = process.env.VARIABLE_2;

console.log("envOne: " + envOne);
console.log("envTwo: " + envTwo);

输出:

Jenkins seems to be running inside container 646633d29eac6e0e5b56e4aef28055075b5a2274e26b159387a7a34f35919fe3
$ docker run -t -d -u 0:0 -p 3000:3000 -w /var/jenkins_home/workspace/fff_master-RUQD36MGKNUXMF26H5CQBCDE6AKFWFLUOG7MTQ6WMTXNXKQHCNMA --volumes-from 646633d29eac6e0e5b56e4aef28055075b5a2274e26b159387a7a34f35919fe3 -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** -e ******** node:6-alpine cat
$ docker top 3fe3059a78e890dc2cadd722c25b97d5a023da059cc807cef3acb29237f0261f -eo pid,comm
[Pipeline] {
[Pipeline] withEnv
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] sh
[fff_master-RUQD36MGKNUXMF26H5CQBCDE6AKFWFLUOG7MTQ6WMTXNXKQHCNMA] Running shell script
+ node main.js
envOne: 10
envTwo: 7
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
$ docker stop --time=1 3fe3059a78e890dc2cadd722c25b97d5a023da059cc807cef3acb29237f0261f
$ docker rm -f 3fe3059a78e890dc2cadd722c25b97d5a023da059cc807cef3acb29237f0261f
[Pipeline] // withDockerContainer
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline