在Groovy中解析terraform输出

wz8daaqr  于 8个月前  发布在  其他
关注(0)|答案(2)|浏览(83)

Jenkins文件:

pipeline {
    agent any
    parameters {
        string(name: 'vmNames', defaultValue: 'host-01,host-02,host-03', description: 'Enter VM names (comma-separated)')
        string(name: 'xoaUrl', defaultValue: 'wss://xo.example.com', description: 'Enter XOA URL' )
        string(name: 'xoaUser', defaultValue: 'red.crick', description: 'Enter XOA User' )
    }

    environment {
        TERRAFORM_HOME = tool name: 'terraform', type: 'org.jenkinsci.plugins.terraform.TerraformInstallation'
        PATH = "${TERRAFORM_HOME}:${env.PATH}"
        XOA_URL = "${xoaUrl}"
        XOA_USER = "${xoaUser}"
        XOA_PASSWORD = "${xoaPassword}"
    }

    stages {
        stage("Terraform init") {        
        ...
        }

        stage("Terraform plan") {
        ...
        }

        stage("Terraform apply") {
            steps {
                dir('dev/xo/clusters/sandbox') {
                    withCredentials([string(credentialsId: 'XOA_PASSWORD', variable: 'xoaPassword')]) {
                        sh '''
                        export XOA_PASSWORD="${xoaPassword}"
                        terraform apply -parallelism=1 -no-color "theplan"
                        '''
                        script {
                            def output = sh(script: 'terraform output -json', returnStdout: true).trim()
                            echo "output is $output"

                            def ipAddresses = readJSON(text: output).ip_addresses.value
                            echo "ipAddresses is $ipAddresses"
                            echo "ipAddresses[0] is $ipAddresses[0]"

                            currentBuild.description = jsonArray.collect { JSONArray.fromObject(ipAddresses) }
                        }
                    }
                }
            }
        }

        stage("Set Hostname and Reboot to Get DNS Records Created.") {
            steps {
                script {
                    def ipAddresses = currentBuild.description
                    def hostnames = vmNames.split(',')

                    withCredentials([sshUserPrivateKey(credentialsId: 'bpadmin-private-ssh-key', keyFileVariable: 'SSH_PRIVATE_KEY', usernameVariable: 'USER')]) {
                        for (int i = 0; i < ipAddresses.size(); i++) {
                            def ipAddress = ipAddresses[i].trim()
                            def hostname = hostnames[i].trim() // Access the correct hostname using the index

                            echo "Setting hostname $hostname for IP address $ipAddress"                    
                        }
                    }
                }
            }
        }
    }
}

问题是我不知道如何处理变量def ipAddresses = readJSON(text: output).ip_addresses.value。这是一个名单吗?它是一根绳子吗?我所希望的是输出看起来像这样:

Setting hostname host-01 for IP address 10.0.22.1
Setting hostname host-02 for IP address 10.0.22.6
Setting hostname host-03 for IP address 10.0.22.16
...

但我得到了这个错误:

ipAddresses is [[10.0.253.236], [10.0.253.234], [10.0.253.233], [10.0.253.231], [10.0.253.232], [10.0.253.235]]
[Pipeline] echo
ipAddresses[0] is [[10.0.253.236], [10.0.253.234], [10.0.253.233], [10.0.253.231], [10.0.253.232], [10.0.253.235]][0]
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // withCredentials
[Pipeline] }
[Pipeline] // dir
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Set Hostname and Reboot to Get DNS Records Created.)
Stage "Set Hostname and Reboot to Get DNS Records Created." skipped due to earlier failure(s)
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Also:   org.jenkinsci.plugins.workflow.actions.ErrorAction$ErrorId: 841a0fee-7b3b-404b-b647-717c38019255
groovy.lang.MissingPropertyException: No such property: jsonArray for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:285)
    at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:375)

我一整天都快疯了请帮忙:)

bis0qfac

bis0qfac1#

您的思路是正确的,ipAddresses变量看起来是JSONArray的一个示例,因此您可以添加

import net.sf.json.JSONArray

在管道的顶部修复错误消息。
但你不必这么做。JSONArray也是一个List,所以把它当作任何其他groovy列表。

currentBuild.description = ipAddresses.flatten().join(',')
ilmyapht

ilmyapht2#

ipAddresses是一个List<List<String>>,其中每个嵌套的List包含您试图访问的IP地址元素。我们可以将此列表展平,然后通过它来实现您的目标:

List ipAddresses = readJSON(text: output).ip_addresses.value
List hostnames = vmNames.split(',')

ipAddresses.flatten().eachWithIndex { ipAddress, i ->
  echo "Setting hostname ${hostname[i].trim()} for IP address ${ipAddress}"
}

请注意,上面的字符串插值语法更安全(因此,为什么你的$ipAddresses[0]产生了意想不到的结果,因为它应该是${ipAddresses[0]}),我也没有看到关于问题中vmNames定义的信息,所以我从答案中省略了它,并且需要假设它已经被正确处理了。但是,我建议将vmNames的定义和/或数据与ip地址相关联,以更安全地确保两者的准确性。

相关问题