If file does not exists always fails


#1

Hi,

I am having a difficult time.

I simply what to run a temple if a file exists or not.

I am always getting a chef fail about cluster_index.txt not beind found.
its not suposed to be found in certain cases.

How do I make the below more robust.

template “/etc/mysql/my.cnf” do
path "/etc/mysql/my.cnf"
source “my.5.7.index.cnf.erb"
owner “root"
group “root"
mode “0644"
notifies :start, resources(:service => “mysql”)
variables lazy {{:cluster_index =>
File.read(”/var/cluster_index.txt”).gsub(/\n/, “”)}}
only_if {File.exists?(”/var/cluster_index.txt”)}
end

template “/etc/mysql/my.cnf” do
path "/etc/mysql/my.cnf"
source "my.5.7.standalone.cnf.erb"
owner "root"
group “root"
mode “0644"
notifies :start, resources(:service => “mysql”)
not_if {File.exists?(”/var/cluster_index.txt”)}
end


#2

Does the error appear at compile or converge time ? A log of the run could help.

Side note: Why using a file for the cluster_index, is it not managed by chef ?


#3

I would write this as:

template "/etc/mysql/my.cnf" do 
  owner "root" 
  group "root"
  mode "0644"
  notifies :start, "service[mysql]" 
  if File.exist?("/var/cluster_index.txt")
    variables lazy {{:cluster_index => File.read("/var/cluster_index.txt").gsub(/\n/, "")}} 
    source "my.5.7.index.cnf.erb" 
  else
    source "my.5.7.standalone.cnf.erb"
  end
end

However: this is dependent on the cluster_index file being there before your chef run.


#4

I though of the same, but at end I don’t see the value of lazy for the variables as the test on File.exist? is not delayed…
(And I though we should use ::File.exists? to avoid clash between ruby File class and Chef::Recipe namespace File class…)

I would tackle it like this (untested code):

node['run_state']['mysql']['template_source'] = 'my.5.7.standalone.cnf.erb'
node['run_state']['mysql']['cluster_index'] = nil

ruby_block "check mysql cluster" do
  block do
    if File.exist?('/var/cluster_index.txt')
      node['run_state']['mysql']['template_source'] = 'my.5.7.index.cnf.erb'
      node['run_state']['mysql']['cluster_index'] = File.read("/var/cluster_index.txt").gsub(/\n/, "")
    end
  end
end

template "/etc/mysql/my.cnf" do 
  owner "root" 
  group "root"
  mode "0644"
  notifies :start, "service[mysql]" 
  source lazy { node['run_state']['mysql']['template_source'] }
  variables lazy { {:cluster_index => node['run_state']['mysql']['cluster_index'] } }
end

Having a variable given to a template not using it if of no harm.