Issue
I have the following function:
function DivideAndCreateFiles ([string] $file, [string] $ruleName) {
$Suffix = 0
$FullData = Get-Content $file
$MaxIP = 40
while ($FullData.count -gt 0 ){
$NewData = $FullData | Select-Object -First $MaxIP
$FullData = $FullData | Select-Object -Skip $MaxIP
$NewName = "$ruleName$Suffix"
New-Variable -name $NewName -Value $NewData
Get-Variable -name $NewName -ValueOnly | out-file "$NewName.txt"
$Suffix++
}
}
This function takes a file location, this file holds hundreds of ips. it then iterate the file and create files from it each one holding 40 ip's naming it $rulename$suffix so if $rulename=blabla
i would get blabla_0 , blabla_1, .. and so on, each with 40 ips.
i need to convert this logic and put it inside a jenkins job. this file is in the working dir of the job and is called ips.txt
suffix = 0
maxIP = 40
ips = readFile('ips.txt')
...
Id be very happy for some help here re-writing this function, im very new to jenkins / groovy
Thanks in advacne
Solution
You can achieve this easily using something like the following groovy code:
def divideAndCreateFiles(path, rule_name, init_suffix = 0, max_ip = 40){
// read the file and split lines by new line separator
def ips = readFile(path).split("\n").trim()
// divide the IPs into groups according to the maximum ip range
def ip_groups = ips.collate(ips.size().intdiv(max_ip))
// Iterate over all groups and write them to the corresponding file
ip_groups.eachWithIndex { group, index ->
writeFile file : "${rule_name}${init_suffix + index}", text: group.join("\n")
}
}
From my perspective, because you are already writing a full pipeline in groovy, it is easier to handle all logic in groovy, including this function.
Answered By - Noam Helmer