问题
I would like my chef recipe to delete all files that match a certain regex. What would be the way to go about this?
回答1:
You could use an execute
resource in your recipe:
execute "Deleting files ... " do
command "find . -regex 'REGEX' -delete"
cwd "/path/to/folder"
action :run
end
The command expects a target system having the find
command.
回答2:
Depending on your use case, the previous answers may work. However, using bash's native delete functionality is not cross-platform. Additionally, depending on the level of control you need over the resources, you may want to use a more Ruby-like approach:
Dir["/path/to/folder/{YOUR_REGEX}"].each do |path|
file ::File.expand_path(path) do
action :delete
end
end
This will create a unique entry in the resource collection for each file that matches the regex. It is also idempotent (meaning it won't run if the files are already deleted) and cross-platform (it will work on Windows too).
回答3:
A scenario where you'd want to do this is cleaning up files installed/setup from a previous version of a recipe.
I found this cookbook that provides several useful recipes for these cleanup purposes: https://github.com/nvwls/zap
zap_directory '/etc/sysctl.d' do
pattern '*.conf'
end
zap_crontab 'root' do
pattern 'test \#*'
end
zap_users '/etc/passwd' do
# only zap users whose uid is greater than 500
filter { |u| u.uid > 500 }
end
来源:https://stackoverflow.com/questions/24431500/deleting-all-files-matching-a-regular-expression-in-chef