Ruby/Chef include_recipe and know variables from parent file?

11,784

Solution 1

You can't share variables between recipes, but there are two ways to share data between recipes.

  1. The preferred route would be to externalize static and django as attributes in attributes/default.rb. This means they'll become available on the node object and accessible from each recipe.

attributes/default.rb

default["server"]["static"] = []
default["server"]["django] = ["project1", "project2"]

recipes/config.rb

node["server"]["static"].each do |vhost|
  ...
end

node["server"]["django"].each do |vhost|
  ...
end
  1. Use Chef libraries to make a common method that returns these arrays.

My suggestion is to definitely stick with option one, it's the most common approach. Hope that helps!

Solution 2

A bit late to the party on this one, and I think the accepted solution is the preferred option here, but...

It is possible to set a variable in a 'parent' recipe and have it used in an included recipe by modifying the node at converge e.g.

node.default['django'] = ["project1", "project2"]

I have done this in the past where I want a helper recipe to behave slightly differently when called from different 'parent' recipes i.e. installing a different git repo, based on a accessing a slightly different set of config from the attributes.

As to whether this is best practise, I welcome comments, but it seemed easier than writing a resource to wrap the git lwrp.

Share:
11,784

Related videos on Youtube

JREAM
Author by

JREAM

Updated on September 18, 2022

Comments

  • JREAM
    JREAM over 1 year

    I am trying to use a local variable in an included file. I get the error that's it's not defined. I am not sure a way to do this, do you? I have a recipe folder with:

    recipes/
        development.rb
        testing.rb
        config.rb
    

    development.rb

    username = "vagrant"
    static = []
    django = ["project1", "project2"]
    
    include_recipe "server::config"   # <-- Trying to use static and django in there.
    

    config.rb

    static.each do |vhost|  #  <-- How do I get the "static" var in here?
        ...
    end
    
    django.each do |vhost|  #  <-- How do I get the "django" var in here?
        ...
    end
    
  • Arthur Maltson
    Arthur Maltson about 9 years
    Glad to help :)