Ben Ford wrote:

> > I want to resolve a hostname via a custom fact:
> > require "resolv"
> > Facter.add("puppet_master_ip") do
> >   setcode do
> >     Resolv::DNS.open(:nameserver => ['8.8.8.8']) do |dns|
> >       ip = dns.getaddresses("www.puppet.org")
> >     end
> >   end
> > end
> > How do I get the output? I just want to get the first IP.
> 
> Ruby has a habit that it picked up from its Perl ancestor of
> implicitly returning the last expression from a block or function.
> That's a neat shortcut, but that's also why you see so much Ruby code
> that just seems to stop and doesn't show returning of data. Because
> it's the last expression evaluated, your fact is simply returning an
> array of Resolv objects, which Facter doesn't know what to do with.
> 
> To make your code work, you just need to do two things:
> 
> require "resolv"
> Facter.add("puppet_master_ip") do
>   setcode do
> 
> *    ip = nil         # Declare your variable outside the block to
> keep its scope available*    Resolv::DNS.open(:nameserver =>
> ['8.8.8.8']) do |dns|       ip = dns.getaddresses("www.puppet.org")
>     end
> 
> *    ip.first.to_s    # implicitly return the string value of the
> first item*  end
> end
> 
> You should also put your fact in a module and let Puppet pluginsync it
> automatically. You'll need to run facter with the -p flag.
>
https://puppet.com/docs/puppet/latest/plugins_in_modules.html#adding-plug-ins-to-a-module
> 
> Cheers!

Thanks a lot and happy holidays!

helmut@h2786452:~$ facter puppet_master_ip
52.24.136.51
helmut@h2786452:~$

-- 
You received this message because you are subscribed to the Google Groups 
"Puppet Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to puppet-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/puppet-users/xn0lj2uk09pf8j7001%40news.gmane.org.
For more options, visit https://groups.google.com/d/optout.

Reply via email to