I am new to Chef and I am working on environments to output different files for different environments. For example, I want to load a different robots.txt and .htaccess file for either staging or productions environments.
I found the code below from a website but am unsure how to accomplish what i am trying to do. Can this be done in a .erb file or does this have to live in an .rb file?
if node.chef_environment == 'development' do
#
# do not configure basic auth
#
else
#
# configure basic auth
#
end
Also, how would I be able to dynamically change content in files instead of having to create a completely separate file. For instance, a link in a js file I want to change depending on the environment. Can that be done through a variable somewhere?
You could do it either way, but I would do it with an .rb file. If you had a .htaccess.erb file, it would be very congested with all your different environment code mingled together - harder to read/diagnose.
I find it much cleaner to have a cookbook dedicated to environment setup, have it's recipes detect the environment and grab all your configuration files from different places within the cookbook. You would be using the cookbook_file, remote_directory or remote_file resources for this.
Here is a decent example from the cookbook_file resource that detects the platform. You should be able to adapt it to detect the environment and source location of the file instead of the destination path.
cookbook_file "application.pm" do
path case node['platform']
when "centos","redhat"
"/usr/lib/version/1.2.3/dir/application.pm"
when "arch"
"/usr/share/version/core_version/dir/application.pm"
else
"/etc/version/dir/application.pm"
end
source "application-#{node['languages']['perl']['version']}.pm"
owner "root"
group "root"
mode "0644"
end
Something like this might work well for you:
cookbook_file ".htaccess" do
path "/var/www/"
source "apache/#{node['chef_environment'].htaccess"
owner "apache"
group "apache"
mode "0400"
end
This should (I'm rusty and haven't Chef'ed in a while) create a file named .htaccess copied from /<cookbook_directory>/files/apache/development.htaccess on nodes in the development environment, and copied from /<cookbook_directory>/files/apache/production.htaccess on nodes in the production environment. Thus each file is clearly named and free from any logic - less likely to make any mistakes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With