0

I am trying to figure out how I can use Facter facts inside a Ruby template erb file configured with Puppet.

Sample Ruby template variable

zk.l.conn=

Expected config file output from Puppet

zk.l.conn=ip-xx-31-xx-xxx.ec2.internal:2181,ip-xxx-31-xx- xxx.ec2.internal:2181,ip-172-xxx-xxx-xx.ec2.internal:2181

Facter fact data:

"zk-internal": [
  {
    "host": "ip-xx-31-xx-xxx.ec2.internal",
    "port": 2181,
    "priority": 2,
    "weight": 10
  },
  {
    "host": "ip-xxx-31-xx-xxx.ec2.internal",
    "port": 2181,
    "priority": 3,
    "weight": 10
  },
  {
    "host": "ip-172-xxx-xxx-xx.ec2.internal",
    "port": 2181,
    "priority": 1,
    "weight": 10
  }
],
Matthew Schuchard
  • 25,172
  • 3
  • 47
  • 67
rocky
  • 137
  • 1
  • 2
  • 6

1 Answers1

3

In short:

zk.1.conn=<%= @facts['zk-internal'].map { |h| "#{h['host']}:#{h['port']}" }.join(',') %>

@facts['zk-internal'] lets you access the structured fact value, used because @zk-internal wouldn't be a valid variable name due to the hyphen.

.map { |h| "#{h['host']}:#{h['port']}" } iterates over every element and returns new strings containing "host:port" from each element, so you have an array of hosts/ports returned.

.join(',') returns a string from the array with each element comma-separated.

This outputs:

zk.1.conn=ip-xx-31-xx-xxx.ec2.internal:2181,ip-xxx-31-xx-xxx.ec2.internal:2181,ip-172-xxx-xxx-xx.ec2.internal:2181

(Tested on Puppet 4.7)

Dominic Cleal
  • 3,205
  • 19
  • 22
  • Clever to use `.map` to retain it as an array during iteration so you can use `.join` for the commas. – Matthew Schuchard Nov 02 '16 at 12:19
  • Excellent ! but If i need to add port to each ip like example ip-xx-31-xx-xxx.ec2.internal:2181? – rocky Nov 02 '16 at 14:59
  • You'd change that in the second part - `.map { |h| "#{h['host']}:#{h['port']}" }` would now return an array of host:port strings. – Dominic Cleal Nov 03 '16 at 08:01
  • I'm glad, I've edited the answer to show the host:port as requested. Please remember to accept the answer (green tick on the left) if it solves the issue. – Dominic Cleal Nov 03 '16 at 14:23