Custom Fact Help? Works in ruby, but not facter...

128 views
Skip to first unread message

smalderma

unread,
May 28, 2014, 10:16:47 AM5/28/14
to puppet...@googlegroups.com
Hi,

I'm working on custom fact that uses Facter::Util::Resolution.exec to run a command that returns output I want to parse with regex.  If I write up a ruby shell script like:

#!/usr/bin/ruby

out = `<command>`
out = out.gsub!(/<regex>/, "\\1\\3")
puts "#{out}"

The desired output comes to the screen, every time, and on every system I run it.

If I modify the script to be a fact like so:

# custom fact
require 'facter'
Facter.add(:newfact) do
  out = Facter::Util::Resolution.exec("<command>")
  out = out.gsub!(/<regex>/, "\\1\\3")
  secode { out }
end

A puppet run actually prints the full output of the command twice after syncing the fact.  Running facter -p newfact does the same.  On top, the printed output is the raw output not the regex filtered.

What am I doing wrong here?

Thanks!

jcbollinger

unread,
May 29, 2014, 9:53:14 AM5/29/14
to puppet...@googlegroups.com


For one thing, you are performing your fact evaluation outside the setcode {} block.  The part in the block passed to Facter.add() but outside setcode {} runs when the fact is added to Facter, but the part inside the setcode {} block is run when the fact is evaluated.  I speculate that you are getting output both times. 

There are very few statements that should ever appear in that middle area.  The one that comes first to mind is 'confine', and others would be similar Facter-specific things.

Your fact should look more like this:

require 'facter'
Facter.add(:newfact) do
  setcode {
    out = Facter::Util::Resolution.exec('<command>')

    # F::U::R::exec() may return nil
    out or out.gsub(/<regex>/, "\\1\\3")
  }
end


Note that whatever value is returned by the setcode {} block is taken as the value of the fact.  There is no particular advantage to assigning it to a variable first, though it is harmless to do so.


John

smalderma

unread,
May 30, 2014, 12:57:02 PM5/30/14
to puppet...@googlegroups.com
John,
  Thanks for the assist.  I guess I was working from a less than stellar example.
Reply all
Reply to author
Forward
0 new messages