在 Jenkins CI CD 管道中循环并在同一作业中调用另一个 JenkinsFile

Looping in Jenkins CICD pipeline and call another JenkinsFiles in same job

我有 Jenkins CICD 管道,我需要读取一个配置文件,其中包含需要使用标签号构建的项目的键值对。

我需要通读这个文件并在循环中执行 Jenkins 管道步骤。

目前我的 Jenkins CICD 管道适用于单一构建。我在尝试读取配置文件并循环执行这些步骤时遇到问题。

下面是我要实现的代码示例:

pipeline{
    agent any    
    environment {
        buildApp = "$ApplicationToBuild"
        cloudEnvironment = "$ENV"
        TIMESTAMP = new java.text.SimpleDateFormat('yyyyMMddHHmmss').format(new Date())
        WORKSPACE="${env.WORKSPACE}"
    }
    stages {
        stage ('Validation step for deployment') {      
            steps {
        script {
                    sh 'line_count=$( wc -l applicationSettings.config )'
                    echo 'line count is $line_count'
                    for (int lines = 0; lines < ${line_count}; lines++) {
                        gitAppRepo=""
                        gitAppTag=""
                        gitAppRepo=$(echo $lines |  sed 's/=.*//')
                        echo "gitAppRepo is $gitAppRepo"
                        gitAppTag=$(grep "^$gitAppRepo=" ./applicationSettings.config |cut -d= -f2)
                        echo "gitAppTag is $gitAppTag"                      
                    }
                    }
                }
            }
    }
    post {
        always {
            echo 'One way or another, I have finished'
            }
    }
}

我使用行数并循环遍历配置文件来部署应用程序和标记。实际部署将在另一个包含所有步骤的 jenkins 文件中调用。

在上述循环中遇到以下错误。在 groovy 中是否有任何有效的循环方法?

java.lang.NoSuchMethodError: No such DSL method '$' found among steps

以及我们如何在同一个项目中调用另一个 JenkinsFile。下面是我的文件结构。我需要在 Jenkins_files.

中调用 Jenkins_files_main
Jenkins_files
README.md
applicationSettings.config
Jenkins_files_main

首先,您使用了 ${line_count},只有当您是 运行 一个 shell 脚本时才有效(因为它会查找环境变量)。除此之外,您可以将其用作 "${line_count}" 或简称 line_count。然后为此,您应该已经在变量中读取了命令的输出,例如:

def line_count= sh(script: "wc -l applicationSettings.config",
                   returnStdout: true).trim()

因此您的 for 循环将变为:

for (int lines = 0; lines < line_count; lines++)

那么,还有一个更好的读取json文件的方法,像这样:

    def object = readJSON file: "your.json"


            for (key in object.element.keySet()) {
               echo "key=${key}"
               echo "value= ${object.element.get(key)}"
}

希望对您有所帮助。