如何使用键作为变量从映射中获取值?

时间:2019-05-15 12:26:27

标签: groovy continuous-integration jenkins-pipeline

我有一个包含以下内容的Jenkins管道:

parameters.groovy

    static Map<String, String> doMapping() {
        [
                'a-b-c': '1-2-3',
                'd-e-f': '4-5-6',
                'g-h-i': '7-8-9'
        ]
    }
    return this

Jenkinsfile

    Map<String, String> myMap = null
    ...
    pipeline {
      parameters {
        string(name: 'param1')
      }
      stages {
        stage('Stage 1', {
          ...
          steps {
            script {
              myMap = load('parameters.groovy').doMapping()
            }
          }
        }
        stage('Stage 2', {
          ...
          steps {
            script {
              String p = ""
              String v = ""
              if (params.PARAM1?.trim()) {
                p = params.PARAM1
                v = myMap.get(p)
                if (v == null) { // Set v to p if not found in the map
                  v = p
                }
                echo "v = ${v}"
                v = myMap.get('d-e-f')
                if (v == null) {
                  v = p
                }
                echo "v = ${v}"
              }
            }
          }
        }
      }
    }

输入:

param1 = d-e-f

输出:

[Pipeline] echo
v = d-e-f
[Pipeline] echo
v = 4-5-6

为什么当变量用作键时却找不到映射条目,而硬编码时又找到映射条目?

我试图检查是否有空格,但是没有,我检查了映射键的类型p,params.PARAM1和v,它们是java.lang.String。

0 个答案:

没有答案