Search code examples
pythonpuppet

PuppetDb Python script get fact if exists?


I'm using the PuppetDb python library. I want to print the value of a fact if it exists.

for group in groups:
  node = puppetdb.node(group[0])
  if hasattr(node.facts, 'custom_fact'):
    print node.fact('custom_fact')

I'm relatively new to python but I read here that the above method should allow me to check if an object has an attribute.

Not sure if I misunderstood the instructions or if a PuppetDb object acts differently.

How can I print custom_fact only if it exists?


Edit: when I use print node.facts it says that node.facts is a bound method. So I'm trying this also (with osfamily fact because it should always return something):

for group in groups:
  node = puppetdb.node(group[0])
  facts = node.facts()
  print facts
  if hasattr(facts, 'osfamily'):
    print facts('osfamily')

print facts returns <generator object facts at 0x7f906ffe35f0>

print node.facts('custom_fact') is never run.

Also trying dir(facts) to look for attributes which doesn't return anything, which leads me to believe this isn't a normal object.


Solution

  • I found using try/except works better:

    for group in groups:
      print group[0]
      node = puppetdb.node(group[0])
      try:
        print node.fact('custom_fact').value
      except:
        pass