Matt
Matt

Reputation: 77

Variable number of properties sent to Chef resource based off of recipe code

I want to pass a variable number of properties to a resource based off of the values that are available in the attributes.

Here is an idea of what I want to do. The if logic around the properties is what I am wanting but not sure if it is possible to do something like that...

rpms = [ 
  {
    "name": "name",
    "version": "version",
    "release": "release",
    "arch": "arch"
  },
  {
    "name": "name"
  }
]

rpms.each do | package_info |
  custom_package 'install' + package_info['name'] do
    name package_info['name']
    if defined?(package_info['version'])  # Only pass that property if it is available
      version package_info['version']
    end
    if defined?(package_info['release'])  # Only pass that property if it is available
      version package_info['release']
    end
    if defined?(package_info['arch'])  # Only pass that property if it is available
      version package_info['arch']
    end
  end
end

Is there anything like this available in Chef?

Upvotes: 1

Views: 35

Answers (1)

Draco Ater
Draco Ater

Reputation: 21206

You can do it using Ruby's send method, which invokes the method identified by the first argument, passing it any other arguments specified.

rpms = [ 
  {
    "name": "name",
    "version": "version",
    "release": "release",
    "arch": "arch"
  },
  {
    "name": "name"
  }
]

rpms.each do |package_info|
  custom_package "install ${package_info['name']}" do
    package_info.each do |key, value|
      send(key, value)
    end
  end
end

Upvotes: 1

Related Questions