Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Manifests and Resources

Variables and Data Types

Learn Puppet variables and scope, strings and interpolation, numbers, booleans, arrays, hashes, undef, the type system with Optional, Enum and Pattern, and the facts hash.

Puppet has variables and a real type system. Variables are assigned once and never change, which fits a declarative language: a catalog should not depend on the order in which statements happen to run. This lesson covers values, interpolation, scope and data types. The code is Puppet (read-only); runnable stand-ins at the end imitate the interpolation and type-matching rules.

Variables

PUPPET
$app_name = 'shop'
$port     = 8080
$debug    = false
  • Names start with $ and are lowercase letters, digits and underscores.
  • A variable is assigned once per scope. Reassigning is a compile error.
  • Variables must be assigned before use in the same scope (unlike resources, which can appear in any order).
  • With Puppet 8's strict mode, reading an undefined variable is an error rather than silently empty.

Strings and interpolation

Single quotes are literal. Double quotes allow escapes (\n, \t) and interpolation:

PUPPET
$name  = 'web1'
$plain = 'Hello ${name}'          # literal: ${name} stays as text
$msg   = "Hello ${name}"          # Hello web1
$host  = "${facts['networking']['hostname']}.example.test"

Inside ${ } you can use any expression, including function calls and hash access. Write "${var}" with braces to avoid ambiguity. Use single quotes by default; switch to double quotes only when you need interpolation or escapes. For long text use a heredoc:

PUPPET
$banner = @("END")
  Authorized use only.
  Host: ${facts['networking']['fqdn']}
  | END

Numbers, booleans and undef

  • Numbers are integers (8080, 0x1F, 0755 octal) or floats (1.5). Quote modes as strings anyway.
  • Booleans are true and false (no quotes). The string 'false' is truthy, a classic bug.
  • undef means "no value". In a resource, attribute => undef behaves as if you omitted it.
  • Empty string, 0 and empty collections are truthy in Puppet. Only false and undef are falsy.

Arrays and hashes

PUPPET
$packages = ['git', 'curl', 'tree']
$first    = $packages[0]            # 'git'
$last     = $packages[-1]           # 'tree'
$some     = $packages[0, 2]         # ['git', 'curl']

$user = {
  'name'  => 'deploy',
  'uid'   => 2001,
  'shell' => '/bin/bash',
}
$uid = $user['uid']

Arrays are zero-indexed, hashes use =>. Many types accept an array as title: package { $packages: ensure => installed } declares three packages at once. Arrays and hashes can nest, which is how structured data (and facts) look.

Facts as variables

Facter supplies the $facts hash on every node, always available, always read-only:

PUPPET
$os     = $facts['os']['family']          # 'Debian'
$memory = $facts['memory']['system']['total_bytes']
$cores  = $facts['processors']['count']

Prefer $facts['x'] to the old top-scope $::osfamily style. Facts are covered in depth later in this course. Related special hashes: $trusted (from the certificate) and $server_facts (about the server).

Scope

A scope is the area where a variable is visible. Variables defined in a class are local to it; others read them with the qualified name $classname::var. Top scope (outside any class, such as in site.pp) is visible everywhere, written $::var or $var; each node block creates a node scope.

PUPPET
class app {
  $port = 8080
}
class monitor {
  $app_port = $app::port     # requires class app to be evaluated first
}

Reading another class's variable only works once that class has been declared earlier in the same compile, which makes ordering fragile. Prefer passing values as class parameters or reading Hiera (Classes and Parameters).

The type system

Every value has a data type, and you can restrict parameters with them. The common ones:

Type Matches Example
String text 'abc'
Integer[0, 65535] whole numbers in a range 8080
Boolean true / false true
Array[String] array of strings ['a','b']
Hash[String, Integer] hash with typed keys/values {'a' => 1}
Enum['dev','prod'] one of these strings 'prod'
Pattern[/^\d+$/] strings matching a regex '42'
Optional[String] a string or undef undef
Variant[Integer, String] any of several types 5
Stdlib::Port alias from stdlib module 443

Use the match operator =~ to test a value against a type, or the function assert_type:

PUPPET
if $port =~ Integer[1, 65535] {
  notice("${port} is a valid port")
}
assert_type(Integer[1, 65535], $port)   # fails the compile if it does not match

Types are most valuable on class parameters, where they reject bad data at compile time with a clear message instead of deploying a broken config.

A stand-in: interpolation and type matching

Python Stand-in: Puppet-style interpolation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Stand-in: a tiny type matcher

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The string "8080" is rejected for an integer parameter: exactly the kind of mistake types catch.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which string interpolates the variable $name?

    Only double-quoted strings interpolate.
  2. 2. Which values are falsy in Puppet?

    Only false and undef are falsy; 0, empty string and empty array are truthy.
  3. 3. Can you reassign a variable in the same scope?

    Variables are immutable within a scope.
  4. 4. How do you read the OS family fact in modern style?

    $facts is the hash of all facts; nested keys are read with brackets.

Summary

  • Variables start with $, are assigned once and used after assignment.
  • Single quotes are literal, double quotes interpolate; only false and undef are falsy.
  • Arrays are zero-indexed, hashes use =>; $facts holds facts.
  • Scope controls visibility; prefer parameters over reading other classes' variables.
  • Data types (Integer, Enum, Optional...) validate input early.

Next: Conditionals and Operators