Remove value from hash Puppet

I have the following options in hiera:

base::users:
  john@example.com:
    ensure: present
    user: john
    sudo: true
    type: ssh-rsa
    key: AAAAB3NzaC1yc2EAAAABJ

      

in the puppet I get the following hash:

 {john@example.com => {ensure => present, user => john, sudo => true, type => ssh-rsa, key => AAAAB3NzaC1yc2EAAAABJ}}

      

Then I call create resources to create the corresponding authorized_keys file:

create_resources('ssh_authorized_key', $users)

      

but it doesn't work because I added a new parameter 'sudo' and before calling create_resources I want to remove this key from the hash and work on another resource.

I tried the following step to remove it:

$users_filtered = $users.each |$k, $v| { $v.delete['sudo'] }

      

I am getting the following error:

Error while evaluating a Function Call, delete(): Wrong number of arguments given 1 for 2.

      

As I understand it, the puppet was trying to use the "delete" function from the stdlib module. But I also tried:

$users_filtered = $users.each |$k, $v| { delete($users, $v['sudo'] }

      

But that won't work. Appreciate any help

+3


source to share


1 answer


Checking the documentation for the function delete

from stdlib

, we see that the two arguments in your case must be a hash to remove the key and a key to remove from the hash.

https://github.com/puppetlabs/puppetlabs-stdlib#delete

$users_filtered = $users.each |$k, $v| { $v.delete['sudo'] }

      

The problem with this line is that you are treating delete

as a hash with a key sudo

. delete

is a function, not a hash. $v

- these are your hash values ​​in the lambda iterator each

here. You can fix this with

$users_filtered = $users.each |$k, $v| { $v.delete('sudo') }

      

viewed delete

as a function. Also, if you want to pass $users_filtered

to a function create_resources

then it must be a nested hash with each key as a header. Therefore your lambda should return a nested hash, which means you need to use map

instead to return a nested hash.

$users_filtered = $users.map |$k, $v| { $v.delete('sudo') }

      

https://docs.puppet.com/puppet/4.10/function.html#map



Then we have another try:

$users_filtered = $users.each |$k, $v| { delete($users, $v['sudo'] }

      

which must also return a hash and must have a key as its second argument. You are specifying $v['sudo']

as the second argument and instead the key value sudo

in this hash. We fix this in a similar way via:

$users_filtered = $users.map |$k, $v| { delete($v, 'sudo'}

      

Note that the two versions of the solution are syntactically different but give the same result and both are acceptable in modern Puppet DSL function calls.

It's also worth noting that you can eliminate the need for an iterator entirely by using delete

the hash for the entire hash from your example.

$users_filtered = delete($users, 'sudo')

      

+9


source







All Articles