Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting all files matching a regular expression in chef

Tags:

chef-infra

I would like my chef recipe to delete all files that match a certain regex. What would be the way to go about this?

like image 697
deadonarrival Avatar asked Jan 28 '26 05:01

deadonarrival


2 Answers

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).

like image 154
sethvargo Avatar answered Jan 29 '26 22:01

sethvargo


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
like image 38
Sebastian Avatar answered Jan 29 '26 22:01

Sebastian