Eric Van Bezooijen
Eric Van Bezooijen

Reputation: 619

Hash element reference inside puppet manifest

I'm trying to complete one of the first exercises, which is including the hostname and osname facts in the /etc/motd. I simply cannot get this to work properly. I cannot get an element out of a hash.

I'm using the VM at puppet, and the copy and paste isn't working for me so I'll use screenshots.

enter image description here

So I create my motd.pp:

enter image description here

But after running puppet apply motd.pp, I see this:

enter image description here

I've tried:

$os[name]
$os['name']
${os}[name]
${os}['name']
$facts['os']['name']
$::os['name']
$::os[name]

Pretty much every permutation I could think of and it always ignores the [name] or [os][name] part of the variable.

Upvotes: 1

Views: 2217

Answers (2)

Matthew Schuchard
Matthew Schuchard

Reputation: 28739

There are two ways of doing this. There is the Puppet 4/Facter 3 way which is:

file { '/etc/motd':
  ensure  => file,
  owner   => 'root',
  group   => 'root',
  content => "${facts['networking']['fqdn']} OS name is ${facts['os']['name']}\n",
}

and the Puppet 3/Facter 2 way which is:

file { '/etc/motd':
  ensure  => file,
  owner   => 'root',
  group   => 'root',
  content => "$::fqdn OS name is ${::os['name']}\n",
}

You can also do this with Puppet 4 and Facter 2. It would work with the syntax from the first example but the fact location in the second example.

file { '/etc/motd':
  ensure  => file,
  owner   => 'root',
  group   => 'root',
  content => "${facts['fqdn']} OS name is ${facts['os']['name']}\n",
}

Upvotes: 2

John Bollinger
John Bollinger

Reputation: 180058

To interpolate a value from a hash into a string, you need to enclose the whole expression after the $ inside curly braces. Optionally, you can use the same form for ordinary variable references (and in some case you must do so to avoid the variable's name being misinterpreted):

file { '/etc/motd':
  ensure  => file,
  owner   => 'root',
  group   => 'root',
  content => "${::fqdn} OS name is ${::os['name']}\n",
}

The presence or absence of single quotes around the hash key is immaterial, but I recommend the quoted form as better style.

Without the curly braces, Puppet does not recognize the subscripting operator inside the string as going with the variable, so it interpolates the string value of the whole hash, and appends the subscript as plain text.

Upvotes: 2

Related Questions