Storing the Server inventory in file and parsing with bash for jenkins

The server inventory list with the list of files in the key value format, separated by the commas. I did this because I tried few jenkins plugin but none of them solved my issue so hope this will help other looking the same. The script will help to solve the following issue.

  • You will select the server in jenkins parameter
  • The respective server ip will be fetched by the bash script parsing the files
  • We can also have multiple server ip under same key or group

Sample inventory list file (server_list.txt):

DEV=111.11.11.1
STAGE=222.22.22.2
ALL=111.11.11.1,2.22.22.2

These are for testing purpose, added random invalid ips.

Bash script to parse the file and fetch the server ip

This is not the only way to write script. You might have better solution that this but it works for me and I use it.

#!/bin/bash

readonly filepath="server_list.txt"
#get items in file with SERVER keys
alllist=`cat $filepath | grep "ALL" `

#get ip only
iponly=${alllist#*=}

 for ip in $(echo $iponly | sed "s/,/ /g")
   do
    echo "$ip"
 done

For better understanding you can echo each line variable to understand what is it exactly doing.

The line number 8 can be made more better by replacing the ALL with variable which will be the SERVER key value passed by the users and the script will fetch the respective server ip based on the key

A quick modification to the script. Why to add the ALL in the inventory list. Simply when user passes ALL that we can read all the items in the inventory for such purpose I have the changes on above script and made it as following.

#!/bin/bash
readonly filepath="/home/nepallink/nepallink_project/testting/server_list.txt"
#get items in file with SERVER keys
item="ALL"

if [[ $item == "ALL" ]]; then 
  while read line ; do
    instance=${line#*=}
    echo $instance
  done < $filepath
else
  all_list=`cat $filepath | grep "DEV"`
  instance=${all_list#*=}
  echo $instance
fi

 

Leave a Reply