Contention
Contention

Reputation: 691

How to use variables in Chef/Ruby execute command?

I'm creating a simple Chef cookbook that sets up vhosts on a VPS. I have this working in terms of creating the correct .conf files by passing the domain variable to a Chef/.erb template, but I'm also trying to do this too (simplified code example):

node[:domains].each do |domain|
    execute 'sudo mkdir -p /var/www/#{domain}/public_html'
end

However, the variables aren't being output into the string, and the command is simply creating a folder called:

/var/www/#{domain}/public_html

So... is there an accepted way to use variables from a loop in a Chef execute command - or is it that my Ruby syntax is out of whack?

Upvotes: 3

Views: 5641

Answers (1)

Psyreactor
Psyreactor

Reputation: 343

Use double quotes, not single quotes, when trying to inject variables into strings.

node [: domains] .each do | domain |
     execute "create_dir_#{domain}" do
       command   "sudo mkdir /var/www/#{domain}/public_html"
     end
end

and I recommend using the directory resource rather than execute

node [: domains] .each do | domain |
     directory "/var/www/#{domain}/public_html" do
       recursive true
       action :create
     end
end

Upvotes: 6

Related Questions