Parsing config file with sections in Jenkins Pipeline and get specific section

1.4k views Asked by At

I have to parse a config with section values in Jenkins Pipeline . Below is the example config file

[deployment]
10.7.1.14
[control]
10.7.1.22
10.7.1.41
10.7.1.17
[worker]
10.7.1.45
10.7.1.42
10.7.1.49
10.7.1.43
10.7.1.39
[edge]
10.7.1.13

Expected Output: control1 = 10.7.1.17 ,control2 = 10.7.1.22 ,control3 = 10.7.1.41

I tried the below code in my Jenkins Pipeline script section . But it seems to be incorrect function to use

def cluster_details = readProperties interpolate: true, file: 'inventory'
echo cluster_details
def Var1= cluster_details['control']
echo "Var1=${Var1}"

Could you please help me with the approach to achieve the expected result

2

There are 2 answers

2
max.ivanch On

Regarding to documentation readProperties is to read Java properties file. But not INI files.

https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readproperties-read-properties-from-files-in-the-workspace-or-text

I think to read INI file you have find available library for that, e.g. https://ourcodeworld.com/articles/read/839/how-to-read-parse-from-and-write-to-ini-files-easily-in-java

0
Manish Pandey On

Hi i got the solution for the problem

control_nodes = sh (script: """
                manish=\$(ansible control -i inventory --list-host |sort -t . -g -k1,1 -k2,2 -k3,3 -k4,4 |awk '{if(NR>1)print}' |awk '{\$1=\$1;print}') ; \
                echo \$manish
                """,returnStdout: true).trim()
echo "Cluster Control Nodes are : ${control_nodes}"
def (control_ip1,control_ip2,control_ip3) = control_nodes.split(' ')
//println c1 // this also works
echo "Control 1: ${control_ip1}"
echo "Control 2: ${control_ip2}"
echo "Control 3: ${control_ip3}"

Explaination: In the script section . I am getting the list of hostnames.Using sort i am sorting the hostname based on dot(.) delimeter. then using awk removing the first line in output. Using the later awk i am removing the leading white spaces.

Using returnStdout to save the shell variable output to jenkins property, which has list of ips separated by white space. Now once i have the values in jenkins property variable, extracting the individual IPs using split methods. Hope it helps.