Puppet Variables, Data Types, Facts, Operators and String Functions

Puppet Training Course 24 min min read Updated: Nov 17, 2026 Beginner
Puppet Variables, Data Types, Facts, Operators and String Functions
Beginner Topic 1 of 4

Variables

Variables start with $. They can be assigned only once in a scope, so you cannot change them later. This keeps code predictable.

puppet $package_name = 'nginx' $port = 8080 $enable_ssl = true $packages = ['git', 'curl', 'vim'] $app = { 'name' => 'shop', 'port' => 8080 } notice("Installing ${package_name} on port ${port}") # $port = 9090 # ERROR: cannot reassign a variable in the same scope
RuleDetail
NamesLowercase letters, digits and underscores, starting with a letter or underscore: $web_port
InterpolationOnly in double quotes: "Port is ${port}"
Hash and array access$app['name'], $packages[0], and for nested data $facts['os']['family']
Qualified names$apache::port reads a variable from another class
ConstantsNo special type. By convention just use lower case and do not change

Data Types

TypeExamplesNotes
String'text', "hi ${x}"Single quotes are literal, double quotes interpolate
Integer, Float, Numeric42, 3.14, 0x1FArithmetic works
Booleantrue, falseNo quotes
UndefundefAbsence of a value
Array[1, 2, 3]Zero-based index
Hash{ 'a' => 1 }Key-value, ordered by insertion
Regexp/^web\d+$/For matching
SensitiveSensitive('secret')Hidden in logs and reports
Timestamp, TimespanTimestamp()Dates and durations
puppet $names = ['web1', 'web2', 'db1'] notice($names[0]) # web1 notice($names[-1]) # db1 (last) notice($names.length) # 3 notice($names[0, 2]) # first two items $server = { 'host' => 'web1', 'ports' => [80, 443] } notice($server['ports'][1]) # 443 $server2 = $server + { 'env' => 'prod' } # merge hashes with +

Type Annotations

Puppet has a type system. You can say what kind of value a variable or class parameter must hold. Wrong data is rejected early with a clear error.

puppet Integer $port = 8080 String[1] $name = 'web' # non-empty string Array[String] $users = ['alice'] Hash[String, Integer] $limits = { 'cpu' => 2 } Enum['dev', 'test', 'prod'] $env = 'dev' Optional[String] $comment = undef # a string or undef Variant[Integer, String] $id = 5 Stdlib::Port $listen = 443 # type from the stdlib module Pattern[/^\d+$/] $digits = '123' Boolean $enabled = true

These annotations are most useful on class parameters (next lesson). You can check types yourself:

puppet if $port =~ Integer[1, 65535] { notice('valid port') } notice(type($port)) # Integer[8080, 8080]

Facts: Information About the Node

Facter collects facts before every run. They are available as the $facts hash. Use the hash form, not old top-level variables.

bash facter # all facts facter os # one fact group facter os.family # nested value facter networking.ip facter memory.system.total facter -p # include facts from installed modules (custom facts) facter --jso
puppet otice("OS: ${facts['os']['name']} ${facts['os']['release']['major']}") notice("Family: ${facts['os']['family']}") # Debian, RedHat, windows ... notice("Hostname: ${facts['networking']['hostname']}") notice("Cores: ${facts['processors']['count']}") notice("Memory: ${facts['memory']['system']['total']}") notice("Virtual: ${facts['is_virtual']}")
Common factMeaning
$facts['os']['family']OS family: Debian, RedHat, Suse, windows
$facts['os']['name']Distribution: Ubuntu, Rocky, Windows
$facts['os']['release']['major']Major version number
$facts['networking']['fqdn']Fully qualified domain name
$facts['networking']['ip']Primary IP address
$facts['kernel']Linux, windows
$facts['processors']['count']CPU count
$facts['is_virtual'], $facts['virtual']Running in a VM, and the platform

Trusted Facts

Normal facts are reported by the node, so a compromised or misconfigured node could lie. Trusted facts come from the node's certificate and are verified by the server, so use them for security decisions.

puppet otice($trusted['certname']) # name in the certificate notice($trusted['extensions']) # certificate extension data such as pp_role notice($server_facts['servername']) # facts about the server itself (on a server compile)

Operators

GroupOperators
Arithmetic+ - * / %
Comparison== != < > <= >= (string comparison ignores case)
Booleanand or !
Match=~ (matches), !~ (does not match)
Membershipin (value in array, key in hash, substring in string)
Array and hash+ (join), - (remove), << (append), * (splat)
puppet $cores = $facts['processors']['count'] $workers = $cores * 2 $is_web = $facts['networking']['hostname'] =~ /^web\d+$/ $is_big = $cores >= 8 and $facts['memory']['system']['total_bytes'] > 8589934592 $ok = 'nginx' in ['apache', 'nginx'] # true $captures = 'web12' =~ /^web(\d+)$/ # also sets $1 = '12' in the same block

Useful Built-in Functions

FunctionExampleResult
notice, warning, errnotice('hi')Writes a log line (use for debugging)
failfail('unsupported OS')Stops compilation with an error
length'puppet'.length6
upcase, downcase, capitalize'web'.upcaseWEB
join, split['a','b'].join('-')a-b
regsubstregsubst('web01', '\d+', 'NN')webNN
sprintfsprintf('%05d', 42)00042
mergemerge($h1, $h2)Combined hash
keys, values$h.keysArray of keys
lookuplookup('app::port')Reads data from Hiera
file, template, eppfile('mod/x.txt')Read or render files
sha256, md5sha256('x')Hash value

Functions can be called as function(value) or as a method on a value: $name.upcase. Both are valid. Use the style that reads better.

Scope: Where Variables Are Visible

  • Top scope: variables defined outside classes, reachable everywhere as $::name (rarely used)
  • Node scope: inside a node block
  • Class scope: variables inside a class belong to the class. Other classes read them as $classname::variable
  • Local scope: inside lambdas and defined types
puppet class webapp { $port = 8080 # class variable } class monitor { include webapp $target = "localhost:${webapp::port}" # read another class variable, must include it first }

Sensitive Data

puppet $db_password = Sensitive('S3cr3t!') file { '/etc/app/db.conf': ensure => file, mode => '0600', content => Sensitive("password=${db_password.unwrap}\n"), # unwrap only where truly needed } notice($db_password) # prints: Sensitive [value redacted]

Debugging Tips

  • notice() prints values at compile time (on the server in a server setup)
  • puppet apply -e 'notice(1+2)' is the quickest scratchpad
  • puppet lookup and facter show data used by the code
  • puppet parser validate file.pp checks syntax without running

Practice Tasks

  1. Print five different facts of your lab machine with notice
  2. Create a hash of three web servers with ports and print the port of the second one
  3. Add type annotations to a variable with Enum and Integer[1,65535] and trigger an error with a wrong value
  4. Use regsubst to turn a hostname like web07.example.com into web07
  5. Wrap a password in Sensitive and confirm it is hidden in output

Conclusion

Puppet variables are set once, data has strong types, and the $facts hash describes each node. Use operators and functions to build values, use trusted facts for security, and Sensitive for secrets.

Quick Summary: $var single assignment; types (Integer, String, Hash, Enum...); $facts['os']['family']; $trusted; =~ and in; Sensitive.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators