5 1. [Module Description - What the module does and why it is useful](#module-description)
6 1. [Setup - The basics of getting started with stdlib](#setup)
7 1. [Usage - Configuration options and additional functionality](#usage)
8 1. [Reference - An under-the-hood peek at what the module is doing and how](#reference)
10 1. [Defined Types](#defined-types)
11 1. [Data Types](#data-types)
13 1. [Functions](#functions)
14 1. [Limitations - OS compatibility, etc.](#limitations)
15 1. [Development - Guide for contributing to the module](#development)
16 1. [Contributors](#contributors)
21 This module provides a standard library of resources for Puppet modules. Puppet modules make heavy use of this standard library. The stdlib module adds the following resources to Puppet:
30 > *Note:* As of version 3.7, Puppet Enterprise no longer includes the stdlib module. If you're running Puppet Enterprise, you should install the most recent release of stdlib for compatibility with Puppet modules.
34 [Install](https://docs.puppet.com/puppet/latest/modules_installing.html) the stdlib module to add the functions, facts, and resources of this standard library to Puppet.
36 If you are authoring a module that depends on stdlib, be sure to [specify dependencies](https://docs.puppet.com/puppet/latest/modules_metadata.html#specifying-dependencies) in your metadata.json.
40 Most of stdlib's features are automatically loaded by Puppet. To use standardized run stages in Puppet, declare this class in your manifest with `include stdlib`.
42 When declared, stdlib declares all other classes in the module. The only other class currently included in the module is `stdlib::stages`.
44 The `stdlib::stages` class declares various run stages for deploying infrastructure, language runtimes, and application layers. The high level stages are (in order):
60 class { java: stage => 'runtime' }
66 * [Public classes](#public-classes)
67 * [Private classes](#private-classes)
68 * [Defined types](#defined-types)
69 * [Data types](#data-types)
71 * [Functions](#functions)
77 The `stdlib` class has no parameters.
81 * `stdlib::stages`: Manages a standard set of run stages for Puppet.
87 Ensures that a given line is contained within a file. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet appends the line to the end of the file to ensure the desired state. Multiple resources can be declared to manage multiple lines in the same file.
92 file_line { 'sudo_rule':
93 path => '/etc/sudoers',
94 line => '%sudo ALL=(ALL) ALL',
97 file_line { 'sudo_rule_nopw':
98 path => '/etc/sudoers',
99 line => '%sudonopw ALL=(ALL) NOPASSWD: ALL',
103 In the example above, Puppet ensures that both of the specified lines are contained in the file `/etc/sudoers`.
108 file_line { 'bashrc_proxy':
110 path => '/etc/bashrc',
111 line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
112 match => '^export\ HTTP_PROXY\=',
116 In the example above, `match` looks for a line beginning with 'export' followed by 'HTTP_PROXY' and replaces it with the value in line.
120 file_line { 'bashrc_proxy':
122 path => '/etc/bashrc',
123 line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
124 match => '^export\ HTTP_PROXY\=',
125 append_on_no_match => false,
128 In this code example, `match` looks for a line beginning with export followed by HTTP_PROXY and replaces it with the value in line. If a match is not found, then no changes are made to the file.
130 Match Example with `ensure => absent`:
133 file_line { 'bashrc_proxy':
135 path => '/etc/bashrc',
136 line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
137 match => '^export\ HTTP_PROXY\=',
138 match_for_absence => true,
142 In the example above, `match` looks for a line beginning with 'export' followed by 'HTTP_PROXY' and deletes it. If multiple lines match, an error is raised, unless the `multiple => true` parameter is set.
147 file_line { "XScreenSaver":
149 path => '/root/XScreenSaver'
150 line => "*lock: 10:00:00",
152 encoding => "iso-8859-1",
156 Files with special characters that are not valid UTF-8 give the error message "Invalid byte sequence in UTF-8". In this case, determine the correct file encoding and specify it with the `encoding` attribute.
158 **Autorequires:** If Puppet is managing the file that contains the line being managed, the `file_line` resource autorequires that file.
162 All parameters are optional, unless otherwise noted.
166 Specifies the line after which Puppet adds any new lines using a regular expression. (Existing lines are added in place.)
168 Values: String containing a regex.
170 Default value: `undef`.
174 Specifies the correct file encoding.
176 Values: String specifying a valid Ruby character encoding.
180 ##### `ensure`: Specifies whether the resource is present.
182 Values: 'present', 'absent'.
184 Default value: 'present'.
190 Sets the line to be added to the file located by the `path` parameter.
196 Specifies a regular expression to compare against existing lines in the file; if a match is found, it is replaced rather than adding a new line. A regex comparison is performed against the line value, and if it does not match, an exception is raised.
198 Values: String containing a regex.
200 Default value: `undef`.
203 ##### `match_for_absence`
205 Specifies whether a match should be applied when `ensure => absent`. If set to `true` and match is set, the line that matches is deleted. If set to `false` (the default), match is ignored when `ensure => absent` and the value of `line` is used instead. Ignored when `ensure => present`.
209 Default value: `false`.
213 Specifies whether `match` and `after` can change multiple lines. If set to `false`, an exception is raised if more than one line matches.
215 Values: `true`, `false`.
217 Default value: `false`.
222 Specifies the name to use as the identity of the resource. If you want the resource namevar to differ from the supplied `title` of the resource, specify it with `name`.
226 Default value: The value of the title.
232 Specifies the file in which Puppet ensures the line specified by `line`.
234 Value: String specifying an absolute path to the file.
238 Specifies whether the resource overwrites an existing line that matches the `match` parameter. If set to `false` and a line is found matching the `match` parameter, the line is not placed in the file.
242 Default value: `true`.
246 #### `Stdlib::Absolutepath`
248 A strict absolute path type. Uses a variant of Unixpath and Windowspath types.
250 Acceptable input examples:
257 /usr2/username/bin:/usr/local/bin:/usr/bin:.
261 C:\\WINDOWS\\System32
264 Unacceptable input example:
270 #### `Stdlib::Httpsurl`
274 Acceptable input example:
280 Unacceptable input example:
283 httds://notquiteright.org`
286 #### `Stdlib::Httpurl`
288 Matches both HTTPS and HTTP URLs.
290 Acceptable input example:
298 Unacceptable input example:
301 httds://notquiteright.org
306 Matches MAC addresses defined in [RFC5342](https://tools.ietf.org/html/rfc5342).
308 #### `Stdlib::Unixpath`
310 Matches paths on Unix operating systems.
312 Acceptable input example:
315 /usr2/username/bin:/usr/local/bin:/usr/bin:
320 Unacceptable input example:
326 #### `Stdlib::Windowspath`
328 Matches paths on Windows operating systems.
330 Acceptable input example:
333 C:\\WINDOWS\\System32
340 Unacceptable input example:
343 /usr2/username/bin:/usr/local/bin:/usr/bin:.
348 #### `package_provider`
350 Returns the default provider Puppet uses to manage packages on this system.
354 Returns whether Puppet Enterprise is installed. Does not report anything on platforms newer than PE 3.x.
358 Returns the version of Puppet Enterprise installed. Does not report anything on platforms newer than PE 3.x.
360 #### `pe_major_version`
362 Returns the major version Puppet Enterprise that is installed. Does not report anything on platforms newer than PE 3.x.
364 #### `pe_minor_version`
366 Returns the minor version of Puppet Enterprise that is installed. Does not report anything on platforms newer than PE 3.x.
368 #### `pe_patch_version`
370 Returns the patch version of Puppet Enterprise that is installed.
374 Returns the value of the Puppet vardir setting for the node running Puppet or Puppet agent.
376 #### `puppet_environmentpath`
378 Returns the value of the Puppet environment path settings for the node running Puppet or Puppet agent.
382 Returns the Puppet agent's `server` value, which is the hostname of the Puppet master with which the agent should communicate.
386 Determines the root home directory.
388 Determines the root home directory, which depends on your operating system. Generally this is '/root'.
390 #### `service_provider`
392 Returns the default provider Puppet uses to manage services on this system
398 Returns the absolute value of a number. For example, '-34.56' becomes '34.56'.
400 Argument: A single argument of either an integer or float value.
406 Converts any object to an array containing that object. Converts empty argument lists are to empty arrays. Hashes are converted to arrays of alternating keys and values. Arrays are not touched.
412 Converts any object to a Boolean:
414 * Strings such as 'Y', 'y', '1', 'T', 't', 'TRUE', 'yes', 'true' return `true`.
415 * Strings such as '0', 'F', 'f', 'N', 'n', 'FALSE', 'no', 'false' return `false`.
416 * Booleans return their original value.
417 * A number (or a string representation of a number) greater than 0 returns `true`, otherwise `false`.
418 * An undef value returns `false`.
419 * Anything else returns `true`.
423 #### `assert_private`
425 Sets the current class or definition as private. Calling the class or defined type from outside the current module fails.
427 For example, `assert_private()` called in class `foo::bar` outputs the following message if class is called from outside module `foo`: `Class foo::bar is private.`
429 To specify the error message you want to use:
432 assert_private("You're not supposed to do that!")
439 Converts a string to and from base64 encoding. Requires an `action` ('encode', 'decode') and either a plain or base64-encoded `string`, and an optional `method` ('default', 'strict', 'urlsafe').
441 For backward compatibility, `method` is set as `default` if not specified.
443 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
448 base64('encode', 'hello')
449 base64('encode', 'hello', 'default')
450 # return: "aGVsbG8=\n"
452 base64('encode', 'hello', 'strict')
455 base64('decode', 'aGVsbG8=')
456 base64('decode', 'aGVsbG8=\n')
457 base64('decode', 'aGVsbG8=', 'default')
458 base64('decode', 'aGVsbG8=\n', 'default')
459 base64('decode', 'aGVsbG8=', 'strict')
462 base64('encode', 'https://puppetlabs.com', 'urlsafe')
463 # return: "aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ=="
465 base64('decode', 'aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ==', 'urlsafe')
466 # return: "https://puppetlabs.com"
473 Returns the `basename` of a path. An optional argument strips the extension. For example:
475 * ('/path/to/a/file.ext') returns 'file.ext'
476 * ('relative/path/file.ext') returns 'file.ext'
477 * ('/path/to/a/file.ext', '.ext') returns 'file'
483 Converts a Boolean to a number. Converts values:
485 * `false`, 'f', '0', 'n', and 'no' to 0.
486 * `true`, 't', '1', 'y', and 'yes' to 1.
488 Argument: a single Boolean or string as an input.
494 Converts a Boolean to a string using optionally supplied arguments. The optional second and third arguments represent what true and false are converted to respectively. If only one argument is given, it is converted from a Boolean to a string containing `true` or `false`.
499 bool2str(true) => `true`
500 bool2str(true, 'yes', 'no') => 'yes'
501 bool2str(false, 't', 'f') => 'f'
510 Converts the case of a string or all strings in an array to CamelCase (mixed case).
512 Arguments: Either an array or string. Returns the same type of argument as it received, but in CamelCase form.
514 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
520 Capitalizes the first character of a string or array of strings and lowercases the remaining characters of each string.
522 Arguments: either a single string or an array as an input. *Type*: rvalue.
524 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
528 Returns the smallest integer greater than or equal to the argument.
530 Arguments: A single numeric value.
536 Removes the record separator from the end of a string or an array of strings; for example, 'hello\n' becomes 'hello'.
538 Arguments: a single string or array.
544 Returns a new string with the last character removed. If the string ends with '\r\n', both characters are removed. Applying `chop` to an empty string returns an empty string. To only remove record separators, use the `chomp` function.
546 Arguments: A string or an array of strings as input.
552 Keeps value within the range [Min, X, Max] by sort based on integer value (parameter order doesn't matter). Strings are converted and compared numerically. Arrays of values are flattened into a list for further handling. For example:
554 * `clamp('24', [575, 187])` returns 187.
555 * `clamp(16, 88, 661)` returns 88.
556 * `clamp([4, 3, '99'])` returns 4.
558 Arguments: strings, arrays, or numerics.
564 Appends the contents of multiple arrays onto the first array given. For example:
566 * `concat(['1','2','3'],'4')` returns ['1','2','3','4'].
567 * `concat(['1','2','3'],'4',['5','6','7'])` returns ['1','2','3','4','5','6','7'].
573 Converts a given integer or base 10 string representing an integer to a specified base, as a string. For example:
575 * `convert_base(5, 2)` results in: '101'
576 * `convert_base('254', '16')` results in: 'fe'
580 If called with only an array, counts the number of elements that are **not** nil or `undef`. If called with a second argument, counts the number of elements in an array that matches the second argument.
586 Recursively merges two or more hashes together and returns the resulting hash.
589 $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
590 $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
591 $merged_hash = deep_merge($hash1, $hash2)
594 The resulting hash is equivalent to:
597 $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }
600 If there is a duplicate key that is a hash, they are recursively merged. If there is a duplicate key that is not a hash, the key in the rightmost hash takes precedence.
604 #### `defined_with_params`
606 Takes a resource reference and an optional hash of attributes. Returns `true` if a resource with the specified attributes has already been added to the catalog. Returns `false` otherwise.
613 if ! defined_with_params(User[dan], {'ensure' => 'present' }) {
614 user { 'dan': ensure => present, }
622 Deletes all instances of a given element from an array, substring from a string, or key from a hash.
626 * `delete(['a','b','c','b'], 'b')` returns ['a','c'].
627 * `delete('abracadabra', 'bra')` returns 'acada'.
628 * `delete({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}.
629 * `delete(['ab', 'b'], 'b')` returns ['ab'].
635 Deletes a determined indexed value from an array.
637 For example: `delete_at(['a','b','c'], 1)` returns ['a','c'].
643 Deletes all instances of a given element from an array or hash that match a provided regular expression. A string is treated as a one-item array.
645 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
650 * `delete_regex(['a','b','c','b'], 'b')` returns ['a','c'].
651 * `delete_regex({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}.
652 * `delete_regex(['abf', 'ab', 'ac'], '^ab.*')` returns ['ac'].
653 * `delete_regex(['ab', 'b'], 'b')` returns ['ab'].
659 Deletes all instances of a given value from a hash.
663 * `delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B')` returns {'a'=>'A','c'=>'C','B'=>'D'}
667 #### `delete_undef_values`
669 Deletes all instances of the `undef` value from an array or hash.
673 * `$hash = delete_undef_values({a=>'A', b=>'', c=>`undef`, d => false})` returns {a => 'A', b => '', d => false}.
679 Prints deprecation warnings and logs a warning once for a given key:
682 deprecation(key, message)
687 * A string specifying the key: To keep the number of messages low during the lifetime of a Puppet process, only one message per key is logged.
688 * A string specifying the message: the text to be logged.
692 **Settings that affect `deprecation`**
694 Other settings in Puppet affect the stdlib `deprecation` function:
696 * [`disable_warnings`](https://docs.puppet.com/puppet/latest/reference/configuration.html#disablewarnings)
697 * [`max_deprecations`](https://docs.puppet.com/puppet/latest/reference/configuration.html#maxdeprecations)
698 * [`strict`](https://docs.puppet.com/puppet/latest/reference/configuration.html#strict):
700 * `error`: Fails immediately with the deprecation message
701 * `off`: Output emits no messages.
702 * `warning`: Logs all warnings. This is the default setting.
704 * The environment variable `STDLIB_LOG_DEPRECATIONS`
706 Specifies whether or not to log deprecation warnings. This is especially useful for automated tests to avoid flooding your logs before you are ready to migrate.
708 This variable is Boolean, with the following effects:
710 * `true`: Functions log a warning.
711 * `false`: No warnings are logged.
712 * No value set: Puppet 4 emits warnings, but Puppet 3 does not.
716 Returns the difference between two arrays. The returned array is a copy of the original array, removing any items that also appear in the second array.
720 * `difference(["a","b","c"],["b","c","d"])` returns ["a"].
726 > DEPRECATED: This function has been replaced with a built-in [`dig`](https://docs.puppet.com/puppet/latest/function.html#dig) function as of Puppet 4.5.0. Use [`dig44()`](#dig44) for backwards compatibility or use the new version.
728 Retrieves a value within multiple layers of hashes and arrays via an array of keys containing a path. The function goes through the structure by each path component and tries to return the value at the end of the path.
730 In addition to the required path argument, the function accepts the default argument. It is returned if the path is not correct, if no value was found, or if any other error has occurred.
743 $value = dig($data, ['a', 'b', 2])
746 # with all possible options
747 $value = dig($data, ['a', 'b', 2], 'not_found')
750 # using the default value
751 $value = dig($data, ['a', 'b', 'c', 'd'], 'not_found')
752 # $value = 'not_found'
755 1. **$data** The data structure we are working with.
756 2. **['a', 'b', 2]** The path array.
757 3. **'not_found'** The default value. It is returned if nothing is found.
759 Default value: `undef`.
765 Retrieves a value within multiple layers of hashes and arrays via an array of keys containing a path. The function goes through the structure by each path component and tries to return the value at the end of the path.
767 In addition to the required path argument, the function accepts the default argument. It is returned if the path is incorrect, if no value was found, or if any other error has occurred.
780 $value = dig44($data, ['a', 'b', 2])
783 # with all possible options
784 $value = dig44($data, ['a', 'b', 2], 'not_found')
787 # using the default value
788 $value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found')
789 # $value = 'not_found'
794 1. **$data** The data structure we are working with.
795 2. **['a', 'b', 2]** The path array.
796 3. **'not_found'** The default value. It will be returned if nothing is found.
797 (optional, defaults to `undef`)
801 Returns the `dirname` of a path. For example, `dirname('/path/to/a/file.ext')` returns '/path/to/a'.
807 Returns the Unix version of the given string. Very useful when using a File resource with a cross-platform template.
812 content => dos2unix(template('my_module/settings.conf.erb')),
816 See also [unix2dos](#unix2dos).
822 Converts the case of a string or of all strings in an array to lowercase.
824 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
830 Returns `true` if the argument is an array or hash that contains no elements, or an empty string. Returns `false` when the argument is a numerical value.
836 Takes an array of IP addresses and encloses the ipv6 addresses with square brackets.
840 #### `ensure_packages`
842 Takes a list of packages in an array or hash and installs them only if they don't already exist. Optionally takes a hash as a second parameter to be passed as the third argument to the `ensure_resource()` or `ensure_resources()` function.
849 ensure_packages(['ksh','openssl'], {'ensure' => 'present'})
855 ensure_packages({'ksh' => { ensure => '20120801-1' } , 'mypackage' => { source => '/tmp/myrpm-1.0.0.x86_64.rpm', provider => "rpm" }}, {'ensure' => 'present'})
858 #### `ensure_resource`
860 Takes a resource type, title, and a hash of attributes that describe the resource(s).
868 This example only creates the resource if it does not already exist:
870 `ensure_resource('user', 'dan', {'ensure' => 'present' })`
872 If the resource already exists, but does not match the specified parameters, this function attempts to recreate the resource, leading to a duplicate resource definition error.
874 An array of resources can also be passed in, and each will be created with the type and parameters specified if it doesn't already exist.
876 `ensure_resource('user', ['dan','alex'], {'ensure' => 'present'})`
880 #### `ensure_resources`
882 Creates resource declarations from a hash, but doesn't conflict with resources that are already declared.
884 Specify a resource type and title and a hash of attributes that describe the resource(s).
892 ensure_resources($user)
895 Pass in a hash of resources. Any listed resources that don't already exist will be created with the type and parameters specified:
897 ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'})
911 ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'})
916 Return the value of a given fact. Supports the use of dot-notation for referring to structured facts. If a fact requested does not exist, returns Undef.
923 fact('os.architecture')
929 $first_processor = fact('processors.models.0')
930 $second_processor = fact('processors.models.1')
933 Fact containing a "." in the fact name:
936 fact('vmware."VRA.version"')
941 Flattens deeply nested arrays and returns a single flat array as a result.
943 For example, `flatten(['a', ['b', ['c']]])` returns ['a','b','c'].
949 Returns the largest integer less than or equal to the argument.
951 Arguments: A single numeric value.
955 #### `fqdn_rand_string`
957 Generates a random alphanumeric string, combining the `$fqdn` fact and an optional seed for repeatable randomness. Optionally, you can specify a character set for the function (defaults to alphanumeric).
962 fqdn_rand_string(LENGTH, [CHARSET], [SEED])
969 fqdn_rand_string(10, 'ABCDEF!@#$%^')
970 fqdn_rand_string(10, '', 'custom seed')
975 * An integer, specifying the length of the resulting string.
976 * Optionally, a string specifying the character set.
977 * Optionally, a string specifying the seed for repeatable randomness.
983 Rotates an array or string a random number of times, combining the `$fqdn` fact and an optional seed for repeatable randomness.
988 fqdn_rotate(VALUE, [SEED])
994 fqdn_rotate(['a', 'b', 'c', 'd'])
996 fqdn_rotate([1, 2, 3], 'custom seed')
1003 Returns a [RFC 4122](https://tools.ietf.org/html/rfc4122) valid version 5 UUID based on an FQDN string under the DNS namespace:
1005 * fqdn_uuid('puppetlabs.com') returns '9c70320f-6815-5fc5-ab0f-debe68bf764c'
1006 * fqdn_uuid('google.com') returns '64ee70a4-8cc1-5d25-abf2-dea6c79a09c8'
1010 #### `get_module_path`
1012 Returns the absolute path of the specified module for the current environment.
1015 $module_path = get_module_path('stdlib')
1022 Returns the value of a resource's parameter.
1024 Arguments: A resource reference and the name of the parameter.
1026 For example, the following returns 'param_value':
1029 define example_resource($param) {
1032 example_resource { "example_resource_instance":
1033 param => "param_value"
1036 getparam(Example_resource["example_resource_instance"], "param")
1043 Looks up a variable in a remote namespace.
1048 $foo = getvar('site::data::foo')
1049 # Equivalent to $foo = $site::data::foo
1052 This is useful if the namespace itself is stored in a string:
1055 $datalocation = 'site::data'
1056 $bar = getvar("${datalocation}::bar")
1057 # Equivalent to $bar = $site::data::bar
1064 Returns an array of strings of paths matching path patterns.
1066 Arguments: A string or an array of strings specifying path patterns.
1069 $confs = glob(['/etc/**/*.conf', '/opt/**/*.conf'])
1076 Searches through an array and returns any elements that match the provided regular expression.
1078 For example, `grep(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['aaa','aaaddd'].
1082 #### `has_interface_with`
1084 Returns a Boolean based on kind and value:
1094 has_interface_with("macaddress", "x:x:x:x:x:x")
1095 has_interface_with("ipaddress", "127.0.0.1") => true
1098 If no kind is given, then the presence of the interface is checked:
1101 has_interface_with("lo") => true
1106 #### `has_ip_address`
1108 Returns `true` if the client has the requested IP address on some interface. This function iterates through the `interfaces` fact and checks the `ipaddress_IFACE` facts, performing a simple string comparison.
1110 Arguments: A string specifying an IP address.
1114 #### `has_ip_network`
1116 Returns `true` if the client has an IP address within the requested network. This function iterates through the `interfaces` fact and checks the `network_IFACE` facts, performing a simple string comparision.
1118 Arguments: A string specifying an IP address.
1124 Determines if a hash has a certain key value.
1129 $my_hash = {'key_one' => 'value_one'}
1130 if has_key($my_hash, 'key_two') {
1131 notice('we will not reach here')
1133 if has_key($my_hash, 'key_one') {
1134 notice('this will be printed')
1142 Converts an array into a hash.
1144 For example, `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}.
1150 Returns an array an intersection of two.
1152 For example, `intersection(["a","b","c"],["b","c","d"])` returns ["b","c"].
1158 Boolean check to determine whether a variable is of a given data type. This is equivalent to the `=~` type checks. This function is available only in Puppet 4, or in Puppet 3 with the "future" parser.
1165 if $foo.is_a(Integer) {
1168 if $bar.is_a(Array) {
1171 if $baz.is_a(String) {
1176 * See the [the Puppet type system](https://docs.puppetlabs.com/latest/type.html#about-resource-types) for more information about types.
1177 * See the [`assert_type()`](https://docs.puppetlabs.com/latest/function.html#asserttype) function for flexible ways to assert the type of a value.
1179 #### `is_absolute_path`
1181 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1183 Returns `true` if the given path is absolute.
1189 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1191 Returns `true` if the variable passed to this function is an array.
1197 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1199 Returns `true` if the variable passed to this function is a Boolean.
1203 #### `is_domain_name`
1205 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1207 Returns `true` if the string passed to this function is a syntactically correct domain name.
1211 #### `is_email_address`
1213 Returns true if the string passed to this function is a valid email address.
1220 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1222 Returns `true` if the variable passed to this function is a float.
1226 #### `is_function_available`
1228 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1230 Accepts a string as an argument and determines whether the Puppet runtime has access to a function by that name. It returns `true` if the function exists, `false` if not.
1236 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1238 Returns `true` if the variable passed to this function is a hash.
1244 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1246 Returns `true` if the variable returned to this string is an integer.
1250 #### `is_ip_address`
1252 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1254 Returns `true` if the string passed to this function is a valid IP address.
1258 #### `is_ipv6_address`
1260 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1262 Returns `true` if the string passed to this function is a valid IPv6 address.
1266 #### `is_ipv4_address`
1268 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1270 Returns `true` if the string passed to this function is a valid IPv4 address.
1274 #### `is_mac_address`
1276 Returns `true` if the string passed to this function is a valid MAC address.
1282 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1284 Returns `true` if the variable passed to this function is a number.
1290 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1292 Returns `true` if the variable passed to this function is a string.
1298 Joins an array into a string using a separator. For example, `join(['a','b','c'], ",")` results in: "a,b,c".
1302 #### `join_keys_to_values`
1304 Joins each key of a hash to that key's corresponding value with a separator, returning the result as strings.
1306 If a value is an array, the key is prefixed to each element. The return value is a flattened array.
1308 For example, `join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ")` results in ["a is 1","b is 2","b is 3"].
1314 Returns the keys of a hash as an array.
1320 Returns the length of a given string, array or hash. Replaces the deprecated `size()` function.
1326 Loads a YAML file containing an array, string, or hash, and returns the data in the corresponding native data type.
1331 $myhash = loadyaml('/etc/puppet/data/myhash.yaml')
1334 The second parameter is returned if the file was not found or could not be parsed.
1339 $myhash = loadyaml('no-file.yaml', {'default'=>'value'})
1346 Loads a JSON file containing an array, string, or hash, and returns the data in the corresponding native data type.
1351 $myhash = loadjson('/etc/puppet/data/myhash.json')
1354 The second parameter is returned if the file was not found or could not be parsed.
1359 $myhash = loadjson('no-file.json', {'default'=>'value'})
1364 #### `load_module_metadata`
1366 Loads the metadata.json of a target module. Can be used to determine module version and authorship for dynamic support of modules.
1369 $metadata = load_module_metadata('archive')
1370 notify { $metadata['author']: }
1373 When a module's metadata file is absent, the catalog compilation fails. To avoid this failure:
1376 $metadata = load_module_metadata('mysql', true)
1377 if empty($metadata) {
1378 notify { "This module does not have a metadata.json file.": }
1386 Strips spaces to the left of a string.
1392 Returns the highest value of all arguments. Requires at least one argument.
1394 Arguments: A numeric or a string representing a number.
1400 This function determines if a variable is a member of an array. The variable can be a string, an array, or a fixnum.
1402 For example, `member(['a','b'], 'b')` and `member(['a','b','c'], ['b','c'])` return `true`, while `member(['a','b'], 'c')` and `member(['a','b','c'], ['c','d'])` return `false`.
1404 *Note*: This function does not support nested arrays. If the first argument contains nested arrays, it will not recurse through them.
1410 Merges two or more hashes together and returns the resulting hash.
1415 $hash1 = {'one' => 1, 'two' => 2}
1416 $hash2 = {'two' => 'dos', 'three' => 'tres'}
1417 $merged_hash = merge($hash1, $hash2)
1418 # The resulting hash is equivalent to:
1419 # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'}
1422 When there is a duplicate key, the key in the rightmost hash takes precedence.
1428 Returns the lowest value of all arguments. Requires at least one argument.
1430 Arguments: A numeric or a string representing a number.
1436 Converts a number or a string representation of a number into a true Boolean. Zero or anything non-numeric becomes `false`. Numbers greater than 0 become `true`.
1442 Converts a string of JSON into the correct Puppet structure (as a hash, array, string, integer, or a combination of such).
1445 * The JSON string to convert, as a first argument.
1446 * Optionally, the result to return if conversion fails, as a second error.
1452 Converts a string of YAML into the correct Puppet structure.
1455 * The YAML string to convert, as a first argument.
1456 * Optionally, the result to return if conversion fails, as a second error.
1462 From a list of values, returns the first value that is not undefined or an empty string. Takes any number of arguments, and raises an error if all values are undefined or empty.
1465 $real_jenkins_version = pick($::jenkins_version, '1.449')
1472 Returns the first value in a list of values. Unlike the `pick()` function, `pick_default()` does not fail if all arguments are empty. This allows it to use an empty value as default.
1478 Applies a prefix to all elements in an array, or to the keys in a hash.
1482 * `prefix(['a','b','c'], 'p')` returns ['pa','pb','pc'].
1483 * `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'pa'=>'b','pb'=>'c','pc'=>'d'}.
1489 Invokes a pry debugging session in the current scope object. Useful for debugging manifest code at specific points during a compilation. Should be used only when running `puppet apply` or running a Puppet master in the foreground. Requires the `pry` gem to be installed in Puppet's rubygems.
1497 In a pry session, useful commands include:
1499 * Run `catalog` to see the contents currently compiling catalog.
1500 * Run `cd catalog` and `ls` to see catalog methods and instance variables.
1501 * Run `@resource_table` to see the current catalog resource table.
1505 Hashes a password using the crypt function. Provides a hash usable on most POSIX systems.
1507 The first argument to this function is the password to hash. If it is `undef` or an empty string, this function returns `undef`.
1509 The second argument to this function is which type of hash to use. It will be converted into the appropriate crypt(3) hash specifier. Valid hash types are:
1511 |Hash type |Specifier|
1512 |---------------------|---------|
1515 |SHA-512 (recommended)|6 |
1517 The third argument to this function is the salt to use.
1519 This function uses the Puppet master's implementation of crypt(3). If your environment contains several different operating systems, ensure that they are compatible before using this function.
1523 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1527 Extrapolates a range as an array when given in the form of '(start, stop)'. For example, `range("0", "9")` returns [0,1,2,3,4,5,6,7,8,9]. Zero-padded strings are converted to integers automatically, so `range("00", "09")` returns [0,1,2,3,4,5,6,7,8,9].
1529 Non-integer strings are accepted:
1531 * `range("a", "c")` returns ["a","b","c"].
1532 * `range("host01", "host10")` returns ["host01", "host02", ..., "host09", "host10"].
1534 You must explicitly include trailing zeros, or the underlying Ruby function fails.
1536 Passing a third argument causes the generated range to step by that interval. For example:
1538 * `range("0", "9", "2")` returns ["0","2","4","6","8"].
1544 Regexp escape a string or array of strings. Requires either a single string or an array as an input.
1550 Searches through an array and rejects all elements that match the provided regular expression.
1552 For example, `reject(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['bbb','ccc'].
1558 Reverses the order of a string or array.
1562 Rounds a number to the nearest integer
1568 Strips spaces to the right of the string.
1574 Takes an integer max value and a string seed value and returns a repeatable random integer smaller than max. Similar to `fqdn_rand`, but does not add node specific data to the seed.
1580 Escapes a string so that it can be safely used in a Bourne shell command line. Note that the resulting string should be used unquoted and is not intended for use in either double or single quotes. This function behaves the same as Ruby's `Shellwords.shellescape()` function; see the [Ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellescape).
1585 shell_escape('foo b"ar') => 'foo\ b\"ar'
1592 Builds a command line string from a given array of strings. Each array item is escaped for Bourne shell. All items are then joined together, with a single space in between. This function behaves the same as Ruby's `Shellwords.shelljoin()` function; see the [Ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shelljoin).
1597 shell_join(['foo bar', 'ba"z']) => 'foo\ bar ba\"z'
1604 Splits a string into an array of tokens. This function behaves the same as Ruby's `Shellwords.shellsplit()` function; see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellsplit).
1609 shell_split('foo\ bar ba\"z') => ['foo bar', 'ba"z']
1616 Randomizes the order of a string or array elements.
1622 Returns the number of elements in a string, an array or a hash. This function will be deprecated in a future release. For Puppet 4, use the `length` function.
1628 Sorts strings and arrays lexically.
1632 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1636 Replaces consecutive repeats (such as 'aaaa') in a string with a single character. Returns a new string.
1642 Converts certain strings to a Boolean. This attempts to convert strings that contain the values '1', 'true', 't', 'y', or 'yes' to `true`. Strings that contain values '0', 'false', 'f', 'n', or 'no', or that are an empty string or undefined are converted to `false`. Any other value causes an error. These checks are case insensitive.
1646 #### `str2saltedsha512`
1648 Converts a string to a salted-SHA512 password hash, used for OS X versions 10.7 or greater. Returns a hex version of a salted-SHA512 password hash, which can be inserted into Puppet manifests as a valid password attribute.
1652 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1656 Returns formatted time.
1658 For example, `strftime("%s")` returns the time since Unix epoch, and `strftime("%Y-%m-%d")` returns the date.
1660 Arguments: A string specifying the time in `strftime` format. See the Ruby [strftime](https://ruby-doc.org/core-2.1.9/Time.html#method-i-strftime) documentation for details.
1664 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1668 * `%a`: The abbreviated weekday name ('Sun')
1669 * `%A`: The full weekday name ('Sunday')
1670 * `%b`: The abbreviated month name ('Jan')
1671 * `%B`: The full month name ('January')
1672 * `%c`: The preferred local date and time representation
1673 * `%C`: Century (20 in 2009)
1674 * `%d`: Day of the month (01..31)
1675 * `%D`: Date (%m/%d/%y)
1676 * `%e`: Day of the month, blank-padded ( 1..31)
1677 * `%F`: Equivalent to %Y-%m-%d (the ISO 8601 date format)
1678 * `%h`: Equivalent to %b
1679 * `%H`: Hour of the day, 24-hour clock (00..23)
1680 * `%I`: Hour of the day, 12-hour clock (01..12)
1681 * `%j`: Day of the year (001..366)
1682 * `%k`: Hour, 24-hour clock, blank-padded ( 0..23)
1683 * `%l`: Hour, 12-hour clock, blank-padded ( 0..12)
1684 * `%L`: Millisecond of the second (000..999)
1685 * `%m`: Month of the year (01..12)
1686 * `%M`: Minute of the hour (00..59)
1687 * `%n`: Newline (\n)
1688 * `%N`: Fractional seconds digits, default is 9 digits (nanosecond)
1689 * `%3N`: Millisecond (3 digits)
1690 * `%6N`: Microsecond (6 digits)
1691 * `%9N`: Nanosecond (9 digits)
1692 * `%p`: Meridian indicator ('AM' or 'PM')
1693 * `%P`: Meridian indicator ('am' or 'pm')
1694 * `%r`: Time, 12-hour (same as %I:%M:%S %p)
1695 * `%R`: Time, 24-hour (%H:%M)
1696 * `%s`: Number of seconds since the Unix epoch, 1970-01-01 00:00:00 UTC.
1697 * `%S`: Second of the minute (00..60)
1698 * `%t`: Tab character ( )
1699 * `%T`: Time, 24-hour (%H:%M:%S)
1700 * `%u`: Day of the week as a decimal, Monday being 1. (1..7)
1701 * `%U`: Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
1702 * `%v`: VMS date (%e-%b-%Y)
1703 * `%V`: Week number of year according to ISO 8601 (01..53)
1704 * `%W`: Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
1705 * `%w`: Day of the week (Sunday is 0, 0..6)
1706 * `%x`: Preferred representation for the date alone, no time
1707 * `%X`: Preferred representation for the time alone, no date
1708 * `%y`: Year without a century (00..99)
1709 * `%Y`: Year with century
1710 * `%z`: Time zone as hour offset from UTC (e.g. +0900)
1711 * `%Z`: Time zone name
1712 * `%%`: Literal '%' character
1716 Removes leading and trailing whitespace from a string or from every string inside an array. For example, `strip(" aaa ")` results in "aaa".
1722 Applies a suffix to all elements in an array or to all keys in a hash.
1726 * `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp'].
1727 * `suffix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'ap'=>'b','bp'=>'c','cp'=>'d'}.
1733 Swaps the existing case of a string. For example, `swapcase("aBcD")` results in "AbCd".
1737 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1741 Returns the current Unix epoch time as an integer.
1743 For example, `time()` returns something like '1311972653'.
1749 Converts the argument into bytes.
1751 For example, "4 kB" becomes "4096".
1753 Arguments: A single string.
1757 #### `try_get_value`
1759 **DEPRECATED:** replaced by `dig()`.
1761 Retrieves a value within multiple layers of hashes and arrays.
1765 * A string containing a path, as the first argument. Provide this argument as a string of hash keys or array indexes starting with zero and separated by the path separator character (default "/"). This function goes through the structure by each path component and tries to return the value at the end of the path.
1767 * A default argument as a second argument. This argument is returned if the path is not correct, if no value was found, or if any other error has occurred.
1768 * The path separator character as a last argument.
1781 $value = try_get_value($data, 'a/b/2')
1784 # with all possible options
1785 $value = try_get_value($data, 'a/b/2', 'not_found', '/')
1788 # using the default value
1789 $value = try_get_value($data, 'a/b/c/d', 'not_found')
1790 # $value = 'not_found'
1792 # using custom separator
1793 $value = try_get_value($data, 'a|b', [], '|')
1794 # $value = ['b1','b2','b3']
1797 1. **$data** The data structure we are working with.
1798 2. **'a/b/2'** The path string.
1799 3. **'not_found'** The default value. It will be returned if nothing is found.
1800 (optional, defaults to *`undef`*)
1801 4. **'/'** The path separator character.
1802 (optional, defaults to *'/'*)
1808 **Deprecated**. This function will be removed in a future release.
1810 Returns a string description of the type of a given value. The type can be a string, array, hash, float, integer, or Boolean. For Puppet 4, use the new type system instead.
1825 This function is provided for backwards compatibility, but the built-in [type() function](https://docs.puppet.com/puppet/latest/reference/function.html#type) provided by Puppet is preferred.
1827 Returns the literal type of a given value. Requires Puppet 4. Useful for comparison of types with `<=` such as in `if type_of($some_value) <= Array[String] { ... }` (which is equivalent to `if $some_value =~ Array[String] { ... }`).
1833 Returns a union of two or more arrays, without duplicates.
1835 For example, `union(["a","b","c"],["b","c","d"])` returns ["a","b","c","d"].
1841 Removes duplicates from strings and arrays.
1843 For example, `unique("aabbcc")` returns 'abc', and `unique(["a","a","b","b","c","c"])` returns ["a","b","c"].
1849 Returns the DOS version of a given string. Useful when using a File resource with a cross-platform template.
1854 file { $config_file:
1856 content => unix2dos(template('my_module/settings.conf.erb')),
1860 See also [dos2unix](#dos2unix).
1864 Converts an object, array, or hash of objects to uppercase. Objects to be converted must respond to upcase.
1866 For example, `upcase('abcd')` returns 'ABCD'.
1870 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1874 URLEncodes a string or array of strings.
1876 Arguments: Either a single string or an array of strings.
1880 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1882 #### `validate_absolute_path`
1884 Validates that a given string represents an absolute path in the filesystem. Works for Windows and Unix style paths.
1886 The following values pass:
1889 $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet'
1890 validate_absolute_path($my_path)
1891 $my_path2 = '/var/lib/puppet'
1892 validate_absolute_path($my_path2)
1893 $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet','C:/Program Files/Puppet Labs/Puppet']
1894 validate_absolute_path($my_path3)
1895 $my_path4 = ['/var/lib/puppet','/usr/share/puppet']
1896 validate_absolute_path($my_path4)
1899 The following values fail, causing compilation to terminate:
1902 validate_absolute_path(true)
1903 validate_absolute_path('../var/lib/puppet')
1904 validate_absolute_path('var/lib/puppet')
1905 validate_absolute_path([ 'var/lib/puppet', '/var/foo' ])
1906 validate_absolute_path([ '/var/lib/puppet', 'var/foo' ])
1907 $undefined = `undef`
1908 validate_absolute_path($undefined)
1913 #### `validate_array`
1915 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1917 Validates that all passed values are array data structures. Terminates catalog compilation if any value fails this check.
1919 The following values pass:
1922 $my_array = [ 'one', 'two' ]
1923 validate_array($my_array)
1926 The following values fail, causing compilation to terminate:
1929 validate_array(true)
1930 validate_array('some_string')
1931 $undefined = `undef`
1932 validate_array($undefined)
1937 #### `validate_augeas`
1939 Validates a string using an Augeas lens.
1943 * The string to test, as the first argument.
1944 * The name of the Augeas lens to use, as the second argument.
1945 * Optionally, a list of paths which should **not** be found in the file, as a third argument.
1946 * Optionally, an error message to raise and show to the user, as a fourth argument.
1948 If Augeas fails to parse the string with the lens, the compilation terminates with a parse error.
1950 The `$file` variable points to the location of the temporary file being tested in the Augeas tree.
1952 For example, to make sure your $passwdcontent never contains user `foo`, include the third argument:
1955 validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo'])
1958 To raise and display an error message, include the fourth argument:
1961 validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas')
1966 #### `validate_bool`
1968 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1970 Validates that all passed values are either `true` or `false`.
1971 Terminates catalog compilation if any value fails this check.
1973 The following values pass:
1978 validate_bool(true, true, false, $iamtrue)
1981 The following values fail, causing compilation to terminate:
1984 $some_array = [ true ]
1985 validate_bool("false")
1986 validate_bool("true")
1987 validate_bool($some_array)
1994 Validates a string with an external command.
1997 * The string to test, as the first argument.
1998 * The path to a test command, as the second argument. This argument takes a % as a placeholder for the file path (if no % placeholder is given, defaults to the end of the command). If the command is launched against a tempfile containing the passed string, or returns a non-null value, compilation will terminate with a parse error.
1999 * Optionally, an error message to raise and show to the user, as a third argument.
2002 # Defaults to end of path
2003 validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content')
2007 # % as file location
2008 validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content')
2013 #### `validate_domain_name`
2015 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2017 Validate that all values passed are syntactically correct domain names. Aborts catalog compilation if any value fails this check.
2019 The following values pass:
2022 $my_domain_name = 'server.domain.tld'
2023 validate_domain_name($my_domain_name)
2024 validate_domain_name('domain.tld', 'puppet.com', $my_domain_name)
2027 The following values fail, causing compilation to abort:
2030 validate_domain_name(1)
2031 validate_domain_name(true)
2032 validate_domain_name('invalid domain')
2033 validate_domain_name('-foo.example.com')
2034 validate_domain_name('www.example.2com')
2039 #### `validate_email_address`
2041 Validate that all values passed are valid email addresses. Fail compilation if any value fails this check.
2043 The following values will pass:
2046 $my_email = "waldo@gmail.com"
2047 validate_email_address($my_email)
2048 validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email)
2051 The following values will fail, causing compilation to abort:
2054 $some_array = [ 'bad_email@/d/efdf.com' ]
2055 validate_email_address($some_array)
2060 #### `validate_hash`
2062 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2064 Validates that all passed values are hash data structures. Terminates catalog compilation if any value fails this check.
2066 The following values will pass:
2069 $my_hash = { 'one' => 'two' }
2070 validate_hash($my_hash)
2073 The following values will fail, causing compilation to terminate:
2077 validate_hash('some_string')
2078 $undefined = `undef`
2079 validate_hash($undefined)
2084 #### `validate_integer`
2086 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2088 Validates an integer or an array of integers. Terminates catalog compilation if any of the checks fail.
2092 * An integer or an array of integers, as the first argument.
2093 * Optionally, a maximum, as the second argument. (All elements of) the first argument must be equal to or less than this maximum.
2094 * Optionally, a minimum, as the third argument. (All elements of) the first argument must be equal to or greater than than this maximum.
2096 This function fails if the first argument is not an integer or array of integers, or if the second or third arguments are not convertable to an integer. However, if (and only if) a minimum is given, the second argument may be an empty string or `undef`, which serves as a placeholder to ensure the minimum check.
2098 The following values pass:
2102 validate_integer(1, 2)
2103 validate_integer(1, 1)
2104 validate_integer(1, 2, 0)
2105 validate_integer(2, 2, 2)
2106 validate_integer(2, '', 0)
2107 validate_integer(2, `undef`, 0)
2109 validate_integer(2, $foo, 0)
2110 validate_integer([1,2,3,4,5], 6)
2111 validate_integer([1,2,3,4,5], 6, 0)
2114 * Plus all of the above, but any combination of values passed as strings ('1' or "1").
2115 * Plus all of the above, but with (correct) combinations of negative integer values.
2117 The following values fail, causing compilation to terminate:
2120 validate_integer(true)
2121 validate_integer(false)
2122 validate_integer(7.0)
2123 validate_integer({ 1 => 2 })
2125 validate_integer($foo)
2126 validate_integer($foobaridontexist)
2128 validate_integer(1, 0)
2129 validate_integer(1, true)
2130 validate_integer(1, '')
2131 validate_integer(1, `undef`)
2132 validate_integer(1, , 0)
2133 validate_integer(1, 2, 3)
2134 validate_integer(1, 3, 2)
2135 validate_integer(1, 3, true)
2138 * Plus all of the above, but any combination of values passed as strings (`false` or "false").
2139 * Plus all of the above, but with incorrect combinations of negative integer values.
2140 * Plus all of the above, but with non-integer items in arrays or maximum / minimum argument.
2144 #### `validate_ip_address`
2146 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2148 Validates that the argument is an IP address, regardless of whether it is an IPv4 or an IPv6 address. It also validates IP address with netmask.
2150 Arguments: A string specifying an IP address.
2152 The following values will pass:
2155 validate_ip_address('0.0.0.0')
2156 validate_ip_address('8.8.8.8')
2157 validate_ip_address('127.0.0.1')
2158 validate_ip_address('194.232.104.150')
2159 validate_ip_address('3ffe:0505:0002::')
2160 validate_ip_address('::1/64')
2161 validate_ip_address('fe80::a00:27ff:fe94:44d6/64')
2162 validate_ip_address('8.8.8.8/32')
2165 The following values will fail, causing compilation to terminate:
2168 validate_ip_address(1)
2169 validate_ip_address(true)
2170 validate_ip_address(0.0.0.256)
2171 validate_ip_address('::1', {})
2172 validate_ip_address('0.0.0.0.0')
2173 validate_ip_address('3.3.3')
2174 validate_ip_address('23.43.9.22/64')
2175 validate_ip_address('260.2.32.43')
2179 #### `validate_legacy`
2181 Validates a value against both a specified type and a deprecated validation function. Silently passes if both pass, errors if only one validation passes, and fails if both validations return false.
2185 * The type to check the value against,
2186 * The full name of the previous validation function,
2187 * The value to be checked,
2188 * An unspecified number of arguments needed for the previous validation function.
2193 validate_legacy("Optional[String]", "validate_re", "Value to be validated", ["."])
2196 This function supports updating modules from Puppet 3-style argument validation (using the stdlib `validate_*` functions) to Puppet 4 data types, without breaking functionality for those depending on Puppet 3-style validation.
2198 > Note: This function is compatible only with Puppet 4.4.0 (PE 2016.1) and later.
2200 ##### For module users
2202 If you are running Puppet 4, the `validate_legacy` function can help you find and resolve deprecated Puppet 3 `validate_*` functions. These functions are deprecated as of stdlib version 4.13 and will be removed in a future version of stdlib.
2204 Puppet 4 allows improved defined type checking using [data types](https://docs.puppet.com/puppet/latest/reference/lang_data.html). Data types avoid some of the problems with Puppet 3's `validate_*` functions, which were sometimes inconsistent. For example, [validate_numeric](#validate_numeric) unintentionally allowed not only numbers, but also arrays of numbers or strings that looked like numbers.
2206 If you run Puppet 4 and use modules with deprecated `validate_*` functions, you might encounter deprecation messages. The `validate_legacy` function makes these differences visible and makes it easier to move to the clearer Puppet 4 syntax.
2208 The deprecation messages you get can vary, depending on the modules and data that you use. These deprecation messages appear by default only in Puppet 4:
2210 * `Notice: Accepting previously invalid value for target type '<type>'`: This message is informational only. You're using values that are allowed by the new type, but would have been invalid by the old validation function.
2211 * `Warning: This method is deprecated, please use the stdlib validate_legacy function`: The module has not yet upgraded to `validate_legacy`. Use the [deprecation](#deprecation) options to silence warnings for now, or submit a fix with the module's developer. See the information [for module developers](#for-module-developers) below for how to fix the issue.
2212 * `Warning: validate_legacy(<function>) expected <type> value, got <actual type>_`: Your code passes a value that was accepted by the Puppet 3-style validation, but will not be accepted by the next version of the module. Most often, you can fix this by removing quotes from numbers or booleans.
2213 * `Error: Evaluation Error: Error while evaluating a Resource Statement, Evaluation Error: Error while evaluating a Function Call, validate_legacy(<function>) expected <type> value, got <actual type>`: Your code passes a value that is not acceptable to either the new or the old style validation.
2215 ##### For module developers
2217 The `validate_legacy` function helps you move from Puppet 3 style validation to Puppet 4 validation without breaking functionality your module's users depend on.
2219 Moving to Puppet 4 type validation allows much better defined type checking using [data types](https://docs.puppet.com/puppet/latest/reference/lang_data.html). Many of Puppet 3's `validate_*` functions have surprising holes in their validation. For example, [validate_numeric](#validate_numeric) allows not only numbers, but also arrays of numbers or strings that look like numbers, without giving you any control over the specifics.
2221 For each parameter of your classes and defined types, choose a new Puppet 4 data type to use. In most cases, the new data type allows a different set of values than the original `validate_*` function. The situation then looks like this:
2223 | | `validate_` pass | `validate_` fail |
2224 | ------------ | ---------------- | ---------------- |
2225 | matches type | pass | pass, notice |
2226 | fails type | pass, deprecated | fail |
2228 The code after the validation still has to handle all possible values for now, but users of your code can change their manifests to pass only values that match the new type.
2230 For each `validate_*` function in stdlib, there is a matching `Stdlib::Compat::*` type that allows the appropriate set of values. See the documentation in the `types/` directory in the stdlib source code for caveats.
2232 For example, given a class that should accept only numbers, like this:
2235 class example($value) {
2236 validate_numeric($value)
2239 the resulting validation code looks like this:
2243 Variant[Stdlib::Compat::Numeric, Numeric] $value
2245 validate_legacy(Numeric, 'validate_numeric', $value)
2248 Here, the type of `$value` is defined as `Variant[Stdlib::Compat::Numeric, Numeric]`, which allows any `Numeric` (the new type), as well as all values previously accepted by `validate_numeric` (through `Stdlib::Compat::Numeric`).
2250 The call to `validate_legacy` takes care of triggering the correct log or fail message for you. It requires the new type, the previous validation function name, and all arguments to that function.
2252 If your module still supported Puppet 3, this is a breaking change. Update your `metadata.json` requirements section to indicate that your module no longer supports Puppet 3, and bump the major version of your module. With this change, all existing tests for your module should still pass. Create additional tests for the new possible values.
2254 As a breaking change, this is also a good time to call [`deprecation`](#deprecation) for any parameters you want to get rid of, or to add additional constraints on your parameters.
2256 After releasing this version, you can release another breaking change release where you remove all compat types and all calls to `validate_legacy`. At that time, you can also go through your code and remove any leftovers dealing with the previously possible values.
2258 Always note such changes in your CHANGELOG and README.
2260 #### `validate_numeric`
2262 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2264 Validates a numeric value, or an array or string of numeric values. Terminates catalog compilation if any of the checks fail.
2268 * A numeric value, or an array or string of numeric values.
2269 * Optionally, a maximum value. (All elements of) the first argument has to be less or equal to this max.
2270 * Optionally, a minimum value. (All elements of) the first argument has to be greater or equal to this min.
2272 This function fails if the first argument is not a numeric (Integer or Float) or an array or string of numerics, or if the second and third arguments are not convertable to a numeric. If, and only if, a minimum is given, the second argument can be an empty string or `undef`, which serves as a placeholder to ensure the minimum check.
2274 For passing and failing usage, see [`validate_integer`](#validate-integer). The same values pass and fail, except that `validate_numeric` also allows floating point values.
2280 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2282 Performs simple validation of a string against one or more regular expressions.
2286 * The string to test, as the first argument. If this argument is not a string, compilation terminates. Use quotes to force stringification.
2287 * A stringified regular expression (without the // delimiters) or an array of regular expressions, as the second argument.
2288 * Optionally, the error message raised and shown to the user, as a third argument.
2290 If none of the regular expressions in the second argument match the string passed in the first argument, compilation terminates with a parse error.
2292 The following strings validate against the regular expressions:
2295 validate_re('one', '^one$')
2296 validate_re('one', [ '^one', '^two' ])
2299 The following string fails to validate, causing compilation to terminate:
2302 validate_re('one', [ '^two', '^three' ])
2305 To set the error message:
2308 validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7')
2311 To force stringification, use quotes:
2314 validate_re("${::operatingsystemmajrelease}", '^[57]$')
2319 #### `validate_slength`
2321 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2323 Validates that a string (or an array of strings) is less than or equal to a specified length
2327 * A string or an array of strings, as a first argument.
2328 * A numeric value for maximum length, as a second argument.
2329 * Optionally, a numeric value for minimum length, as a third argument.
2331 The following values pass:
2334 validate_slength("discombobulate",17)
2335 validate_slength(["discombobulate","moo"],17)
2336 validate_slength(["discombobulate","moo"],17,3)
2339 The following values fail:
2342 validate_slength("discombobulate",1)
2343 validate_slength(["discombobulate","thermometer"],5)
2344 validate_slength(["discombobulate","moo"],17,10)
2349 #### `validate_string`
2351 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2353 Validates that all passed values are string data structures. Aborts catalog compilation if any value fails this check.
2355 The following values pass:
2358 $my_string = "one two"
2359 validate_string($my_string, 'three')
2362 The following values fail, causing compilation to terminate:
2365 validate_string(true)
2366 validate_string([ 'some', 'array' ])
2369 *Note:* validate_string(`undef`) will not fail in this version of the functions API.
2374 if $var == `undef` {
2381 #### `validate_x509_rsa_key_pair`
2383 Validates a PEM-formatted X.509 certificate and private key using OpenSSL.
2384 Verifies that the certificate's signature was created from the supplied key.
2386 Fails catalog compilation if any value fails this check.
2390 * An X.509 certificate as the first argument.
2391 * An RSA private key, as the second argument.
2394 validate_x509_rsa_key_pair($cert, $key)
2401 Returns the values of a given hash.
2403 For example, given `$hash = {'a'=1, 'b'=2, 'c'=3} values($hash)` returns [1,2,3].
2409 Finds values inside an array based on location.
2413 * The array you want to analyze, as the first argument.
2414 * Any combination of the following values, as the second argument:
2415 * A single numeric index
2416 * A range in the form of 'start-stop' (eg. 4-9)
2417 * An array combining the above
2421 * `values_at(['a','b','c'], 2)` returns ['c'].
2422 * `values_at(['a','b','c'], ["0-1"])` returns ['a','b'].
2423 * `values_at(['a','b','c','d','e'], [0, "2-3"])` returns ['a','c','d'].
2429 Takes one element from first array given and merges corresponding elements from second array given. This generates a sequence of n-element arrays, where *n* is one more than the count of arguments. For example, `zip(['1','2','3'],['4','5','6'])` results in ["1", "4"], ["2", "5"], ["3", "6"]. *Type*: rvalue.
2433 As of Puppet Enterprise 3.7, the stdlib module is no longer included in PE. PE users should install the most recent release of stdlib for compatibility with Puppet modules.
2435 ### Version Compatibility
2437 Versions | Puppet 2.6 | Puppet 2.7 | Puppet 3.x | Puppet 4.x |
2438 :---------------|:-----:|:---:|:---:|:----:
2439 **stdlib 2.x** | **yes** | **yes** | no | no
2440 **stdlib 3.x** | no | **yes** | **yes** | no
2441 **stdlib 4.x** | no | **yes** | **yes** | no
2442 **stdlib 4.6+** | no | **yes** | **yes** | **yes**
2443 **stdlib 5.x** | no | no | **yes** | **yes**
2445 **stdlib 5.x**: When released, stdlib 5.x will drop support for Puppet 2.7.x. Please see [this discussion](https://github.com/puppetlabs/puppetlabs-stdlib/pull/176#issuecomment-30251414).
2449 Puppet Labs modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We can’t access the huge number of platforms and myriad hardware, software, and deployment configurations that Puppet is intended to serve. We want to keep it as easy as possible to contribute changes so that our modules work in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. For more information, see our [module contribution guide](https://docs.puppetlabs.com/forge/contributing.html).
2451 To report or research a bug with any part of this module, please go to
2452 [http://tickets.puppetlabs.com/browse/MODULES](http://tickets.puppetlabs.com/browse/MODULES).
2456 The list of contributors can be found at: [https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors](https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors).