How do you modulate a chef's recipe?

Here is an example working recipe that looks through an array of website names and creates them in IIS using the createIisWebsite () function.

def createIisWebsite(websiteName) iis_site websiteName do protocol :http port 80 path "#{node['iis']['docroot']}/#{websiteName}" host_header "#{websiteName}.test.kermit.a-aws.co.uk" action [:add,:start] end end 
In our real solution, this data is stored elsewhere and is accessible through the web API.
 websiteNames = ["website-2", "website-3", "website-4"] for websiteName in websiteNames do createIisWebsite websiteName end 

Now I want to be able to call the createIisWebsite () function from several recipes in this cookbook.

I tried to drop it into a helper module (library). There I can not get the link to iis_site to work.

I tried moving the function to default.rb and then doing include_recipe ":: default". This also doesn't seem to work.

I get the message "Cannot find the resource for createIisWebsite in Windows version 6.2.9200"

The reason I use this approach is because I want to have a recipe containing a list of websites on a cluster of web servers. I have a feeling that I do not choose the best practice route.

Any ideas?

+7
source share
1 answer

The problem is that the function is defined inside the recipe and can only be used in this recipe. The include_recipe method ensures that the recipe is loaded, but it does not import anything into the recipe that makes the inclusion.

Since your function is used to declare a chef's resource with some calculated parameters, the closest thing you can pay attention to is Definition (Chef Docs) . Definitions look similar to resources that have a name and a set of optional parameters, but are actually simple macros that expand into a recipe when compiled.

In your cookbook directory, create definitions/my_iis_website.rb containing something like:

 define :my_iis_website do iis_site websiteName do protocol :http port 80 path "#{node['iis']['docroot']}/#{websiteName}" host_header "#{websiteName}.test.kermit.a-aws.co.uk" action [:add,:start] end end 

Then replace the loop in your recipe with:

 for websiteName in websiteNames do my_iis_website websiteName end 

If your recipes for each server cluster are identical, but for a list of sites, you may want to save this data in attributes or data bags . This will help you avoid repeating yourself in your recipes, and also allow you to add sites without updating your cookbook.

+6
source

Source: https://habr.com/ru/post/944462/


All Articles