Search code examples
rubychef-infracookbookrecipe

Run arbitrary ruby code in a chef cookbook


I have a simple chef cookbook and all it does is it sets the MOTD on a CentOS machine. It takes the content of the /tmp/mymotd.txt and turns it into the MOTD.

I also have a simple ruby script (a full-fledged ruby script) that simply reads the text from the web-server and puts in into the /tmp/mymotd.txt.

My questions are:

  1. how do I run this ruby script from within the cookbook?
  2. how do I pass some parameters to the script (e.g. the address of the web-server)

Thanks a lot beforehand.


Solution

  • Ad 1.

    You can use libraries directory in scripts to place there your ruby script and declare it in a module. Example:

    # includes
    module MODULE_NAME
        # here some code using your script 
    
        # Example function
        def example_function (text)
            # some code
        end
    end
    

    You can use then

    include MODULE_NAME
    

    in your recipe to import those functions and just use it like

    example_function(something)
    

    What's good - you can use there also Chef functions and resources.

    IMPORTANT INFO: Just remember that Chef has 2 compilation phases. First will be all of Ruby code, second all of Chef resources. This means, that you have to remember priority of code. I won't write here more info about it, since you haven't asked for this, but if you want, you can find it here.

    Ad 2.

    You can do this in several ways, but it seems to me, that the best option for you would be to use environments. You can find more info in here. Basically, you can set up environment for script before it will run - this way you can define some variables you would use later.

    Hope this helps.