Accessing Puppet variables
ERB templates can access Puppet variables. This is the main source of data for templates.
An ERB template has its own local scope, and its parent scope is set to the class or defined type that evaluates the template. This means a template can use short names for variables from that class or type, but it can’t insert new variables into it.
There are two ways to access variables in an ERB template:
@variable
scope['variable']
and its older equivalent,scope.lookupvar('variable')
@variable
All variables in the current scope (including global variables) are passed to templates
as Ruby instance variables, which begin with “at” signs
(@
). If you can access a variable by its short name
in the surrounding manifest, you can access it in the template by replacing
its $
sign with an @
, so that $os
becomes @os
, and $trusted
becomes @trusted
.
This is the most legible way to access variables, but it doesn’t support variables from
other scopes. For that, you need to use the scope
object.
scope['variable'] or scope.lookupvar('variable')
Puppet also passes templates an object
called scope
, which can access all variables
(including out-of-scope variables) with a hash-style access expression. For example, to
access $ntp::tinker
you would
use scope['ntp::tinker']
.
Another way to use the scope
object is to call its
lookupvar
method and pass the variable’s name as its
argument, as in scope.lookupvar('ntp::tinker')
. This is
exactly equivalent to the above, if slightly less convenient. This usage predates the
hash-style indexing added in Puppet 3.0.
Puppet data types in Ruby
Puppet's data types are converted to Ruby classes as follows:
Puppet type | Ruby class |
---|---|
Boolean | Boolean |
String | String |
Number | Subtype of Numeric |
Array | Array |
Hash | Hash |
Default | Symbol (value :default ) |
Regexp | Regexp |
Resource reference | Puppet::Pops::Types::PResourceType or
Puppet::Pops::Types::PHostClassType |
Lambda (code block) | Puppet::Pops::Evaluator::Closure |
Data type (type) | A type class under Puppet::Pops::Types , such as Puppet::Pops::Types::PIntegerType |
Undef | NilClass (value nil )If a Puppet variable was never defined, its
value is undef , which means its value
in a template is nil . |