Reputation: 193
I am still a beginner in Puppet. So please bear with me. Let's assume i have this hash created in Puppet through some module
account = {
user@desktop1 => {
owner => john,
type => ssh-rsa,
public => SomePublicKey
},
user@desktop2 => {
owner => mary,
type => ssh-rsa,
public => SomePublicKey
},
user@desktop3 => {
owner => john,
type => ssh-rsa,
public => SomePublicKey
},
user@desktop4 => {
owner => matt,
type => ssh-rsa,
public => SomePublicKey
}
}
How can i find find the key for specific key and value pair inside the hash? which in this case just for example i want to find all the key owned by john
. So the expected result would be something like:
[user@desktop1, user@desktop3]
Thanks in advance
Upvotes: 0
Views: 2299
Reputation: 15472
The question asks about how to do this in Puppet, although, confusingly, the Hash is a Ruby Hash and the question also has a Ruby tag.
Anyway, this is how you do it in Puppet:
$account = {
'user@desktop1' => {
'owner' => 'john',
'type' => 'ssh-rsa',
'public' => 'SomePublicKey',
},
'user@desktop2' => {
'owner' => 'mary',
'type' => 'ssh-rsa',
'public' => 'SomePublicKey',
},
'user@desktop3' => {
'owner' => 'john',
'type' => 'ssh-rsa',
'public' => 'SomePublicKey',
},
'user@desktop4' => {
'owner' => 'matt',
'type' => 'ssh-rsa',
'public' => 'SomePublicKey',
}
}
$users = $account.filter |$k, $v| { $v['owner'] == 'john' }.keys
notice($users)
Puppet applying that leads to:
Notice: Scope(Class[main]): [user@desktop1, user@desktop3]
Upvotes: 3
Reputation: 11193
Another option using Enumerable#each_with_object
:
account.each_with_object([]) { |(k, v), a| a << k if v['owner'] == 'john'}
#=> ["user@desktop1", "user@desktop3"]
Supposing keys and values to be String
.
Upvotes: 1
Reputation: 22926
https://ruby-doc.org/core-2.5.1/Hash.html#method-i-select
account.select {|key, value| value['owner'] == 'john'}.keys
Upvotes: 2