如何在Jenkins Matrix插件中获取Lockable Resources的设备端口参数
规范实现Jenkins Matrix多设备并行测试的端口映射
方案1:利用Lockable Resources的资源属性(推荐)
Lockable Resources插件支持给每个资源添加自定义属性,刚好可以用来绑定设备和端口:
- 进入Jenkins全局配置 → Lockable Resources Management,给每个设备资源(比如
device1、device2)添加属性:- 键:
port,值分别填/dev/ttyUSB1、/dev/ttyUSB2
- 键:
- 流水线中锁定资源后,直接通过
resource.attributes获取对应端口:
matrix { axes { axis { name 'DEVICE' values 'device1', 'device2' } } stages { stage('Run Test') { steps { lock(resource: DEVICE) { def targetPort = resource.attributes.port echo "Testing on ${DEVICE}, port: ${targetPort}" // 执行你的测试命令,比如 `automation-test --port ${targetPort}` } } } } }
方案2:用映射表统一管理设备-端口对应关系
如果不想修改全局配置,直接在流水线里定义一个Map存储对应关系,扩展性更强:
// 提前定义设备与端口的映射,新增设备直接加一行即可 def devicePortMap = [ "device1": "/dev/ttyUSB1", "device2": "/dev/ttyUSB2" ] pipeline { agent none stages { stage('Parallel Device Tests') { matrix { axes { axis { name 'DEVICE' values devicePortMap.keySet().toList() } } agent { label 'your-shared-agent' } stages { stage('Execute Test') { steps { lock(resource: DEVICE) { def targetPort = devicePortMap[DEVICE] echo "Running test on ${DEVICE} (port: ${targetPort})" // 测试执行逻辑 } } } } } } } }
方案3:Declarative Pipeline中用环境变量动态赋值
如果使用纯Declarative语法,可在环境块里通过脚本逻辑动态生成端口:
pipeline { agent none stages { stage('Matrix Test') { matrix { axes { axis { name 'DEVICE' values 'device1', 'device2' } } agent { label 'your-agent' } environment { PORT = script { def map = [device1: "/dev/ttyUSB1", device2: "/dev/ttyUSB2"] return map[DEVICE] } } stages { stage('Lock & Test') { steps { lock(resource: DEVICE) { echo "Device: ${DEVICE}, Port: ${PORT}" // 测试命令 } } } } } } } }
这些方案都比临时的if判断更易维护:新增设备时,要么在全局资源属性里加一条,要么在Map里加一行,无需修改大量分支判断逻辑。
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

