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)
18 <a id="module-description"></a>
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.
35 [Install](https://puppet.com/docs/puppet/latest/modules_installing.html) the stdlib module to add the functions, facts, and resources of this standard library to Puppet.
37 If you are authoring a module that depends on stdlib, be sure to [specify dependencies](https://puppet.com/docs/puppet/latest/modules_metadata.html#specifying-dependencies-in-modules) in your metadata.json.
42 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`.
44 When declared, stdlib declares all other classes in the module. The only other class currently included in the module is `stdlib::stages`.
46 The `stdlib::stages` class declares various run stages for deploying infrastructure, language runtimes, and application layers. The high level stages are (in order):
62 class { java: stage => 'runtime' }
66 <a id="reference"></a>
69 * [Public classes](#public-classes)
70 * [Private classes](#private-classes)
71 * [Defined types](#defined-types)
72 * [Data types](#data-types)
74 * [Functions](#functions)
79 <a id="public-classes"></a>
82 The `stdlib` class has no parameters.
84 <a id="private-classes"></a>
87 * `stdlib::stages`: Manages a standard set of run stages for Puppet.
89 <a id="defined-types"></a>
94 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.
99 file_line { 'sudo_rule':
100 path => '/etc/sudoers',
101 line => '%sudo ALL=(ALL) ALL',
104 file_line { 'sudo_rule_nopw':
105 path => '/etc/sudoers',
106 line => '%sudonopw ALL=(ALL) NOPASSWD: ALL',
110 In the example above, Puppet ensures that both of the specified lines are contained in the file `/etc/sudoers`.
115 file_line { 'bashrc_proxy':
117 path => '/etc/bashrc',
118 line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
119 match => '^export\ HTTP_PROXY\=',
123 In the example above, `match` looks for a line beginning with 'export' followed by 'HTTP_PROXY' and replaces it with the value in line.
128 file_line { 'bashrc_proxy':
130 path => '/etc/bashrc',
131 line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
132 match => '^export\ HTTP_PROXY\=',
133 append_on_no_match => false,
137 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.
139 Examples of `ensure => absent`:
141 This type has two behaviors when `ensure => absent` is set.
143 The first is to set `match => ...` and `match_for_absence => true`. Match looks for a line beginning with 'export', followed by 'HTTP_PROXY', and then deletes it. If multiple lines match, an error is raised unless the `multiple => true` parameter is set.
145 The `line => ...` parameter in this example would be accepted but ignored.
150 file_line { 'bashrc_proxy':
152 path => '/etc/bashrc',
153 match => '^export\ HTTP_PROXY\=',
154 match_for_absence => true,
158 The second way of using `ensure => absent` is to specify a `line => ...` and no match. When ensuring lines are absent, the default behavior is to remove all lines matching. This behavior can't be disabled.
163 file_line { 'bashrc_proxy':
165 path => '/etc/bashrc',
166 line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
174 file_line { "XScreenSaver":
176 path => '/root/XScreenSaver'
177 line => "*lock: 10:00:00",
179 encoding => "iso-8859-1",
183 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.
185 **Autorequires:** If Puppet is managing the file that contains the line being managed, the `file_line` resource autorequires that file.
189 All parameters are optional, unless otherwise noted.
193 Specifies the line after which Puppet adds any new lines using a regular expression. (Existing lines are added in place.)
195 Values: String containing a regex.
197 Default value: `undef`.
201 Specifies the correct file encoding.
203 Values: String specifying a valid Ruby character encoding.
209 Specifies whether the resource is present.
211 Values: 'present', 'absent'.
213 Default value: 'present'.
219 Sets the line to be added to the file located by the `path` parameter.
225 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.
227 Values: String containing a regex.
229 Default value: `undef`.
232 ##### `match_for_absence`
234 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`.
238 Default value: `false`.
242 Specifies whether `match` and `after` can change multiple lines. If set to `false`, allows file_line to replace only one line and raises an error if more than one will be replaced. If set to `true`, allows file_line to replace one or more lines.
244 Values: `true`, `false`.
246 Default value: `false`.
251 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`.
255 Default value: The value of the title.
261 Specifies the file in which Puppet ensures the line specified by `line`.
263 Value: String specifying an absolute path to the file.
267 Specifies whether the resource overwrites an existing line that matches the `match` parameter when `line` does not otherwise exist.
269 If set to `false` and a line is found matching the `match` parameter, the line is not placed in the file.
273 Default value: `true`.
275 ##### `replace_all_matches_not_matching_line`
277 Replaces all lines matched by `match` parameter, even if `line` already exists in the file.
279 Default value: `false`.
281 <a id="data-types"></a>
284 #### `Stdlib::Absolutepath`
286 A strict absolute path type. Uses a variant of Unixpath and Windowspath types.
288 Acceptable input examples:
295 /usr2/username/bin:/usr/local/bin:/usr/bin:.
299 C:\\WINDOWS\\System32
302 Unacceptable input example:
308 #### `Stdlib::Ensure::Service`
310 Matches acceptable ensure values for service resources.
312 Acceptable input examples:
319 Unacceptable input example:
326 #### `Stdlib::Httpsurl`
328 Matches HTTPS URLs. It is a case insensitive match.
330 Acceptable input example:
338 Unacceptable input example:
341 httds://notquiteright.org`
344 #### `Stdlib::Httpurl`
346 Matches both HTTPS and HTTP URLs. It is a case insensitive match.
348 Acceptable input example:
358 Unacceptable input example:
361 httds://notquiteright.org
366 Matches MAC addresses defined in [RFC5342](https://tools.ietf.org/html/rfc5342).
368 #### `Stdlib::Unixpath`
370 Matches absolute paths on Unix operating systems.
372 Acceptable input example:
375 /usr2/username/bin:/usr/local/bin:/usr/bin:
380 Unacceptable input example:
390 #### `Stdlib::Filemode`
392 Matches octal file modes consisting of one to four numbers and symbolic file modes.
394 Acceptable input examples:
408 Unacceptable input examples:
418 #### `Stdlib::Windowspath`
420 Matches paths on Windows operating systems.
422 Acceptable input example:
425 C:\\WINDOWS\\System32
432 Valid values: A windows filepath.
434 #### `Stdlib::Filesource`
436 Matches paths valid values for the source parameter of the Puppet file type.
438 Acceptable input example:
448 Valid values: A filepath.
452 Matches paths on fully qualified domain name.
454 Acceptable input example:
463 Valid values: Domain name of a server.
467 Matches a valid host which could be a valid ipv4, ipv6 or fqdn.
469 Acceptable input example:
479 Valid values: An IP address or domain name.
483 Matches a valid TCP/UDP Port number.
485 Acceptable input examples:
495 Valid values: An Integer.
497 #### `Stdlib::Port::Privileged`
499 Matches a valid TCP/UDP Privileged port i.e. < 1024.
501 Acceptable input examples:
511 Valid values: A number less than 1024.
513 #### `Stdlib::Port::Unprivileged`
515 Matches a valid TCP/UDP Privileged port i.e. >= 1024.
517 Acceptable input examples:
528 Valid values: A number more than or equal to 1024.
530 #### `Stdlib::Base32`
532 Matches paths a valid base32 string.
534 Acceptable input example:
544 Valid values: A base32 string.
546 #### `Stdlib::Base64`
548 Matches paths a valid base64 string.
550 Acceptable input example:
553 asdasdASDSADA342386832/746+=
555 asdasdASDSADA34238683274/6+
557 asdasdASDSADA3423868327/46+==
560 Valid values: A base64 string.
564 This type is no longer available. To make use of this functionality, use [Stdlib::IP::Address::V4](https://github.com/puppetlabs/puppetlabs-stdlib#stdlibipaddressv4).
568 This type is no longer available. To make use of this functionality, use [Stdlib::IP::Address::V6](https://github.com/puppetlabs/puppetlabs-stdlib#stdlibipaddressv6).
570 #### `Stdlib::Ip_address`
572 This type is no longer available. To make use of this functionality, use [Stdlib::IP::Address](https://github.com/puppetlabs/puppetlabs-stdlib#stdlibipaddress)
574 #### `Stdlib::IP::Address`
576 Matches any IP address, including both IPv4 and IPv6 addresses. It will match them either with or without an address prefix as used in CIDR format IPv4 addresses.
581 '127.0.0.1' =~ Stdlib::IP::Address # true
582 '10.1.240.4/24' =~ Stdlib::IP::Address # true
583 '52.10.10.141' =~ Stdlib::IP::Address # true
584 '192.168.1' =~ Stdlib::IP::Address # false
585 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210' =~ Stdlib::IP::Address # true
586 'FF01:0:0:0:0:0:0:101' =~ Stdlib::IP::Address # true
589 #### `Stdlib::IP::Address::V4`
591 Match any string consisting of an IPv4 address in the quad-dotted decimal format, with or without a CIDR prefix. It will not match any abbreviated form (for example, 192.168.1) because these are poorly documented and inconsistently supported.
596 '127.0.0.1' =~ Stdlib::IP::Address::V4 # true
597 '10.1.240.4/24' =~ Stdlib::IP::Address::V4 # true
598 '192.168.1' =~ Stdlib::IP::Address::V4 # false
599 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210' =~ Stdlib::IP::Address::V4 # false
600 '12AB::CD30:192.168.0.1' =~ Stdlib::IP::Address::V4 # false
603 Valid values: An IPv4 address.
605 #### `Stdlib::IP::Address::V6`
607 Match any string consistenting of an IPv6 address in any of the documented formats in RFC 2373, with or without an address prefix.
612 '127.0.0.1' =~ Stdlib::IP::Address::V6 # false
613 '10.1.240.4/24' =~ Stdlib::IP::Address::V6 # false
614 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210' =~ Stdlib::IP::Address::V6 # true
615 'FF01:0:0:0:0:0:0:101' =~ Stdlib::IP::Address::V6 # true
616 'FF01::101' =~ Stdlib::IP::Address::V6 # true
619 Valid values: An IPv6 address.
621 #### `Stdlib::IP::Address::Nosubnet`
623 Match the same things as the `Stdlib::IP::Address` alias, except it will not match an address that includes an address prefix (for example, it will match '192.168.0.6' but not '192.168.0.6/24').
625 Valid values: An IP address with no subnet.
627 #### `Stdlib::IP::Address::V4::CIDR`
629 Match an IPv4 address in the CIDR format. It will only match if the address contains an address prefix (for example, it will match '192.168.0.6/24'
630 but not '192.168.0.6').
632 Valid values: An IPv4 address with a CIDR provided eg: '192.186.8.101/105'. This will match anything inclusive of '192.186.8.101' to '192.168.8.105'.
634 #### `Stdlib::IP::Address::V4::Nosubnet`
636 Match an IPv4 address only if the address does not contain an address prefix (for example, it will match '192.168.0.6' but not '192.168.0.6/24').
638 Valid values: An IPv4 address with no subnet.
640 #### `Stdlib::IP::Address::V6::Full`
642 Match an IPv6 address formatted in the "preferred form" as documented in section 2.2 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt), with or without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt).
644 #### `Stdlib::IP::Address::V6::Alternate`
646 Match an IPv6 address formatted in the "alternative form" allowing for representing the last two 16-bit pieces of the address with a quad-dotted decimal, as documented in section 2.2.1 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will match addresses with or without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt).
648 #### `Stdlib::IP::Address::V6::Compressed`
650 Match an IPv6 address which may contain `::` used to compress zeros as documented in section 2.2.2 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will match addresses with or without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt).
652 #### `Stdlib::IP::Address::V6::Nosubnet`
654 Alias to allow `Stdlib::IP::Address::V6::Nosubnet::Full`, `Stdlib::IP::Address::V6::Nosubnet::Alternate` and `Stdlib::IP::Address::V6::Nosubnet::Compressed`.
656 #### `Stdlib::IP::Address::V6::Nosubnet::Full`
658 Match an IPv6 address formatted in the "preferred form" as documented in section 2.2 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will not match addresses with address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt).
660 #### `Stdlib::IP::Address::V6::Nosubnet::Alternate`
662 Match an IPv6 address formatted in the "alternative form" allowing for representing the last two 16-bit pieces of the address with a quad-dotted decimal, as documented in section 2.2.1 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will only match addresses without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt).
664 #### `Stdlib::IP::Address::V6::Nosubnet::Compressed`
666 Match an IPv6 address which may contain `::` used to compress zeros as documented in section 2.2.2 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt). It will only match addresses without an address prefix as documented in section 2.3 of [RFC 2373](https://www.ietf.org/rfc/rfc2373.txt).
668 #### `Stdlib::IP::Address::V6::CIDR`
670 Match an IPv6 address in the CIDR format. It will only match if the address contains an address prefix (for example, it will match 'FF01:0:0:0:0:0:0:101/32', 'FF01::101/60', '::/0',
671 but not 'FF01:0:0:0:0:0:0:101', 'FF01::101', '::').
676 #### `package_provider`
678 Returns the default provider Puppet uses to manage packages on this system.
682 Returns whether Puppet Enterprise is installed. Does not report anything on platforms newer than PE 3.x.
686 Returns the version of Puppet Enterprise installed. Does not report anything on platforms newer than PE 3.x.
688 #### `pe_major_version`
690 Returns the major version Puppet Enterprise that is installed. Does not report anything on platforms newer than PE 3.x.
692 #### `pe_minor_version`
694 Returns the minor version of Puppet Enterprise that is installed. Does not report anything on platforms newer than PE 3.x.
696 #### `pe_patch_version`
698 Returns the patch version of Puppet Enterprise that is installed.
702 Returns the value of the Puppet vardir setting for the node running Puppet or Puppet agent.
704 #### `puppet_environmentpath`
706 Returns the value of the Puppet environment path settings for the node running Puppet or Puppet agent.
710 Returns the Puppet agent's `server` value, which is the hostname of the Puppet master with which the agent should communicate.
714 Determines the root home directory.
716 Determines the root home directory, which depends on your operating system. Generally this is '/root'.
718 #### `service_provider`
720 Returns the default provider Puppet uses to manage services on this system
722 <a id="functions"></a>
727 **Deprecated:** This function has been replaced with a built-in [`abs`](https://puppet.com/docs/puppet/latest/function.html#abs) function as of Puppet 6.0.0.
729 Returns the absolute value of a number. For example, '-34.56' becomes '34.56'.
731 Argument: A single argument of either an integer or float value.
737 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.
739 Since Puppet 5.0.0, you can create new values of almost any datatype using the type system — you can use the built-in [`Array.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-array-and-tuple) function to create a new array:
741 $hsh = {'key' => 42, 'another-key' => 100}
744 Would notice `[['key', 42], ['another-key', 100]]`
746 The array data type also has a special mode to "create an array if not already an array":
748 notice(Array({'key' => 42, 'another-key' => 100}, true))
750 Would notice `[{'key' => 42, 'another-key' => 100}]`, as the `true` flag prevents the hash from being transformed into an array.
756 Converts any object to a Boolean:
758 * Strings such as 'Y', 'y', '1', 'T', 't', 'TRUE', 'yes', 'true' return `true`.
759 * Strings such as '0', 'F', 'f', 'N', 'n', 'FALSE', 'no', 'false' return `false`.
760 * Booleans return their original value.
761 * A number (or a string representation of a number) greater than 0 returns `true`, otherwise `false`.
762 * An undef value returns `false`.
763 * Anything else returns `true`.
765 See the built-in [`Boolean.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-boolean)
769 #### `assert_private`
771 Sets the current class or definition as private. Calling the class or defined type from outside the current module fails.
773 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.`
775 To specify the error message you want to use:
778 assert_private("You're not supposed to do that!")
785 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').
787 For backward compatibility, `method` is set as `default` if not specified.
789 > **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.
791 Since Puppet 4.8.0, the `Binary` data type can be used to produce base 64 encoded strings.
793 See the built-in [`String.new`](https://puppet.com/docs/puppet/latest/function.html#binary-value-to-string) and [`Binary.new`](https://puppet.com/docs/puppet/latest/function.html#creating-a-binary) functions.
795 See the built-in [`binary_file`](https://puppet.com/docs/puppet/latest/function.html#binary_file) function for reading a file with binary (non UTF-8) content.
797 # encode a string as if it was binary
798 $encodestring = String(Binary('thestring', '%s'))
799 # decode a Binary assuming it is an UTF-8 String
800 $decodestring = String(Binary("dGhlc3RyaW5n"), "%s")
805 base64('encode', 'hello')
806 base64('encode', 'hello', 'default')
807 # return: "aGVsbG8=\n"
809 base64('encode', 'hello', 'strict')
812 base64('decode', 'aGVsbG8=')
813 base64('decode', 'aGVsbG8=\n')
814 base64('decode', 'aGVsbG8=', 'default')
815 base64('decode', 'aGVsbG8=\n', 'default')
816 base64('decode', 'aGVsbG8=', 'strict')
819 base64('encode', 'https://puppetlabs.com', 'urlsafe')
820 # return: "aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ=="
822 base64('decode', 'aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ==', 'urlsafe')
823 # return: "https://puppetlabs.com"
830 Returns the `basename` of a path. An optional argument strips the extension. For example:
833 basename('/path/to/a/file.ext') => 'file.ext'
834 basename('relative/path/file.ext') => 'file.ext'
835 basename('/path/to/a/file.ext', '.ext') => 'file'
842 Converts a Boolean to a number. Converts values:
844 * `false`, 'f', '0', 'n', and 'no' to 0.
845 * `true`, 't', '1', 'y', and 'yes' to 1.
847 Argument: a single Boolean or string as an input.
849 Since Puppet 5.0.0, you can create values for almost any data type using the type system — you can use the built-in [`Numeric.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-numeric), [`Integer.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-integer), and [`Float.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-float)
850 functions to convert to numeric values:
852 notice(Integer(false)) # Notices 0
853 notice(Float(true)) # Notices 1.0
859 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`.
864 bool2str(true) => `true`
865 bool2str(true, 'yes', 'no') => 'yes'
866 bool2str(false, 't', 'f') => 'f'
871 Since Puppet 5.0.0, you can create new values for almost any
872 data type using the type system — you can use the built-in
873 [`String.new`](https://puppet.com/docs/puppet/latest/function.html#boolean-to-string)
874 function to convert to String, with many different format options:
876 notice(String(false)) # Notices 'false'
877 notice(String(true)) # Notices 'true'
878 notice(String(false, '%y')) # Notices 'yes'
879 notice(String(true, '%y')) # Notices 'no'
885 **Deprecated:** This function has been replaced with a built-in [`camelcase`](https://puppet.com/docs/puppet/latest/function.html#camelcase) function as of Puppet 6.0.0.
887 Converts the case of a string or all strings in an array to CamelCase (mixed case).
889 Arguments: Either an array or string. Returns the same type of argument as it received, but in CamelCase form.
891 *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.
897 **Deprecated:** This function has been replaced with a built-in [`capitalize`](https://puppet.com/docs/puppet/latest/function.html#capitalize) function as of Puppet 6.0.0.
899 Capitalizes the first character of a string or array of strings and lowercases the remaining characters of each string.
901 Arguments: either a single string or an array as an input. *Type*: rvalue.
903 *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.
907 **Deprecated:** This function has been replaced with a built-in [`ceiling`](https://puppet.com/docs/puppet/latest/function.html#ceiling) function as of Puppet 6.0.0.
909 Returns the smallest integer greater than or equal to the argument.
911 Arguments: A single numeric value.
917 **Deprecated:** This function has been replaced with a built-in [`chomp`](https://puppet.com/docs/puppet/latest/function.html#chomp) function as of Puppet 6.0.0.
919 Removes the record separator from the end of a string or an array of strings; for example, 'hello\n' becomes 'hello'.
921 Arguments: a single string or array.
927 **Deprecated:** This function has been replaced with a built-in [`chop`](https://puppet.com/docs/puppet/latest/function.html#chop) function as of Puppet 6.0.0.
929 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.
931 Arguments: A string or an array of strings as input.
937 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:
939 * `clamp('24', [575, 187])` returns 187.
940 * `clamp(16, 88, 661)` returns 88.
941 * `clamp([4, 3, '99'])` returns 4.
943 Arguments: strings, arrays, or numerics.
945 Since Puppet 6.0.0, you can use built-in functions to get the same result:
947 [$minval, $maxval, $value_to_clamp].sort[1]
953 Appends the contents of multiple arrays onto the first array given. For example:
955 * `concat(['1','2','3'],'4')` returns ['1','2','3','4'].
956 * `concat(['1','2','3'],'4',['5','6','7'])` returns ['1','2','3','4','5','6','7'].
958 Since Puppet 4.0, you can use the `+` operator for concatenation of arrays and merge of hashes, and the `<<` operator for appending:
960 ['1','2','3'] + ['4','5','6'] + ['7','8','9'] # returns ['1','2','3','4','5','6','7','8','9']
961 [1, 2, 3] << 4 # returns [1, 2, 3, 4]
962 [1, 2, 3] << [4, 5] # returns [1, 2, 3, [4, 5]]
968 Converts a given integer or base 10 string representing an integer to a specified base, as a string. For example:
970 * `convert_base(5, 2)` results in: '101'
971 * `convert_base('254', '16')` results in: 'fe'
973 Since Puppet 4.5.0, you can do this with the built-in [`String.new`](https://puppet.com/docs/puppet/latest/function.html#integer-to-string) function, with various formatting options:
975 $binary_repr = String(5, '%b') # results in "101"
976 $hex_repr = String(254, '%x') # results in "fe"
977 $hex_repr = String(254, '%#x') # results in "0xfe"
981 Takes an array as the first argument and an optional second argument.
982 It counts the number of elements in an array that is equal to the second argument.
983 If called with only an array, it counts the number of elements that are not nil/undef/empty-string.
985 > **Note**: Equality is tested with a Ruby method. It is subject to what Ruby considers
986 to be equal. For strings, equality is case sensitive.
988 In Puppet core, counting is done using a combination of the built-in functions
989 [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) (since Puppet 4.0.0) and
990 [`length`](https://puppet.com/docs/puppet/latest/function.html#length) (since Puppet 5.5.0, before that in stdlib).
992 This example shows counting values that are not `undef`:
994 notice([42, "hello", undef].filter |$x| { $x =~ NotUndef }.length)
1002 Recursively merges two or more hashes together and returns the resulting hash.
1005 $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
1006 $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
1007 $merged_hash = deep_merge($hash1, $hash2)
1010 The resulting hash is equivalent to:
1013 $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }
1016 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.
1020 #### `defined_with_params`
1022 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.
1029 if ! defined_with_params(User[dan], {'ensure' => 'present' }) {
1030 user { 'dan': ensure => present, }
1038 Deletes all instances of a given element from an array, substring from a string, or key from a hash.
1042 * `delete(['a','b','c','b'], 'b')` returns ['a','c'].
1043 * `delete('abracadabra', 'bra')` returns 'acada'.
1044 * `delete({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}.
1045 * `delete(['ab', 'b'], 'b')` returns ['ab'].
1047 Since Puppet 4.0.0, the minus (`-`) operator deletes values from arrays and deletes keys from a hash:
1049 ['a', 'b', 'c', 'b'] - 'b'
1050 # would return ['a', 'c']
1052 {'a'=>1,'b'=>2,'c'=>3} - ['b','c'])
1053 # would return {'a' => '1'}
1055 You can perform a global delete from a string with the built-in
1056 [`regsubst`](https://puppet.com/docs/puppet/latest/function.html#regsubst) function.
1058 'abracadabra'.regsubst(/bra/, '', 'G')
1059 # would return 'acada'
1061 In general, the built-in
1062 [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function
1063 can filter out entries from arrays and hashes based on a combination of keys and values.
1069 Deletes a determined indexed value from an array.
1071 For example: `delete_at(['a','b','c'], 1)` returns ['a','c'].
1073 Since Puppet 4, this can be done with the built-in
1074 [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
1076 ['a', 'b', 'c'].filter |$pos, $val | { $pos != 1 } # returns ['a', 'c']
1077 ['a', 'b', 'c', 'd'].filter |$pos, $val | { $pos % 2 != 0 } # returns ['b', 'd']
1079 Or, if you want to delete from the beginning or the end of the array — or from both ends at the same time — use the slice operator `[ ]`:
1081 $array[0, -1] # the same as all the values
1082 $array[2, -1] # all but the first 2 elements
1083 $array[0, -3] # all but the last 2 elements
1084 $array[1, -2] # all but the first and last element
1090 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.
1092 *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.
1096 * `delete_regex(['a','b','c','b'], 'b')` returns ['a','c'].
1097 * `delete_regex({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}.
1098 * `delete_regex(['abf', 'ab', 'ac'], '^ab.*')` returns ['ac'].
1099 * `delete_regex(['ab', 'b'], 'b')` returns ['ab'].
1101 Since Puppet 4.0.0, do the equivalent with the built-in
1102 [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
1104 ["aaa", "aba", "aca"].filter |$val| { $val !~ /b/ }
1105 # Would return: ['aaa', 'aca']
1109 #### `delete_values`
1111 Deletes all instances of a given value from a hash.
1115 * `delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B')` returns {'a'=>'A','c'=>'C','B'=>'D'}
1117 Since Puppet 4.0.0, do the equivalent with the built-in
1118 [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
1120 $array.filter |$val| { $val != 'B' }
1121 $hash.filter |$key, $val| { $val != 'B' }
1125 #### `delete_undef_values`
1127 Deletes all instances of the `undef` value from an array or hash.
1131 * `$hash = delete_undef_values({a=>'A', b=>'', c=>`undef`, d => false})` returns {a => 'A', b => '', d => false}.
1133 Since Puppet 4.0.0, do the equivalent with the built-in
1134 [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
1136 $array.filter |$val| { $val =~ NotUndef }
1137 $hash.filter |$key, $val| { $val =~ NotUndef }
1143 Prints deprecation warnings and logs a warning once for a given key:
1146 deprecation(key, message)
1151 * 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.
1152 * A string specifying the message: the text to be logged.
1156 **Settings that affect `deprecation`**
1158 Other settings in Puppet affect the stdlib `deprecation` function:
1160 * [`disable_warnings`](https://puppet.com/docs/puppet/latest/configuration.html#disablewarnings)
1161 * [`max_deprecations`](https://puppet.com/docs/puppet/latest/configuration.html#maxdeprecations)
1162 * [`strict`](https://puppet.com/docs/puppet/latest/configuration.html#strict):
1164 * `error`: Fails immediately with the deprecation message
1165 * `off`: Output emits no messages.
1166 * `warning`: Logs all warnings. This is the default setting.
1168 * The environment variable `STDLIB_LOG_DEPRECATIONS`
1170 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.
1172 This variable is Boolean, with the following effects:
1174 * `true`: Functions log a warning.
1175 * `false`: No warnings are logged.
1176 * No value set: Puppet 4 emits warnings, but Puppet 3 does not.
1180 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.
1184 * `difference(["a","b","c"],["b","c","d"])` returns ["a"].
1186 Since Puppet 4, the minus (`-`) operator in the Puppet language does the same:
1188 ['a', 'b', 'c'] - ['b', 'c', 'd']
1189 # would return ['a']
1195 **Deprecated:** This function has been replaced with a built-in [`dig`](https://puppet.com/docs/puppet/latest/function.html#dig) function as of Puppet 4.5.0. Use [`dig44()`](#dig44) for backwards compatibility or use the new version.
1197 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.
1199 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.
1212 $value = dig($data, ['a', 'b', 2])
1215 # with all possible options
1216 $value = dig($data, ['a', 'b', 2], 'not_found')
1219 # using the default value
1220 $value = dig($data, ['a', 'b', 'c', 'd'], 'not_found')
1221 # $value = 'not_found'
1224 1. **$data** The data structure we are working with.
1225 2. **['a', 'b', 2]** The path array.
1226 3. **'not_found'** The default value. It is returned if nothing is found.
1228 Default value: `undef`.
1234 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.
1236 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.
1249 $value = dig44($data, ['a', 'b', 2])
1252 # with all possible options
1253 $value = dig44($data, ['a', 'b', 2], 'not_found')
1256 # using the default value
1257 $value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found')
1258 # $value = 'not_found'
1263 1. **$data** The data structure we are working with.
1264 2. **['a', 'b', 2]** The path array.
1265 3. **'not_found'** The default value. It will be returned if nothing is found.
1266 (optional, defaults to `undef`)
1270 Returns the `dirname` of a path. For example, `dirname('/path/to/a/file.ext')` returns '/path/to/a'.
1276 Returns the Unix version of the given string. Very useful when using a File resource with a cross-platform template.
1279 file { $config_file:
1281 content => dos2unix(template('my_module/settings.conf.erb')),
1285 See also [unix2dos](#unix2dos).
1291 **Deprecated:** This function has been replaced with a built-in [`downcase`](https://puppet.com/docs/puppet/latest/function.html#downcase) function as of Puppet 6.0.0.
1293 Converts the case of a string or of all strings in an array to lowercase.
1295 *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.
1301 **Deprecated:** This function has been replaced with a built-in [`empty`](https://puppet.com/docs/puppet/latest/function.html#empty) function as of Puppet 5.5.0.
1303 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.
1309 Takes an array of IP addresses and encloses the ipv6 addresses with square brackets.
1313 #### `ensure_packages`
1315 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.
1322 ensure_packages(['ksh','openssl'], {'ensure' => 'present'})
1328 ensure_packages({'ksh' => { ensure => '20120801-1' } , 'mypackage' => { source => '/tmp/myrpm-1.0.0.x86_64.rpm', provider => "rpm" }}, {'ensure' => 'present'})
1331 #### `ensure_resource`
1333 Takes a resource type, title, and a hash of attributes that describe the resource(s).
1341 This example only creates the resource if it does not already exist:
1343 `ensure_resource('user', 'dan', {'ensure' => 'present' })`
1345 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.
1347 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.
1349 `ensure_resource('user', ['dan','alex'], {'ensure' => 'present'})`
1353 #### `ensure_resources`
1355 Creates resource declarations from a hash, but doesn't conflict with resources that are already declared.
1357 Specify a resource type and title and a hash of attributes that describe the resource(s).
1365 ensure_resources($user)
1368 Pass in a hash of resources. Any listed resources that don't already exist will be created with the type and parameters specified:
1370 ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'})
1384 ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'})
1387 #### `stdlib::extname`
1389 Returns the Extension (the Portion of Filename in Path starting from the last Period).
1394 stdlib::extname('test.rb') => '.rb'
1395 stdlib::extname('a/b/d/test.rb') => '.rb'
1396 stdlib::extname('test') => ''
1397 stdlib::extname('.profile') => ''
1404 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.
1411 fact('os.architecture')
1417 $first_processor = fact('processors.models.0')
1418 $second_processor = fact('processors.models.1')
1421 Fact containing a "." in the fact name:
1424 fact('vmware."VRA.version"')
1429 **Deprecated:** This function has been replaced with a built-in [`flatten`](https://puppet.com/docs/puppet/latest/function.html#flatten) function as of Puppet 5.5.0.
1431 Flattens deeply nested arrays and returns a single flat array as a result.
1433 For example, `flatten(['a', ['b', ['c']]])` returns ['a','b','c'].
1439 **Deprecated:** This function has been replaced with a built-in [`floor`](https://puppet.com/docs/puppet/latest/function.html#floor) function as of Puppet 6.0.0.
1441 Returns the largest integer less than or equal to the argument.
1443 Arguments: A single numeric value.
1447 #### `fqdn_rand_string`
1449 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).
1454 fqdn_rand_string(LENGTH, [CHARSET], [SEED])
1460 fqdn_rand_string(10)
1461 fqdn_rand_string(10, 'ABCDEF!@#$%^')
1462 fqdn_rand_string(10, '', 'custom seed')
1467 * An integer, specifying the length of the resulting string.
1468 * Optionally, a string specifying the character set.
1469 * Optionally, a string specifying the seed for repeatable randomness.
1475 Rotates an array or string a random number of times, combining the `$fqdn` fact and an optional seed for repeatable randomness.
1480 fqdn_rotate(VALUE, [SEED])
1486 fqdn_rotate(['a', 'b', 'c', 'd'])
1488 fqdn_rotate([1, 2, 3], 'custom seed')
1495 Returns a [RFC 4122](https://tools.ietf.org/html/rfc4122) valid version 5 UUID based on an FQDN string under the DNS namespace:
1497 * fqdn_uuid('puppetlabs.com') returns '9c70320f-6815-5fc5-ab0f-debe68bf764c'
1498 * fqdn_uuid('google.com') returns '64ee70a4-8cc1-5d25-abf2-dea6c79a09c8'
1502 #### `get_module_path`
1504 Returns the absolute path of the specified module for the current environment.
1507 $module_path = get_module_path('stdlib')
1510 Since Puppet 5.4.0, the built-in [`module_directory`](https://puppet.com/docs/puppet/latest/function.html#module_directory) function does the same thing and will return the path to the first module found, if given multiple values or an array.
1515 Returns the value of a resource's parameter.
1517 Arguments: A resource reference and the name of the parameter.
1519 > Note: User defined resource types are evaluated lazily.
1524 # define a resource type with a parameter
1525 define example_resource($param) {
1528 # declare an instance of that type
1529 example_resource { "example_resource_instance":
1530 param => "'the value we are getting in this example''"
1533 # Because of order of evaluation, a second definition is needed
1534 # that will be evaluated after the first resource has been declared
1536 define example_get_param {
1537 # This will notice the value of the parameter
1538 notice(getparam(Example_resource["example_resource_instance"], "param"))
1541 # Declare an instance of the second resource type - this will call notice
1542 example_get_param { 'show_notify': }
1545 Would notice: 'the value we are getting in this example'
1547 Since Puppet 4.0.0, you can get a parameter value by using its data type
1548 and the [ ] operator. The example below is equivalent to a call to getparam():
1551 Example_resource['example_resource_instance']['param']
1555 **Deprecated:** This function has been replaced with a built-in [`getvar`](https://puppet.com/docs/puppet/latest/function.html#getvar)
1556 function as of Puppet 6.0.0. The new version also supports digging into a structured value.
1558 Looks up a variable in a remote namespace.
1563 $foo = getvar('site::data::foo')
1564 # Equivalent to $foo = $site::data::foo
1567 This is useful if the namespace itself is stored in a string:
1570 $datalocation = 'site::data'
1571 $bar = getvar("${datalocation}::bar")
1572 # Equivalent to $bar = $site::data::bar
1579 Returns an array of strings of paths matching path patterns.
1581 Arguments: A string or an array of strings specifying path patterns.
1584 $confs = glob(['/etc/**/*.conf', '/opt/**/*.conf'])
1591 Searches through an array and returns any elements that match the provided regular expression.
1593 For example, `grep(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['aaa','aaaddd'].
1595 Since Puppet 4.0.0, the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function does the "same" — as any logic can be used to filter, as opposed to just regular expressions:
1597 ['aaa', 'bbb', 'ccc', 'aaaddd']. filter |$x| { $x =~ 'aaa' }
1601 #### `has_interface_with`
1603 Returns a Boolean based on kind and value:
1613 has_interface_with("macaddress", "x:x:x:x:x:x")
1614 has_interface_with("ipaddress", "127.0.0.1") => true
1617 If no kind is given, then the presence of the interface is checked:
1620 has_interface_with("lo") => true
1625 #### `has_ip_address`
1627 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.
1629 Arguments: A string specifying an IP address.
1633 #### `has_ip_network`
1635 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.
1637 Arguments: A string specifying an IP address.
1642 **Deprecated:** This function has been replaced with the built-in operator `in`.
1644 Determines if a hash has a certain key value.
1649 $my_hash = {'key_one' => 'value_one'}
1650 if has_key($my_hash, 'key_two') {
1651 notice('we will not reach here')
1653 if has_key($my_hash, 'key_one') {
1654 notice('this will be printed')
1658 Since Puppet 4.0.0, this can be achieved in the Puppet language with the following equivalent expression:
1660 $my_hash = {'key_one' => 'value_one'}
1661 if 'key_one' in $my_hash {
1662 notice('this will be printed')
1669 **Deprecated:** This function has been replaced with the built-in ability to create a new value of almost any
1670 data type - see the built-in [`Hash.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-hash-and-struct) function
1673 Converts an array into a hash.
1675 For example (deprecated), `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}.
1677 For example (built-in), `Hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}.
1683 Returns an array an intersection of two.
1685 For example, `intersection(["a","b","c"],["b","c","d"])` returns ["b","c"].
1691 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.
1698 if $foo.is_a(Integer) {
1701 if $bar.is_a(Array) {
1704 if $baz.is_a(String) {
1709 * See the [the Puppet type system](https://puppet.com/docs/puppet/latest/lang_data.html) for more information about types.
1710 * See the [`assert_type()`](https://puppet.com/docs/puppet/latest/function.html#asserttype) function for flexible ways to assert the type of a value.
1712 #### `is_absolute_path`
1714 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1716 Returns `true` if the given path is absolute.
1722 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1724 Returns `true` if the variable passed to this function is an array.
1730 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1732 Returns `true` if the variable passed to this function is a Boolean.
1736 #### `is_domain_name`
1738 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1740 Returns `true` if the string passed to this function is a syntactically correct domain name.
1744 #### `is_email_address`
1746 Returns true if the string passed to this function is a valid email address.
1753 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1755 Returns `true` if the variable passed to this function is a float.
1759 #### `is_function_available`
1761 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1763 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.
1769 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1771 Returns `true` if the variable passed to this function is a hash.
1777 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1779 Returns `true` if the variable returned to this string is an integer.
1783 #### `is_ip_address`
1785 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1787 Returns `true` if the string passed to this function is a valid IP address.
1791 #### `is_ipv6_address`
1793 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1795 Returns `true` if the string passed to this function is a valid IPv6 address.
1799 #### `is_ipv4_address`
1801 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1803 Returns `true` if the string passed to this function is a valid IPv4 address.
1807 #### `is_mac_address`
1809 Returns `true` if the string passed to this function is a valid MAC address.
1815 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1817 Returns `true` if the variable passed to this function is a number.
1823 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
1825 Returns `true` if the variable passed to this function is a string.
1831 **Deprecated:** This function has been replaced with a built-in [`join`](https://puppet.com/docs/puppet/latest/function.html#join) function as of Puppet 5.5.0.
1833 Joins an array into a string using a separator. For example, `join(['a','b','c'], ",")` results in: "a,b,c".
1837 #### `join_keys_to_values`
1839 Joins each key of a hash to that key's corresponding value with a separator, returning the result as strings.
1841 If a value is an array, the key is prefixed to each element. The return value is a flattened array.
1843 For example, `join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ")` results in ["a is 1","b is 2","b is 3"].
1845 Since Puppet 5.0.0, there is more control over the formatting (including indentations and line breaks, delimiters around arrays and hash entries, between key/values in hash entries, and individual
1846 formatting of values in the array) - see the
1847 built-in [`String.new`](https://docs.puppet.com/puppet/latest/function.html#conversion-to-string) function and its formatting options for `Array` and `Hash`.
1853 **Deprecated:** This function has been replaced with a built-in [`keys`](https://puppet.com/docs/puppet/latest/function.html#keys) function as of Puppet 5.5.0.
1855 Returns the keys of a hash as an array.
1861 **Deprecated:** This function has been replaced with a built-in [`length`](https://puppet.com/docs/puppet/latest/function.html#length) function as of Puppet 5.5.0.
1863 Returns the length of a given string, array or hash. Replaces the deprecated `size()` function.
1869 Loads a YAML file containing an array, string, or hash, and returns the data in the corresponding native data type.
1874 $myhash = loadyaml('/etc/puppet/data/myhash.yaml')
1877 The second parameter is returned if the file was not found or could not be parsed.
1882 $myhash = loadyaml('no-file.yaml', {'default'=>'value'})
1889 Loads a JSON file containing an array, string, or hash, and returns the data in the corresponding native data type.
1893 The first parameter can be an absolute file path, or a URL.
1896 $myhash = loadjson('/etc/puppet/data/myhash.json')
1899 The second parameter is returned if the file was not found or could not be parsed.
1904 $myhash = loadjson('no-file.json', {'default'=>'value'})
1909 #### `load_module_metadata`
1911 Loads the metadata.json of a target module. Can be used to determine module version and authorship for dynamic support of modules.
1914 $metadata = load_module_metadata('archive')
1915 notify { $metadata['author']: }
1918 When a module's metadata file is absent, the catalog compilation fails. To avoid this failure, do the following:
1921 $metadata = load_module_metadata('mysql', true)
1922 if empty($metadata) {
1923 notify { "This module does not have a metadata.json file.": }
1931 **Deprecated:** This function has been replaced with a built-in [`lstrip`](https://puppet.com/docs/puppet/latest/function.html#lstrip) function as of Puppet 6.0.0.
1933 Strips spaces to the left of a string.
1939 **Deprecated:** This function has been replaced with a built-in [`max`](https://puppet.com/docs/puppet/latest/function.html#max) function as of Puppet 6.0.0.
1941 Returns the highest value of all arguments. Requires at least one argument.
1943 Arguments: A numeric or a string representing a number.
1949 This function determines if a variable is a member of an array. The variable can be a string, an array, or a fixnum.
1951 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`.
1953 *Note*: This function does not support nested arrays. If the first argument contains nested arrays, it will not recurse through them.
1955 Since Puppet 4.0.0, you can perform the same in the Puppet language. For single values,
1956 use the operator `in`:
1958 'a' in ['a', 'b'] # true
1960 And for arrays, use the operator `-` to compute a diff:
1962 ['d', 'b'] - ['a', 'b', 'c'] == [] # false because 'd' is not subtracted
1963 ['a', 'b'] - ['a', 'b', 'c'] == [] # true because both 'a' and 'b' are subtracted
1965 Also note that since Puppet 5.2.0, the general form to test the content of an array or hash is to use the built-in [`any`](https://puppet.com/docs/puppet/latest/function.html#any) and [`all`](https://puppet.com/docs/puppet/latest/function.html#all) functions.
1971 Merges two or more hashes together and returns the resulting hash.
1976 $hash1 = {'one' => 1, 'two' => 2}
1977 $hash2 = {'two' => 'dos', 'three' => 'tres'}
1978 $merged_hash = merge($hash1, $hash2)
1979 # The resulting hash is equivalent to:
1980 # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'}
1983 When there is a duplicate key, the key in the rightmost hash takes precedence.
1985 Since Puppet 4.0.0, you can use the + operator to achieve the same merge.
1987 $merged_hash = $hash1 + $hash2
1993 **Deprecated:** This function has been replaced with a built-in [`min`](https://puppet.com/docs/puppet/latest/function.html#min) function as of Puppet 6.0.0.
1995 Returns the lowest value of all arguments. Requires at least one argument.
1997 Arguments: A numeric or a string representing a number.
2003 Converts a number, or a string representation of a number, into a true Boolean.
2004 Zero or anything non-numeric becomes `false`.
2005 Numbers greater than zero become `true`.
2007 Since Puppet 5.0.0, the same can be achieved with the Puppet type system.
2008 See the [`Boolean.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-boolean)
2009 function in Puppet for the many available type conversions.
2016 #### `os_version_gte`
2018 Checks to see if the OS version is at least a certain version. Note that only the major version is taken into account.
2022 if os_version_gte('Debian', '9') { }
2023 if os_version_gte('Ubuntu', '18.04') { }
2027 - Boolean(0) # When OS is below the given version.
2028 - Boolean(1) # When OS is equal to or greater than the given version.
2032 Converts a string of JSON into the correct Puppet structure (as a hash, array, string, integer, or a combination of such).
2035 * The JSON string to convert, as a first argument.
2036 * Optionally, the result to return if conversion fails, as a second error.
2042 Converts a string of YAML into the correct Puppet structure.
2045 * The YAML string to convert, as a first argument.
2046 * Optionally, the result to return if conversion fails, as a second error.
2052 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.
2055 $real_jenkins_version = pick($::jenkins_version, '1.449')
2062 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.
2068 Applies a prefix to all elements in an array, or to the keys in a hash.
2072 * `prefix(['a','b','c'], 'p')` returns ['pa','pb','pc'].
2073 * `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'pa'=>'b','pb'=>'c','pc'=>'d'}.
2075 Since Puppet 4.0.0, modify values in array by using the built-in [`map`](https://docs.puppet.com/puppet/latest/function.html#map) function.
2076 This example does the same as the first example above:
2078 ['a', 'b', 'c'].map |$x| { "p${x}" }
2084 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.
2092 In a pry session, useful commands include:
2094 * Run `catalog` to see the contents currently compiling catalog.
2095 * Run `cd catalog` and `ls` to see catalog methods and instance variables.
2096 * Run `@resource_table` to see the current catalog resource table.
2100 Hashes a password using the crypt function. Provides a hash usable on most POSIX systems.
2102 The first argument to this function is the password to hash. If it is `undef` or an empty string, this function returns `undef`.
2104 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:
2106 |Hash type |Specifier|
2107 |---------------------|---------|
2110 |SHA-512 (recommended)|6 |
2112 The third argument to this function is the salt to use.
2114 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.
2118 *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.
2122 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].
2124 Non-integer strings are accepted:
2126 * `range("a", "c")` returns ["a","b","c"].
2127 * `range("host01", "host10")` returns ["host01", "host02", ..., "host09", "host10"].
2129 You must explicitly include trailing zeros, or the underlying Ruby function fails.
2131 Passing a third argument causes the generated range to step by that interval. For example:
2133 * `range("0", "9", "2")` returns ["0","2","4","6","8"].
2135 > Note: The Puppet language supports `Integer` and `Float` ranges by using the type system. They are suitable for iterating a given number of times.
2137 See the built-in [`step`](https://docs.puppet.com/puppet/latest/function.html#step) function in Puppet for skipping values.
2139 Integer[0, 9].each |$x| { notice($x) } # notices 0, 1, 2, ... 9
2145 Regexp escape a string or array of strings. Requires either a single string or an array as an input.
2151 Searches through an array and rejects all elements that match the provided regular expression.
2153 For example, `reject(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['bbb','ccc'].
2155 Since Puppet 4.0.0, the same is true with the built-in [`filter`](https://docs.puppet.com/puppet/latest/function.html#filter) function in Puppet.
2156 The equivalent of the stdlib `reject` function:
2158 ['aaa','bbb','ccc','aaaddd'].filter |$x| { $x !~ /aaa/ }
2164 Reverses the order of a string or array.
2166 > *Note*: The same can be done with the built-in [`reverse_each`](https://docs.puppet.com/puppet/latest/function.html#reverse_each) function in Puppet.
2171 **Deprecated:** This function has been replaced with a built-in [`round`](https://puppet.com/docs/puppet/latest/function.html#round) function as of Puppet 6.0.0.
2173 Rounds a number to the nearest integer.
2179 **Deprecated:** This function has been replaced with a built-in [`rstrip`](https://puppet.com/docs/puppet/latest/function.html#rstrip) function as of Puppet 6.0.0.
2181 Strips spaces to the right of the string.
2187 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.
2191 #### `seeded_rand_string`
2193 Generates a consistent (based on seed value) random string. Useful for generating matching passwords for different hosts.
2197 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).
2202 shell_escape('foo b"ar') => 'foo\ b\"ar'
2209 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).
2214 shell_join(['foo bar', 'ba"z']) => 'foo\ bar ba\"z'
2221 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).
2226 shell_split('foo\ bar ba\"z') => ['foo bar', 'ba"z']
2233 Randomizes the order of a string or array elements.
2239 **Deprecated:** This function has been replaced with a built-in [`size`](https://puppet.com/docs/puppet/latest/function.html#size) function as of Puppet 6.0.0 (`size` is now an alias for `length`).
2241 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.
2247 **Deprecated:** The same functionality can be achieved with the built-in [`sprintf`](https://docs.puppet.com/puppet/latest/function.html#sprintf) function as of Puppet 4.10.10 and 5.3.4. This function will be removed in a future release.
2249 Performs printf-style formatting with named references of text.
2251 The first parameter is a format string describing how to format the rest of the parameters in the hash. See Ruby documentation for [`Kernel::sprintf`](https://ruby-doc.org/core-2.4.2/Kernel.html#method-i-sprintf) for details about this function.
2256 $output = sprintf_hash('String: %<foo>s / number converted to binary: %<number>b',
2257 { 'foo' => 'a string', 'number' => 5 })
2258 # $output = 'String: a string / number converted to binary: 101'
2265 **Deprecated:** This function has been replaced with a built-in [`sort`](https://puppet.com/docs/puppet/latest/function.html#sort) function as of Puppet 6.0.0.
2267 Sorts strings and arrays lexically.
2271 > *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.
2275 Replaces consecutive repeats (such as 'aaaa') in a string with a single character. Returns a new string.
2281 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.
2283 Since Puppet 5.0.0, the same can be achieved with the Puppet type system.
2284 See the [`Boolean.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-boolean)
2285 function in Puppet for the many available type conversions.
2287 Boolean('false'), Boolean('n'), Boolean('no') # all false
2288 Boolean('true'), Boolean('y'), Boolean('yes') # all true
2292 #### `str2saltedsha512`
2294 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.
2298 > *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.
2302 **Deprecated:** This function has been replaced with a built-in [`strftime`](https://puppet.com/docs/puppet/latest/function.html#strftime) function as of Puppet 4.8.0.
2304 Returns formatted time.
2306 For example, `strftime("%s")` returns the time since Unix epoch, and `strftime("%Y-%m-%d")` returns the date.
2308 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.
2312 > *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.
2316 * `%a`: The abbreviated weekday name ('Sun')
2317 * `%A`: The full weekday name ('Sunday')
2318 * `%b`: The abbreviated month name ('Jan')
2319 * `%B`: The full month name ('January')
2320 * `%c`: The preferred local date and time representation
2321 * `%C`: Century (20 in 2009)
2322 * `%d`: Day of the month (01..31)
2323 * `%D`: Date (%m/%d/%y)
2324 * `%e`: Day of the month, blank-padded ( 1..31)
2325 * `%F`: Equivalent to %Y-%m-%d (the ISO 8601 date format)
2326 * `%h`: Equivalent to %b
2327 * `%H`: Hour of the day, 24-hour clock (00..23)
2328 * `%I`: Hour of the day, 12-hour clock (01..12)
2329 * `%j`: Day of the year (001..366)
2330 * `%k`: Hour, 24-hour clock, blank-padded ( 0..23)
2331 * `%l`: Hour, 12-hour clock, blank-padded ( 0..12)
2332 * `%L`: Millisecond of the second (000..999)
2333 * `%m`: Month of the year (01..12)
2334 * `%M`: Minute of the hour (00..59)
2335 * `%n`: Newline (\n)
2336 * `%N`: Fractional seconds digits, default is 9 digits (nanosecond)
2337 * `%3N`: Millisecond (3 digits)
2338 * `%6N`: Microsecond (6 digits)
2339 * `%9N`: Nanosecond (9 digits)
2340 * `%p`: Meridian indicator ('AM' or 'PM')
2341 * `%P`: Meridian indicator ('am' or 'pm')
2342 * `%r`: Time, 12-hour (same as %I:%M:%S %p)
2343 * `%R`: Time, 24-hour (%H:%M)
2344 * `%s`: Number of seconds since the Unix epoch, 1970-01-01 00:00:00 UTC.
2345 * `%S`: Second of the minute (00..60)
2346 * `%t`: Tab character ( )
2347 * `%T`: Time, 24-hour (%H:%M:%S)
2348 * `%u`: Day of the week as a decimal, Monday being 1. (1..7)
2349 * `%U`: Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
2350 * `%v`: VMS date (%e-%b-%Y)
2351 * `%V`: Week number of year according to ISO 8601 (01..53)
2352 * `%W`: Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
2353 * `%w`: Day of the week (Sunday is 0, 0..6)
2354 * `%x`: Preferred representation for the date alone, no time
2355 * `%X`: Preferred representation for the time alone, no date
2356 * `%y`: Year without a century (00..99)
2357 * `%Y`: Year with century
2358 * `%z`: Time zone as hour offset from UTC (for example +0900)
2359 * `%Z`: Time zone name
2360 * `%%`: Literal '%' character
2364 **Deprecated:** This function has been replaced with a built-in [`strip`](https://puppet.com/docs/puppet/latest/function.html#strip) function as of Puppet 6.0.0.
2366 Removes leading and trailing whitespace from a string or from every string inside an array. For example, `strip(" aaa ")` results in "aaa".
2372 Applies a suffix to all elements in an array or to all keys in a hash.
2376 * `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp'].
2377 * `suffix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'ap'=>'b','bp'=>'c','cp'=>'d'}.
2379 Note that since Puppet 4.0.0, you can modify values in an array using the built-in [`map`](https://docs.puppet.com/puppet/latest/function.html#map) function. This example does the same as the first example above:
2381 ['a', 'b', 'c'].map |$x| { "${x}p" }
2387 Swaps the existing case of a string. For example, `swapcase("aBcD")` results in "AbCd".
2391 > *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.
2395 Returns the current Unix epoch time as an integer.
2397 For example, `time()` returns something like '1311972653'.
2399 Since Puppet 4.8.0, the Puppet language has the data types `Timestamp` (a point in time) and `Timespan` (a duration). The following example is equivalent to calling `time()` without any arguments:
2407 Converts the argument into bytes.
2409 For example, "4 kB" becomes "4096".
2411 Arguments: A single string.
2417 Converts input into a JSON String.
2419 For example, `{ "key" => "value" }` becomes `{"key":"value"}`.
2423 #### `to_json_pretty`
2425 Converts input into a pretty JSON String.
2427 For example, `{ "key" => "value" }` becomes `{\n \"key\": \"value\"\n}`.
2433 Converts input into a YAML String.
2435 For example, `{ "key" => "value" }` becomes `"---\nkey: value\n"`.
2439 #### `try_get_value`
2441 **Deprecated:** Replaced by `dig()`.
2443 Retrieves a value within multiple layers of hashes and arrays.
2447 * 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.
2449 * 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.
2450 * The path separator character as a last argument.
2463 $value = try_get_value($data, 'a/b/2')
2466 # with all possible options
2467 $value = try_get_value($data, 'a/b/2', 'not_found', '/')
2470 # using the default value
2471 $value = try_get_value($data, 'a/b/c/d', 'not_found')
2472 # $value = 'not_found'
2474 # using custom separator
2475 $value = try_get_value($data, 'a|b', [], '|')
2476 # $value = ['b1','b2','b3']
2479 1. **$data** The data structure we are working with.
2480 2. **'a/b/2'** The path string.
2481 3. **'not_found'** The default value. It will be returned if nothing is found.
2482 (optional, defaults to *`undef`*)
2483 4. **'/'** The path separator character.
2484 (optional, defaults to *'/'*)
2490 **Deprecated:** This function will be removed in a future release.
2492 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.
2507 This function is provided for backwards compatibility, but the built-in [type() function](https://puppet.com/docs/puppet/latest/function.html#type) provided by Puppet is preferred.
2509 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] { ... }`).
2515 Returns a union of two or more arrays, without duplicates.
2517 For example, `union(["a","b","c"],["b","c","d"])` returns ["a","b","c","d"].
2523 Removes duplicates from strings and arrays.
2525 For example, `unique("aabbcc")` returns 'abc', and `unique(["a","a","b","b","c","c"])` returns ["a","b","c"].
2531 Returns the DOS version of a given string. Useful when using a File resource with a cross-platform template.
2536 file { $config_file:
2538 content => unix2dos(template('my_module/settings.conf.erb')),
2542 See also [dos2unix](#dos2unix).
2546 **Deprecated:** This function has been replaced with a built-in [`upcase`](https://puppet.com/docs/puppet/latest/function.html#upcase) function as of Puppet 6.0.0.
2548 Converts an object, array, or hash of objects to uppercase. Objects to be converted must respond to upcase.
2550 For example, `upcase('abcd')` returns 'ABCD'.
2554 *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.
2558 URLEncodes a string or array of strings.
2560 Arguments: Either a single string or an array of strings.
2564 > *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.
2566 #### `validate_absolute_path`
2568 Validates that a given string represents an absolute path in the filesystem. Works for Windows and Unix style paths.
2570 The following values pass:
2573 $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet'
2574 validate_absolute_path($my_path)
2575 $my_path2 = '/var/lib/puppet'
2576 validate_absolute_path($my_path2)
2577 $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet','C:/Program Files/Puppet Labs/Puppet']
2578 validate_absolute_path($my_path3)
2579 $my_path4 = ['/var/lib/puppet','/usr/share/puppet']
2580 validate_absolute_path($my_path4)
2583 The following values fail, causing compilation to terminate:
2586 validate_absolute_path(true)
2587 validate_absolute_path('../var/lib/puppet')
2588 validate_absolute_path('var/lib/puppet')
2589 validate_absolute_path([ 'var/lib/puppet', '/var/foo' ])
2590 validate_absolute_path([ '/var/lib/puppet', 'var/foo' ])
2591 $undefined = `undef`
2592 validate_absolute_path($undefined)
2597 #### `validate_array`
2599 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
2601 Validates that all passed values are array data structures. Terminates catalog compilation if any value fails this check.
2603 The following values pass:
2606 $my_array = [ 'one', 'two' ]
2607 validate_array($my_array)
2610 The following values fail, causing compilation to terminate:
2613 validate_array(true)
2614 validate_array('some_string')
2615 $undefined = `undef`
2616 validate_array($undefined)
2621 #### `validate_augeas`
2623 Validates a string using an Augeas lens.
2627 * The string to test, as the first argument.
2628 * The name of the Augeas lens to use, as the second argument.
2629 * Optionally, a list of paths which should **not** be found in the file, as a third argument.
2630 * Optionally, an error message to raise and show to the user, as a fourth argument.
2632 If Augeas fails to parse the string with the lens, the compilation terminates with a parse error.
2634 The `$file` variable points to the location of the temporary file being tested in the Augeas tree.
2636 For example, to make sure your $passwdcontent never contains user `foo`, include the third argument:
2639 validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo'])
2642 To raise and display an error message, include the fourth argument:
2645 validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas')
2650 #### `validate_bool`
2652 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
2654 Validates that all passed values are either `true` or `false`.
2655 Terminates catalog compilation if any value fails this check.
2657 The following values pass:
2662 validate_bool(true, true, false, $iamtrue)
2665 The following values fail, causing compilation to terminate:
2668 $some_array = [ true ]
2669 validate_bool("false")
2670 validate_bool("true")
2671 validate_bool($some_array)
2678 Validates a string with an external command.
2681 * The string to test, as the first argument.
2682 * 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.
2683 * Optionally, an error message to raise and show to the user, as a third argument.
2686 # Defaults to end of path
2687 validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content')
2691 # % as file location
2692 validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content')
2697 #### `validate_domain_name`
2699 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
2701 Validate that all values passed are syntactically correct domain names. Aborts catalog compilation if any value fails this check.
2703 The following values pass:
2706 $my_domain_name = 'server.domain.tld'
2707 validate_domain_name($my_domain_name)
2708 validate_domain_name('domain.tld', 'puppet.com', $my_domain_name)
2711 The following values fail, causing compilation to abort:
2714 validate_domain_name(1)
2715 validate_domain_name(true)
2716 validate_domain_name('invalid domain')
2717 validate_domain_name('-foo.example.com')
2718 validate_domain_name('www.example.2com')
2723 #### `validate_email_address`
2725 Validate that all values passed are valid email addresses. Fail compilation if any value fails this check.
2727 The following values will pass:
2730 $my_email = "waldo@gmail.com"
2731 validate_email_address($my_email)
2732 validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email)
2735 The following values will fail, causing compilation to abort:
2738 $some_array = [ 'bad_email@/d/efdf.com' ]
2739 validate_email_address($some_array)
2744 #### `validate_hash`
2746 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
2748 Validates that all passed values are hash data structures. Terminates catalog compilation if any value fails this check.
2750 The following values will pass:
2753 $my_hash = { 'one' => 'two' }
2754 validate_hash($my_hash)
2757 The following values will fail, causing compilation to terminate:
2761 validate_hash('some_string')
2762 $undefined = `undef`
2763 validate_hash($undefined)
2768 #### `validate_integer`
2770 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
2772 Validates an integer or an array of integers. Terminates catalog compilation if any of the checks fail.
2776 * An integer or an array of integers, as the first argument.
2777 * Optionally, a maximum, as the second argument. (All elements of) the first argument must be equal to or less than this maximum.
2778 * Optionally, a minimum, as the third argument. (All elements of) the first argument must be equal to or greater than than this maximum.
2780 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.
2782 The following values pass:
2786 validate_integer(1, 2)
2787 validate_integer(1, 1)
2788 validate_integer(1, 2, 0)
2789 validate_integer(2, 2, 2)
2790 validate_integer(2, '', 0)
2791 validate_integer(2, `undef`, 0)
2793 validate_integer(2, $foo, 0)
2794 validate_integer([1,2,3,4,5], 6)
2795 validate_integer([1,2,3,4,5], 6, 0)
2798 * Plus all of the above, but any combination of values passed as strings ('1' or "1").
2799 * Plus all of the above, but with (correct) combinations of negative integer values.
2801 The following values fail, causing compilation to terminate:
2804 validate_integer(true)
2805 validate_integer(false)
2806 validate_integer(7.0)
2807 validate_integer({ 1 => 2 })
2809 validate_integer($foo)
2810 validate_integer($foobaridontexist)
2812 validate_integer(1, 0)
2813 validate_integer(1, true)
2814 validate_integer(1, '')
2815 validate_integer(1, `undef`)
2816 validate_integer(1, , 0)
2817 validate_integer(1, 2, 3)
2818 validate_integer(1, 3, 2)
2819 validate_integer(1, 3, true)
2822 * Plus all of the above, but any combination of values passed as strings (`false` or "false").
2823 * Plus all of the above, but with incorrect combinations of negative integer values.
2824 * Plus all of the above, but with non-integer items in arrays or maximum / minimum argument.
2828 #### `validate_ip_address`
2830 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
2832 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.
2834 Arguments: A string specifying an IP address.
2836 The following values will pass:
2839 validate_ip_address('0.0.0.0')
2840 validate_ip_address('8.8.8.8')
2841 validate_ip_address('127.0.0.1')
2842 validate_ip_address('194.232.104.150')
2843 validate_ip_address('3ffe:0505:0002::')
2844 validate_ip_address('::1/64')
2845 validate_ip_address('fe80::a00:27ff:fe94:44d6/64')
2846 validate_ip_address('8.8.8.8/32')
2849 The following values will fail, causing compilation to terminate:
2852 validate_ip_address(1)
2853 validate_ip_address(true)
2854 validate_ip_address(0.0.0.256)
2855 validate_ip_address('::1', {})
2856 validate_ip_address('0.0.0.0.0')
2857 validate_ip_address('3.3.3')
2858 validate_ip_address('23.43.9.22/64')
2859 validate_ip_address('260.2.32.43')
2863 #### `validate_legacy`
2865 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.
2869 * The type to check the value against,
2870 * The full name of the previous validation function,
2871 * The value to be checked,
2872 * An unspecified number of arguments needed for the previous validation function.
2877 validate_legacy('Optional[String]', 'validate_re', 'Value to be validated', ["."])
2880 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.
2882 > Note: This function is compatible only with Puppet 4.4.0 (PE 2016.1) and later.
2884 ##### For module users
2886 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.
2888 Puppet 4 allows improved defined type checking using [data types](https://puppet.com/docs/puppet/latest/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.
2890 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.
2892 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:
2894 * `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.
2895 * `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.
2896 * `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.
2897 * `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.
2899 ##### For module developers
2901 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.
2903 Moving to Puppet 4 type validation allows much better defined type checking using [data types](https://puppet.com/docs/puppet/latest/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.
2905 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:
2907 | | `validate_` pass | `validate_` fail |
2908 | ------------ | ---------------- | ---------------- |
2909 | matches type | pass | pass, notice |
2910 | fails type | pass, deprecated | fail |
2912 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.
2914 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.
2916 For example, given a class that should accept only numbers, like this:
2919 class example($value) {
2920 validate_numeric($value)
2923 the resulting validation code looks like this:
2927 Variant[Stdlib::Compat::Numeric, Numeric] $value
2929 validate_legacy(Numeric, 'validate_numeric', $value)
2932 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`).
2934 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.
2936 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.
2938 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.
2940 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.
2942 Always note such changes in your CHANGELOG and README.
2944 #### `validate_numeric`
2946 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
2948 Validates a numeric value, or an array or string of numeric values. Terminates catalog compilation if any of the checks fail.
2952 * A numeric value, or an array or string of numeric values.
2953 * Optionally, a maximum value. (All elements of) the first argument has to be less or equal to this max.
2954 * Optionally, a minimum value. (All elements of) the first argument has to be greater or equal to this min.
2956 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.
2958 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.
2964 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
2966 Performs simple validation of a string against one or more regular expressions.
2970 * The string to test, as the first argument. If this argument is not a string, compilation terminates. Use quotes to force stringification.
2971 * A stringified regular expression (without the // delimiters) or an array of regular expressions, as the second argument.
2972 * Optionally, the error message raised and shown to the user, as a third argument.
2974 If none of the regular expressions in the second argument match the string passed in the first argument, compilation terminates with a parse error.
2976 The following strings validate against the regular expressions:
2979 validate_re('one', '^one$')
2980 validate_re('one', [ '^one', '^two' ])
2983 The following string fails to validate, causing compilation to terminate:
2986 validate_re('one', [ '^two', '^three' ])
2989 To set the error message:
2992 validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7')
2995 To force stringification, use quotes:
2998 validate_re("${::operatingsystemmajrelease}", '^[57]$')
3003 #### `validate_slength`
3005 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
3007 Validates that a string (or an array of strings) is less than or equal to a specified length
3011 * A string or an array of strings, as a first argument.
3012 * A numeric value for maximum length, as a second argument.
3013 * Optionally, a numeric value for minimum length, as a third argument.
3015 The following values pass:
3018 validate_slength("discombobulate",17)
3019 validate_slength(["discombobulate","moo"],17)
3020 validate_slength(["discombobulate","moo"],17,3)
3023 The following values fail:
3026 validate_slength("discombobulate",1)
3027 validate_slength(["discombobulate","thermometer"],5)
3028 validate_slength(["discombobulate","moo"],17,10)
3033 #### `validate_string`
3035 **Deprecated:** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).
3037 Validates that all passed values are string data structures. Aborts catalog compilation if any value fails this check.
3039 The following values pass:
3042 $my_string = "one two"
3043 validate_string($my_string, 'three')
3046 The following values fail, causing compilation to terminate:
3049 validate_string(true)
3050 validate_string([ 'some', 'array' ])
3053 > *Note:* validate_string(`undef`) will not fail in this version of the functions API.
3058 if $var == `undef` {
3065 #### `validate_x509_rsa_key_pair`
3067 Validates a PEM-formatted X.509 certificate and private key using OpenSSL.
3068 Verifies that the certificate's signature was created from the supplied key.
3070 Fails catalog compilation if any value fails this check.
3074 * An X.509 certificate as the first argument.
3075 * An RSA private key, as the second argument.
3078 validate_x509_rsa_key_pair($cert, $key)
3085 **Deprecated:** This function has been replaced with a built-in [`values`](https://puppet.com/docs/puppet/latest/function.html#values) function as of Puppet 5.5.0.
3087 Returns the values of a given hash.
3089 For example, given `$hash = {'a'=1, 'b'=2, 'c'=3} values($hash)` returns [1,2,3].
3095 Finds values inside an array based on location.
3099 * The array you want to analyze, as the first argument.
3100 * Any combination of the following values, as the second argument:
3101 * A single numeric index
3102 * A range in the form of 'start-stop' (eg. 4-9)
3103 * An array combining the above
3107 * `values_at(['a','b','c'], 2)` returns ['c'].
3108 * `values_at(['a','b','c'], ["0-1"])` returns ['a','b'].
3109 * `values_at(['a','b','c','d','e'], [0, "2-3"])` returns ['a','c','d'].
3111 Since Puppet 4.0.0, you can slice an array with index and count directly in the language.
3112 A negative value is taken to be "from the end" of the array, for example:
3115 ['a', 'b', 'c', 'd'][1, 2] # results in ['b', 'c']
3116 ['a', 'b', 'c', 'd'][2, -1] # results in ['c', 'd']
3117 ['a', 'b', 'c', 'd'][1, -2] # results in ['b', 'c']
3124 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.
3126 <a id="limitations"></a>
3129 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.
3131 For an extensive list of supported operating systems, see [metadata.json](https://github.com/puppetlabs/puppetlabs-stdlib/blob/master/metadata.json)
3133 <a id="development"></a>
3136 Puppet 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.puppet.com/forge/contributing.html).
3138 To report or research a bug with any part of this module, please go to
3139 [http://tickets.puppetlabs.com/browse/MODULES](http://tickets.puppetlabs.com/browse/MODULES).
3141 <a id="contributors"></a>
3144 The list of contributors can be found at: [https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors](https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors).