Dave Shaw
Dave Shaw

Reputation: 97

Read multiple hash keys and keep only unique values

If I have data in Hiera like:

resource_adapter_instances:
  'Adp1':
    adapter_plan_dir: "/opt/weblogic/middleware"
    adapter_plan:     'Plan_DB.xml'
  'Adp2':
    adapter_plan_dir: "/opt/weblogic/middleware"
    adapter_plan:     'ODB_Plan_DB.xml'
  'Adp3':
    adapter_plan_dir: "/opt/weblogic/middleware"
    adapter_plan:     'Plan_DB.xml'

And I need to transform this into an array like this, noting duplicates are removed:

[/opt/weblogic/middleware/Plan_DB.xml, /opt/weblogic/middleware/ODB_Plan_DB.xml]

I know I have to use Puppet's map but I am really struggling with it.

I tried this:

$resource_adapter_instances = hiera('resource_adapter_instances', {})
$resource_adapter_paths = $resource_adapter_instances.map |$h|{$h['adapter_plan_dir']},{$h['adapter_plan']}.join('/').uniq
notice($resource_adapter_instances)

But that doesn't work, and emits syntax errors. How do I do this?

Upvotes: 1

Views: 1169

Answers (1)

Alex Harvey
Alex Harvey

Reputation: 15472

You are on the right track. A possible solution is as follows:

$resource_adapter_instances = lookup('resource_adapter_instances', {})
$resource_adapter_paths =
  $resource_adapter_instances.map |$x| {
    [$x[1]['adapter_plan_dir'], $x[1]['adapter_plan']].join('/')
  }
  .unique
notice($resource_adapter_paths)

A few further notes:

  • The hiera function is deprecated so I rewrote using lookup and you should too.

  • Puppet's map function can be a little confusing - especially if you need to iterate with it through a nested Hash, as in your case. On each iteration, Puppet passes each key and value pair as an array in the form [key, value]. Thus, $x[0] gets your Hash key (Adp1 etc) and $x[1] gets the data on the right hand side.

  • Puppet's unique function is not uniq as in Bash, Ruby etc but actually is spelt out as unique.

  • Note I've rewritten it without the massively long lines. It's much easier to read.

If you puppet apply that you'll get:

Notice: Scope(Class[main]): [/opt/weblogic/middleware/Plan_DB.xml,
  /opt/weblogic/middleware/ODB_Plan_DB.xml]

Upvotes: 3

Related Questions