Ask Your Question
0

get list of directory subdirectories

asked 2017-09-10 02:43:25 -0500

sinaowolabi gravatar image

updated 2017-09-10 02:48:01 -0500

Hi! I am trying to create a custom fact that returns the list of subdirectories within a subdirectory, if the subdirectory exists. For example, if the computer has /data/files, I need to obtain all the subdirectories inside it (/data/files/one, /data/files/two, /data/files/three), without the prefix path (so just (one two three).

I tried to write a custom fact but I am failing woefully,

Facter.add(:datasubdirs) do
    result = ''
    setcode do
            if File.directory? '/data/files' do |str|
                    Facter::Util::Resolution.exec('/bin/ls  /data/files/')
            result += str
            end
            end
    end

end

Please what am I doing wrong and how can I make it better?

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2017-09-10 19:50:36 -0500

Uargh, why are you leaving your ruby environment? On a shell one would use find(1), like so:

[ -d /data/files ] && find /data/files -type d -maxdepth 1 -printf '%f\n'

but we don't have to waste resources and spawn (another) process. So

Facter.add('datasubdirs') do
  setcode do
    Dir.glob('/data/files/*/').map do |x|
      File.basename(x)
    end
  end
end

does the trick and is by far more beautiful. Especially, it returns your directory names in a structured fashion, meaning they're in an array.

edit flag offensive delete link more
0

answered 2017-09-10 03:31:01 -0500

sinaowolabi gravatar image

updated 2017-09-10 03:31:23 -0500

I think I have gotten it working somewhat: This:

Facter.add(:datasubdirs) do
    setcode do
            if File.directory? '/data/files'
                    dirs = Facter::Core::Execution.exec('/bin/ls /data/files/ | /bin/tr  "\n" " " | sed "s/ *$//"')
            end
            dirs
            end

end returns the following when I run puppet facts find all on a client:

"datasubdirs":"two three one"
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2017-09-10 02:43:25 -0500

Seen: 30 times

Last updated: Sep 10