You need to enable JavaScript to run this app. 如何将Jenkins全局凭据传入Jenkinsfile调用的Python脚本
优惠活动
大模型
产品
解决方案
定价
更多

如何将Jenkins全局凭据传入Jenkinsfile调用的Python脚本

解决方案

你可以直接通过环境变量传递凭据,不需要用到argparse,操作非常简单,只需要修改两处代码即可:

第一步:修正Jenkinsfile配置

你现在的withCredentials块没有把执行Python脚本的命令包裹进去,会导致变量无法传递,同时虚拟环境的激活逻辑也需要调整,否则后续命令不会使用你创建的虚拟环境。修改后完整配置如下:

pipeline {
    options { 
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '30', artifactNumToKeepStr: '30')) 
    }
    agent { label 'ops_slave' }
    stages {
        stage('Environment Build') {
            steps {
                echo "Hello World!"
                sh "echo Hello from the shell"
                sh "hostname"
                sh "uptime"
                sh "python3 -m venv test_env"
                // 把虚拟环境激活、依赖安装、脚本执行都放到同一个sh块,且放在withCredentials内部
                withCredentials([[
                    $class: 'UsernamePasswordMultiBinding',
                    credentialsId: 98,
                    usernameVariable: 'user',
                    passwordVariable: 'pw',
                ]]){
                    sh """
                        source ./test_env/bin/activate
                        pip3 install pandas psycopg2
                        echo the script is working
                        python3 bartek-jenkins-testing/python/test.py
                    """
                }
            }
        }
    }
}

说明:withCredentials块内定义的user和pw变量,会自动作为环境变量传递给块内执行的shell命令,Python可以直接读取这些环境变量。

第二步:修改Python脚本读取环境变量

只需要导入os模块,读取对应环境变量即可,修改后完整代码如下:

print('Hello World this is python')
import os
import pandas as pd
print(pd.__version__)
import pyodbc
import psycopg2

# 读取Jenkins传递的环境变量
db_user = os.environ.get('user')
db_pw = os.environ.get('pw')

connection = psycopg2.connect(
    host="saturn-dv",
    database="saturn_dv",
    port='8080',
    user=db_user,
    password=db_pw
)
connection.set_session(readonly=True)
query = """
SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_schema,table_name;"""
data = pd.read_sql(query, connection)
print(data)

注意事项

  • 不要在脚本中打印db_user和db_pw的值,Jenkins会自动屏蔽日志中这两个变量的内容,但主动打印仍有泄露风险
  • 确保你的Jenkins agent节点的Python环境可以正常读取shell传递的环境变量,默认配置下都支持该操作

内容的提问来源于stack exchange,提问作者Bartek Malysz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 00:24:01