Search code examples
chef-infracookbook

Chef: reading attribute value from shell environment variables


I am trying to read value of an environment variable in attributes file of chef cookbook. Many posts have described that i can use ENV[] of ruby to achieve what i want.

My attributes file looks something like this

default['some_object']['some_attribute'] = ENV['SOME_ENV_VAR']

While running recipe, it seems to result in empty string. Any pointers?


Solution

  • assume that what you describe is the right way to do so (which is not), note that you need to set the environment variable on the node where you execute chef-client.

    chef-client execution, has several phases:

    • compilation phase: all recipes are loaded in the order specified by the expanded run-list.
    • convergence phase: Each resource is executed in the order identified by the run-list, and then by the order in which each resource is listed in each recipe. ...each action configures a specific part of the system.

    for more information about chef-client about the phase, see chef-client overview.

    the evaluation of your environment variable, namely ENV['SOME_ENV_VAR'] happens on the compilation phase. what you should really do, is to use json attribute:

    you can provide custom attributes by including --json-attributes (i strongly advise you to visit the documentation, since it holds examples) in chef-client

    -j PATH, --json-attributes PATH The path to a file that contains JSON data. Used to setup the first client run. For all the future runs with option -i the attributes are expected to be persisted in the chef-server.

    you can always use the environment variables that are set for you to construct a json structure and then feed it to chef-client when you execute it.