ZakG
ZakG

Reputation: 53

Jenkins pipeline, parse csv

I've been trying to do a simple parse CSV in a Jenkins pipeline.

My CSV is a simple one consisting of a machine name, its IP address, its subnet mask, its default gateway and its primary DNS server address

so

SystemName,IPAddress,Subnet,DefGate,DNS
server1,10.10.10.10,255.255.255.0,10.10.10.1,10.10.10.1
server2,10.10.10.11,255.255.255.0,10.10.10.1,10.10.10.1

etc.

My script is just this ( basically want to prove I can read the csv split it by line then split each line on the , and echo the individual values out on a line by line basis) :

   stage('Parse the CSV') {
        steps {
            script {
                dir ('FolderWhereCSVIsClonedFromGit') {
                    if (fileExists('MyCSV.csv')) {
                        echo ' MyCSV.csv found'

                        readFile("MyCSV.csv").eachLine { line, count ->
                            def fields = line.split(',')
                            for(String item: fields) {
                                println item
                                println ' you are parsing line : ' + count
                                }
                                nodes["line${count}"] = {
                                    node {
                                        echo fields[0] + ': ' + fields[1] + ': ' + fields[2] + ': ' + fields[3] + ': ' + fields[4];
                                    }
                                }
                    }
                    } else {
                        echo ' Machines.csv Not found. Failing.'
                    }

...

Each time the code runs it only returns the first line though it is split correctly any subsequent lines are not parsed and printed to the console.

The Jenkins install is a managed service though I can get additional modules/plugins installed it's the not knowing what to ask for which keeps throwing me.

Upvotes: 3

Views: 15019

Answers (2)

towel
towel

Reputation: 2214

A bit late to the party, but for future viewers readCSV makes CSV consumption super easy because it returns it as a matrix:

readCSV(file: "/tmp/MyCSV.csv").each { line ->
    line.each { field ->
        // ...
    }
}

Upvotes: 6

Rob Hales
Rob Hales

Reputation: 5319

This is a known bug: JENKINS-46988

You can work around this issue like this:

readFile("/tmp/MyCSV.csv").split('\n').each { line, count ->

Upvotes: 5

Related Questions