jackofall
jackofall

Reputation: 316

Chef ruby block updating value even after applying guard

I am writing a recipe in chef, where in I am updating a file with ruby_block resource. Every time I do a convergence it adds up the same line at the end of the file.

To make it idempotent I added a not if guard as well, but still it doesn't work.

ruby_block 'edit httpd conf' do
  block do
  rc = Chef::Util::FileEdit.new('/etc/httpd/conf/httpd.conf')
  rc.insert_line_if_no_match("IncludeOptional\ssites-enabled\/\*\.conf", 
"IncludeOptional sites-enabled/*.conf")
  rc.write_file
end
  not_if "grep \"IncludeOptional\ssites-enabled\/\*\.conf\" 
/etc/httpd/conf/httpd.conf"
end

There are 2 things that is not clear to me.

First when I am using insert line if no match then why is it not checking the regex and updating the file.

Second why is not_if guard not working properly.

I may be wrong with regex here and I have read at several places not to use this kind of methods for file editing, but i wanted to append something to file here.

Please guide me a better way of appending to a file or replacing something in the file with updated value also.

Upvotes: 0

Views: 544

Answers (2)

jackofall
jackofall

Reputation: 316

not_if { File.open('/etc/httpd/conf/httpd.conf').lines.any?{|line| line.include?('IncludeOptional sites-enabled')} }

It works this way using not_if guard, which evaluates a file line by line and return boolean if the line exists.

Insert line if no match should work, but dont know why it does not work

Upvotes: 0

Ali
Ali

Reputation: 434

With the not_if grep needs to have -c to only return the exit status code. so the quote about not_if is

A string is executed as a shell command. If the command returns 0, the guard is applied. If the command returns any other value, then the guard attribute is not applied

In your case, it is not returning zero and so the guard is not applied.

check the grep result screenshot

Upvotes: 1

Related Questions