- From: jfotop <
>
- To:
- Subject: [chef] Re: RE: Re: Re: Re: Augeas support
- Date: Wed, 20 Feb 2013 03:33:00 -0800 (PST)
As for the file_edit within a template code:
First of all, for my own purposes in my cookbook/libraries directory I have
added a method to the file_edit class:
#search the file line by line and match each line with the given regex
#if matched, replace the whole line with newline. If not matched, add
#newline to the file.
def search_file_replace_line_or_add(regex, newline)
search_match(regex, newline, 'r', 3)
end
and also modified the line:
when command == 'r'
new_contents << ((method == 1 || method == 3) ? replace :
line.gsub!(exp, replace))
in the "search_match" method, so it can use my new method.
For an example, i will use sshd_config file. I have created the following
attributes that I want to be used and configured from chef:
set['sshd_config_path'] = "/etc/sshd/sshd_config"
set['sshd_config']['SyslogFacility'] = "AUTHPRIV"
set['sshd_config']['PermitRootLogin'] = "without-password"
set['sshd_config']['IgnoreRhosts'] = "yes"
set['sshd_config']['X11Forwarding'] = "no"
then I create a template in a recipe:
template "/etc/ssh/sshd_config" do
source "sshd_config.erb"
mode 0600
owner "root"
group "root"
action :create
notifies :reload, "service[sshd]", :immediately
end
And the then I create the template file "sshd_config.erb" that has the code:
<% temp_file = [] -%>
<% config = Chef::Util::FileEdit.new("/etc/ssh/sshd_config") -%>
<% node.sshd_config.each do |option, value| -%>
<% temp_file = config.search_file_replace_line_or_add("^#{option}",
"#{option}
#{value}\n") -%>
<% end -%>
<% if temp_file[-1] == "\n" -%>
<% temp_file.pop -%>
<% end -%>
<%= temp_file %>
When I tested, i saw that a newline was added each time the array was created,
so the last "if" block removes the new line. This is important as the newline
will make the template checksum change and think that something changed.
So, what we have here is: the sshd_config is copied from each node, all
[sshd_config][some_directive] are checked for existence. If they are found and
not commented out, their values from chef attributes are applied, if they are
not found, they are added along with the value of the attribute. If, on the
next run there is nothing modified, then the template resource does not
change,
no notifications are called.
If you want to add a new attribute, you may. If those 4 attributes are the
ones
you care about you are not afraid to update sshd. Even if the config file
changes, those 4 attributes will be there after the chef run.
Actually, I have to say that I prefer clean templates with with chef
attributes, but in a few cases where it wasn't helpful, I used the
file_edit/template way as an alternative.
- [chef] Re: RE: Re: Re: Re: Augeas support, jfotop, 02/20/2013
Archive powered by MHonArc 2.6.16.