user3617841
user3617841

Reputation: 11

Chef: passing variables

Everytime we create a new server I have a bash script that asks the end-user a set of questions to help chef configure the custom server, his/her answer to those questions needs to be injected into chef so that I can use their responses within my chef script (to set the server "hostname" = "server1.stack.com", for instance). There is a json attribute when running chef-client I've read about that may be helpful but I'm not sure how that would work in our environment.

Note: We run chef-client on all of our systems every 15 minutes via cronjob to get updates.

Psuedocode:

echo -n "What is the server name?"
read hostname

chef-client -j {'hostname' => ENV['$hostname']}

Upvotes: 0

Views: 749

Answers (2)

Tejay Cardon
Tejay Cardon

Reputation: 4223

Passing raw json into chef-client is possible, but requires a little creativity. You simply do something like this:

echo '{"hostname": "$hostname"}' | chef-client -j /dev/stdin

The values in your json will be deep merged with the "normal" attributes stored in the chef-server. You can also include a run_list in your json, which will replace (not be merged) the run_list on the chef server.

You can see the run_list replacing the server run list here: https://github.com/opscode/chef/blob/cbb9ae97e2d3d90b28764fbb23cb8eab4dda4ec8/lib/chef/node.rb#L327-L338

And you can see the deep merge of attributes here: https://github.com/opscode/chef/blob/cbb9ae97e2d3d90b28764fbb23cb8eab4dda4ec8/lib/chef/node.rb#L305-L311

Also, any attributes you declare in your json will override the attributes already stored on the chef-server.

Upvotes: 1

coderanger
coderanger

Reputation: 54267

Two issues, first is that -j takes a filename not raw JSON and second is that using -j will entirely override the node data coming from the server which also includes the run list and environment. If this is being done at system provisioning time you can definitely do stuff like this, see my AMI bootstrap script for an example. If this is done after initial provisioning, you are probably best off writing those responses to a file, and then reading that in from you Chef recipe code.

Upvotes: 1

Related Questions