Evaluate all but one file in a directory - InSpec

Hello,
Hoping someone might be able to help me out with a specific issue here. I would imagine this is a very common case but I can find no explicit answers...

I want to run a control where I evaluate file properties for each object in a directory. The expectation is that every single object in this directory is a file, except for a single directory that is nested within.

Say I have a directory with 5 files and 1 directory.

When I run:

::Dir.glob('/etc/a_directory/*').each do |f|
    describe file(f) do
    it { should exist }
    it { should be_file }
    its('mode') { should cmp '0440' }
  end
end

It checks every file like it is supposed to, but obviously gets to my directory and the test fails on it because it is not a file. How do I exclude just that single nested directory?
I have experimented with only_if() but it just causes the whole control to be cancelled.

Can I embed Ruby if/then statements? The file names in the directory will be variable, so I can't hard code them. The directory name will be constant however. How do I exclude this single directory from evaluation - or at least prevent it from failing the control?

Thanks

Have you tried using the .reject option to exclude the sub directories?

I have tested this and it seems to solve the issue you have outlined:

dirfiles = ::Dir.glob('/etc/yourdirectory/*').reject do |path|
  File.directory?(path)
end
dirfiles.each do |f|
  describe file(f) do
    it { should exist }
    it { should be_file }
    its('mode') { should cmp '0440' }
  end
end
1 Like

Thanks much for this @byteflyer ! After taking a look I think this should solve the issue as well - let us know if that works for you :+1:

Fantastic! The .reject option combined with the dirfiles object creation was what I was missing! I applied both and they work as intended. This helps quite a bit, thank you!