0

In scripting languages like shell/perl, I could use variables to get a specific directory name at run time which can be used in the script. But inside a chef recipe how do I make use of variables without passing them as parameters

I want to assign output of a shell command line to a variable- How do I achieve it within a chef recipe. I am using chef-solo.

Shell example:

install_dir=`grep install /tmp/my_info.txt | cut -d"/" -f4`
cd /dev/install_dir
sethvargo
  • 26,739
  • 10
  • 86
  • 156
Balualways
  • 4,250
  • 10
  • 38
  • 51
  • possible duplicate of [Chef Solo get user input](http://stackoverflow.com/questions/19754127/chef-solo-get-user-input) – sethvargo Aug 07 '14 at 16:32

1 Answers1

0

Have you tested out your recipe? The syntax is already correct. For instance if I have a file /tmp/my_info.txt and the contents of said file are something like:

install is here
but not here

And I run the following Chef recipe:

install_dir = `grep install /tmp/my_info.txt`
Chef::Log.error("Result of grep is: #{install_dir}")

Then the output from a chef-client run will be:

ERROR: Result of grep is: install is here

If you need to use install_dir in some resource (which you haven't really shown), it could be something as simple as:

directory "#{install_dir}" do
  owner "root"
  group "root"
  mode 00644
  action :create
end
Display Name is missing
  • 6,197
  • 3
  • 34
  • 46
  • Yes I could make it happen by writing the values to files, and creating another file with formatted value. But it sounds like too much overhead for a variable usage. First I will create the myinfo file as : unzip #{extract_path}/* -d /tmp | grep install.csh | cut -d":" -f2 > /tmp/my_info.txt Then I will extract the directory name as install_dir=`grep install /tmp/my_info.txt | cut -d"/" -f4` echo "/dev/#{install_dir}/setup > /dev/install_script_path grep again to another variable to get the output string – Balualways Aug 07 '14 at 19:32
  • ??? So I guess I don't understand what your question is, the above works. If it seems silly to do it all via calls like those above, write your own shell script to call from Chef with the `bash` resource – Display Name is missing Aug 07 '14 at 21:40
  • @DisplayNameismissing You might have missed a lead from the question, indeed. It reads: "How do I assign a value to a variable inside my chef recipe **at runtime**". Variables assigned in chef with the backtick syntax are assigned at *compile time* as opposed to *execution time* (a.k.a. runtime). Therefore, if the data doesn't exist **before** the chef execution, it will fail. See http://stackoverflow.com/questions/25980820/ for further information. – 7heo.tk May 13 '15 at 14:11
  • @7heo.tk good call - that link helps. But as are many questions on SO... the world will never know until Balualways responds ;) – Display Name is missing May 13 '15 at 15:45