Best way to rename a file with chef
Asked Answered
O

2

7

How can I rename a file with chef?

In the chef doc I found only:

  • create
  • create_if_missing
  • delete
  • touch
Overhasty answered 23/11, 2012 at 11:41 Comment(0)
L
10

Use ruby_block and inside use ::File.Rename(src,dst). Chef framework doesn't have file rename (or at least didn't had until 0.10.18).

Just an example:

ruby_block "Rename file" do
  block do
    ::File.rename(new_resource.src,new_resource.dst)
  end
end
Lovemaking answered 23/11, 2012 at 11:47 Comment(3)
I'm just wondering... Is this idempotent? I mean... What happens when this runs for a second time and new_resource.src doesn't exist any longer?Huckster
It will fail. This is just an example. You should assure yourself for the files from disk.Lovemaking
wouldn't you just put a guard? as in only_if { File.exists?(new_resource.src)}Servility
W
1

Another option if you need to rename multiple files. Checks one of the resource to know if it already ran.

ruby_block "Rename file" do
  block do
    ::Dir.glob("*/*.src").each {|i| File.rename(i, i.gsub(/(.*).src/,'\\1.dst'))};
  end
  not_if {File.exists?("new_resource.dst")}
end
Wilke answered 7/7, 2015 at 20:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.