How to do an "unless" conditional when changing permissions in a ruby_block in chef?

Viewed 303

In chef I Have a ruby_block where I am changing permissions and ownership of a directory. How can I do a check where the permissions are only changed if they have not already been changed by the " FileUtils.chown" statement? I need to do this within the ruby_block if possible because i am ganna have other code in the ruby block. What would my "unless" statement be? Here is my code:

  ruby_block 'exe' do
    block do
      FileUtils.chmod 0755, '/make/news'
      FileUtils.chown('root', 'root', '/make/news')
    end
  end
2 Answers

The correct way to do this is to use Chef's file resource:

file '/make/news' do
  mode 0755
  owner 'root'
  group 'root'
end

You're going down the road of trying to re-write the file resource which is not a good idea.

Using the Chef Resource's not_if Guard

Chef resources share a number of common functions. The ruby_block resource supports the not_if property as a conditional guard. The general format is:

ruby_block 'custom chmod' do
  block do
    #
  end

  not_if { true }
end

So, you could program your logic this way, but it will eventually bite you badly. Chef often works better if you use a file or directory resource declaratively using a separate block to manage permissions, and then (if necessary) chain it with a notification from some other block that needs a given permission set. For example:

directory '/make/news' do
  mode  '0755'
  owner 'root'
  group 'root'
  action :nothing
end

ruby_block 'do something with news' do
  block do
    #
  end

  only_if { true }
  notifies :create, 'directory[/make/news]', :before
end

That said, the goal of configuration management is to continuously converge, so I'd strongly question whether creating this interdependency between resource blocks is truly necessary in the first place. If possible, just converge your directory permissions every time to enforce them. While this may create a sequencing dependency within your recipe, a more declarative approach often simplifies cookbook and recipe debugging in the long run. Your individual mileage may vary.

Related