Access variable defined in each {}

9 views
Skip to first unread message

Helmut Schneider

unread,
Mar 19, 2020, 5:11:48 PM3/19/20
to puppet...@googlegroups.com
Hi,

class abc {
keys($netconfig['interfaces']).each |String $interface| {
if $netconfig['interfaces'][$interface]['ip6'] {
$myvariable = 'yes'
break()
}
}

if $myvariable == 'yes' {
do something
}
}

How can I access $myvariable?

Thank you!

Henrik Lindberg

unread,
Mar 19, 2020, 5:55:16 PM3/19/20
to puppet...@googlegroups.com
You cannot access local variables from outside a lambda using the each
function - its contract is to return the input to allow chaining. What
you are actually doing is reducing a collection of interfaces to a
single value - which you can do with the reduce() function. In this
particular case it seems much simpler as you are really asking if
there is any interface that has something that is true for 'ip6' - you
can therefore use the `any()` function.

Perhaps something like this:

if $netconfig['interfaces'].any() |$k, $v| { $v['ip6'] =~ NotUndef } {
# do something
}

No need for a variable or anything - if you do need one do this:

$myvariable = $netconfig['interfaces'].any() |$k, $v| {
$v['ip6'] =~ NotUndef
}

if $myvariable {
# do something
}

- henrik



--

Visit my Blog "Puppet on the Edge"
http://puppet-on-the-edge.blogspot.se/

Helmut Schneider

unread,
Mar 20, 2020, 5:27:17 AM3/20/20
to puppet...@googlegroups.com
Am 19.03.2020 um 22:54 schrieb Henrik Lindberg:
> On 2020-03-19 22:11, Helmut Schneider wrote:
>> Hi,
>>
>> class abc {
>>   keys($netconfig['interfaces']).each |String $interface| {
>>     if $netconfig['interfaces'][$interface]['ip6'] {
>>       $myvariable = 'yes'
>>       break()
>>     }
>>   }
>>
>>   if $myvariable == 'yes' {
>>     do something
>>   }
>> }
>>
>> How can I access $myvariable?
>
> No need for a variable or anything - if you do need one do this:
>
> $myvariable = $netconfig['interfaces'].any() |$k, $v| {
> $v['ip6'] =~ NotUndef
> }
>
> if $myvariable {
> # do something
> }

Works like a charm.

Thank you!

Reply all
Reply to author
Forward
0 new messages