Skip to content

Instantly share code, notes, and snippets.

@MikaelSmith
Last active April 1, 2022 11:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikaelSmith/14bfddd1ebe5283defc83f98e3c6b410 to your computer and use it in GitHub Desktop.
Save MikaelSmith/14bfddd1ebe5283defc83f98e3c6b410 to your computer and use it in GitHub Desktop.
Transforming hash in Puppet
$data = [
{
"certname" => "server1",
"parameters" => {
"port" => 1234,
"job" => "job1"
}
},
{
"certname" => "server2",
"parameters" => {
"port" => 5678,
"job" => "job1"
}
},
{
"certname" => "server3",
"parameters" => {
"port" => 987,
"job" => "job2"
}
}
]
$output = $data.reduce({}) |$memo, $entry| {
# Group entries by job
$job = $entry['parameters']['job']
$address = "${$entry['certname']}:${$entry['parameters']['port']}"
if $memo[$job] {
# Have to merge into the old hash because values are immutable in Puppet
$memo + { $job => $memo[$job] + [$address] }
} else {
$memo + { $job => [$address] }
}
}.map |$job, $entries| {
{
'job' => $job,
'entries' => $entries
}
}
notice($output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment