Update stdlib
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / README.md
1 # stdlib
2
3 #### Table of Contents
4
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)
9     1. [Classes](#classes)
10     1. [Defined Types](#defined-types)
11     1. [Data Types](#data-types)
12     1. [Facts](#facts)
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)
17
18
19 ## Module Description
20
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:
22
23  * Stages
24  * Facts
25  * Functions
26  * Defined types
27  * Data types
28  * Providers
29
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.
31
32 ## Setup
33
34 [Install](https://docs.puppet.com/puppet/latest/modules_installing.html) the stdlib module to add the functions, facts, and resources of this standard library to Puppet.
35
36 If you are authoring a module that depends on stdlib, be sure to [specify dependencies](https://docs.puppet.com/puppet/latest/modules_metadata.html#specifying-dependencies) in your metadata.json.
37
38 ## Usage
39
40 Most of stdlib's features are automatically loaded by Puppet. To use standardized run stages in Puppet, declare this class in your manifest with `include stdlib`.
41
42 When declared, stdlib declares all other classes in the module. The only other class currently included in the module is `stdlib::stages`.
43
44 The `stdlib::stages` class declares various run stages for deploying infrastructure, language runtimes, and application layers. The high level stages are (in order):
45
46   * setup
47   * main
48   * runtime
49   * setup_infra
50   * deploy_infra
51   * setup_app
52   * deploy_app
53   * deploy
54
55 Sample usage:
56
57 ```puppet
58 node default {
59   include stdlib
60   class { java: stage => 'runtime' }
61 }
62 ```
63
64 ## Reference
65
66 * [Public classes](#public-classes)
67 * [Private classes](#private-classes)
68 * [Defined types](#defined-types)
69 * [Data types](#data-types)
70 * [Facts](#facts)
71 * [Functions](#functions)
72
73 ### Classes
74
75 #### Public classes
76
77 The `stdlib` class has no parameters.
78
79 #### Private classes
80
81 * `stdlib::stages`: Manages a standard set of run stages for Puppet.
82
83 ### Defined types
84
85 #### `file_line`
86
87 Ensures that a given line is contained within a file. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet appends the line to the end of the file to ensure the desired state. Multiple resources can be declared to manage multiple lines in the same file.
88
89 Example:
90
91 ```puppet
92 file_line { 'sudo_rule':
93   path => '/etc/sudoers',
94   line => '%sudo ALL=(ALL) ALL',
95 }
96
97 file_line { 'sudo_rule_nopw':
98   path => '/etc/sudoers',
99   line => '%sudonopw ALL=(ALL) NOPASSWD: ALL',
100 }
101 ```
102
103 In the example above, Puppet ensures that both of the specified lines are contained in the file `/etc/sudoers`.
104
105 Match Example:
106
107 ```puppet
108 file_line { 'bashrc_proxy':
109   ensure => present,
110   path   => '/etc/bashrc',
111   line   => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
112   match  => '^export\ HTTP_PROXY\=',
113 }
114 ```
115
116 In the example above, `match` looks for a line beginning with 'export' followed by 'HTTP_PROXY' and replaces it with the value in line.
117
118 Match Example:
119
120     file_line { 'bashrc_proxy':
121       ensure             => present,
122       path               => '/etc/bashrc',
123       line               => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
124       match              => '^export\ HTTP_PROXY\=',
125       append_on_no_match => false,
126     }
127
128 In this code example, `match` looks for a line beginning with export followed by HTTP_PROXY and replaces it with the value in line. If a match is not found, then no changes are made to the file.
129
130 Match Example with `ensure => absent`:
131
132 ```puppet
133 file_line { 'bashrc_proxy':
134   ensure            => absent,
135   path              => '/etc/bashrc',
136   line              => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
137   match             => '^export\ HTTP_PROXY\=',
138   match_for_absence => true,
139 }
140 ```
141
142 In the example above, `match` looks for a line beginning with 'export' followed by 'HTTP_PROXY' and deletes it. If multiple lines match, an error is raised, unless the `multiple => true` parameter is set.
143
144 Encoding example:
145
146 ```puppet
147 file_line { "XScreenSaver":
148   ensure   => present,
149   path     => '/root/XScreenSaver'
150   line     => "*lock: 10:00:00",
151   match    => '^*lock:',
152   encoding => "iso-8859-1",
153 }
154 ```
155
156 Files with special characters that are not valid UTF-8 give the error message "Invalid byte sequence in UTF-8". In this case, determine the correct file encoding and specify it with the `encoding` attribute.
157
158 **Autorequires:** If Puppet is managing the file that contains the line being managed, the `file_line` resource autorequires that file.
159
160 **Parameters**
161
162 All parameters are optional, unless otherwise noted.
163
164 ##### `after`
165
166 Specifies the line after which Puppet adds any new lines using a regular expression. (Existing lines are added in place.)
167
168 Values: String containing a regex.
169
170 Default value: `undef`.
171
172 ##### `encoding`
173
174 Specifies the correct file encoding.
175
176 Values: String specifying a valid Ruby character encoding.
177
178 Default: 'UTF-8'.
179
180 ##### `ensure`: Specifies whether the resource is present.
181
182 Values: 'present', 'absent'.
183
184 Default value: 'present'.
185
186 ##### `line`
187
188 **Required.**
189
190 Sets the line to be added to the file located by the `path` parameter.
191
192 Values: String.
193
194 ##### `match`
195
196 Specifies a regular expression to compare against existing lines in the file; if a match is found, it is replaced rather than adding a new line. A regex comparison is performed against the line value, and if it does not match, an exception is raised.
197
198 Values: String containing a regex.
199
200 Default value: `undef`.
201
202
203 ##### `match_for_absence`
204
205 Specifies whether a match should be applied when `ensure => absent`. If set to `true` and match is set, the line that matches is deleted. If set to `false` (the default), match is ignored when `ensure => absent` and the value of `line` is used instead. Ignored when `ensure => present`.
206
207 Boolean.
208
209 Default value: `false`.
210
211 ##### `multiple`
212
213 Specifies whether `match` and `after` can change multiple lines. If set to `false`, an exception is raised if more than one line matches.
214
215 Values: `true`, `false`.
216
217 Default value: `false`.
218
219
220 ##### `name`
221
222 Specifies the name to use as the identity of the resource. If you want the resource namevar to differ from the supplied `title` of the resource, specify it with `name`.
223
224 Values: String.
225
226 Default value: The value of the title.
227
228 ##### `path`
229
230 **Required.**
231
232 Specifies the file in which Puppet ensures the line specified by `line`.
233
234 Value: String specifying an absolute path to the file.
235
236 ##### `replace`
237
238 Specifies whether the resource overwrites an existing line that matches the `match` parameter. If set to `false` and a line is found matching the `match` parameter, the line is not placed in the file.
239
240 Boolean.
241
242 Default value: `true`.
243
244 ### Data types
245
246 #### `Stdlib::Absolutepath`
247
248 A strict absolute path type. Uses a variant of Unixpath and Windowspath types.
249
250 Acceptable input examples:
251
252 ```shell
253 /var/log
254 ```
255
256 ```shell
257 /usr2/username/bin:/usr/local/bin:/usr/bin:.
258 ```
259
260 ```shell
261 C:\\WINDOWS\\System32
262 ```
263
264 Unacceptable input example:
265
266 ```shell
267 ../relative_path
268 ```
269
270 #### `Stdlib::Httpsurl`
271
272 Matches HTTPS URLs.
273
274 Acceptable input example:
275
276 ```shell
277 https://hello.com
278 ```
279
280 Unacceptable input example:
281
282 ```shell
283 httds://notquiteright.org`
284 ```
285
286 #### `Stdlib::Httpurl`
287
288 Matches both HTTPS and HTTP URLs.
289
290 Acceptable input example:
291
292 ```shell
293 https://hello.com
294
295 http://hello.com
296 ```
297
298 Unacceptable input example:
299
300 ```shell
301 httds://notquiteright.org
302 ```
303
304 #### `Stdlib::MAC`
305
306 Matches MAC addresses defined in [RFC5342](https://tools.ietf.org/html/rfc5342).
307
308 #### `Stdlib::Unixpath`
309
310 Matches paths on Unix operating systems.
311
312 Acceptable input example:
313
314 ```shell
315 /usr2/username/bin:/usr/local/bin:/usr/bin:
316
317 /var/tmp
318 ```
319
320 Unacceptable input example:
321
322 ```shell
323 C:/whatever
324 ```
325
326 #### `Stdlib::Windowspath`
327
328 Matches paths on Windows operating systems.
329
330 Acceptable input example:
331
332 ```shell
333 C:\\WINDOWS\\System32
334
335 C:\\
336
337 \\\\host\\windows
338 ```
339
340 Unacceptable input example:
341
342 ```shell
343 /usr2/username/bin:/usr/local/bin:/usr/bin:.
344 ```
345
346 ### Facts
347
348 #### `package_provider`
349
350 Returns the default provider Puppet uses to manage packages on this system.
351
352 #### `is_pe`
353
354 Returns whether Puppet Enterprise is installed. Does not report anything on platforms newer than PE 3.x.
355
356 #### `pe_version`
357
358 Returns the version of Puppet Enterprise installed. Does not report anything on platforms newer than PE 3.x.
359
360 #### `pe_major_version`
361
362 Returns the major version Puppet Enterprise that is installed. Does not report anything on platforms newer than PE 3.x.
363
364 #### `pe_minor_version`
365
366 Returns the minor version of Puppet Enterprise that is installed. Does not report anything on platforms newer than PE 3.x.
367
368 #### `pe_patch_version`
369
370 Returns the patch version of Puppet Enterprise that is installed.
371
372 #### `puppet_vardir`
373
374 Returns the value of the Puppet vardir setting for the node running Puppet or Puppet agent.
375
376 #### `puppet_environmentpath`
377
378 Returns the value of the Puppet environment path settings for the node running Puppet or Puppet agent.
379
380 #### `puppet_server`
381
382 Returns the Puppet agent's `server` value, which is the hostname of the Puppet master with which the agent should communicate.
383
384 #### `root_home`
385
386 Determines the root home directory.
387
388 Determines the root home directory, which depends on your operating system. Generally this is '/root'.
389
390 #### `service_provider`
391
392 Returns the default provider Puppet uses to manage services on this system
393
394 ### Functions
395
396 #### `abs`
397
398 Returns the absolute value of a number. For example, '-34.56' becomes '34.56'.
399
400 Argument: A single argument of either an integer or float value.
401
402 *Type*: rvalue.
403
404 #### `any2array`
405
406 Converts any object to an array containing that object. Converts empty argument lists are to empty arrays. Hashes are converted to arrays of alternating keys and values. Arrays are not touched.
407
408 *Type*: rvalue.
409
410 #### `any2bool`
411
412 Converts any object to a Boolean:
413
414 * Strings such as 'Y', 'y', '1', 'T', 't', 'TRUE', 'yes', 'true' return `true`.
415 * Strings such as '0', 'F', 'f', 'N', 'n', 'FALSE', 'no', 'false' return `false`.
416 * Booleans return their original value.
417 * A number (or a string representation of a number) greater than 0 returns `true`, otherwise `false`.
418 * An undef value returns `false`.
419 * Anything else returns `true`.
420
421 *Type*: rvalue.
422
423 #### `assert_private`
424
425 Sets the current class or definition as private. Calling the class or defined type from outside the current module fails.
426
427 For example, `assert_private()` called in class `foo::bar` outputs the following message if class is called from outside module `foo`: `Class foo::bar is private.`
428
429 To specify the error message you want to use:
430
431 ```puppet
432 assert_private("You're not supposed to do that!")
433 ```
434
435 *Type*: statement.
436
437 #### `base64`
438
439 Converts a string to and from base64 encoding. Requires an `action` ('encode', 'decode') and either a plain or base64-encoded `string`, and an optional `method` ('default', 'strict', 'urlsafe').
440
441 For backward compatibility, `method` is set as `default` if not specified.
442
443 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
444
445 **Examples:**
446
447 ```puppet
448 base64('encode', 'hello')
449 base64('encode', 'hello', 'default')
450 # return: "aGVsbG8=\n"
451
452 base64('encode', 'hello', 'strict')
453 # return: "aGVsbG8="
454
455 base64('decode', 'aGVsbG8=')
456 base64('decode', 'aGVsbG8=\n')
457 base64('decode', 'aGVsbG8=', 'default')
458 base64('decode', 'aGVsbG8=\n', 'default')
459 base64('decode', 'aGVsbG8=', 'strict')
460 # return: "hello"
461
462 base64('encode', 'https://puppetlabs.com', 'urlsafe')
463 # return: "aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ=="
464
465 base64('decode', 'aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ==', 'urlsafe')
466 # return: "https://puppetlabs.com"
467 ```
468
469 *Type*: rvalue.
470
471 #### `basename`
472
473 Returns the `basename` of a path. An optional argument strips the extension. For example:
474
475   * ('/path/to/a/file.ext') returns 'file.ext'
476   * ('relative/path/file.ext') returns 'file.ext'
477   * ('/path/to/a/file.ext', '.ext') returns 'file'
478
479 *Type*: rvalue.
480
481 #### `bool2num`
482
483 Converts a Boolean to a number. Converts values:
484
485 * `false`, 'f', '0', 'n', and 'no' to 0.
486 * `true`, 't', '1', 'y', and 'yes' to 1.
487
488   Argument: a single Boolean or string as an input.
489
490   *Type*: rvalue.
491
492 #### `bool2str`
493
494 Converts a Boolean to a string using optionally supplied arguments. The optional second and third arguments represent what true and false are converted to respectively. If only one argument is given, it is converted from a Boolean to a string containing `true` or `false`.
495
496 *Examples:*
497
498 ```puppet
499 bool2str(true)                    => `true`
500 bool2str(true, 'yes', 'no')       => 'yes'
501 bool2str(false, 't', 'f')         => 'f'
502 ```
503
504 Arguments: Boolean.
505
506 *Type*: rvalue.
507
508 #### `camelcase`
509
510 Converts the case of a string or all strings in an array to CamelCase (mixed case).
511
512 Arguments: Either an array or string. Returns the same type of argument as it received, but in CamelCase form.
513
514 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
515
516  *Type*: rvalue.
517
518 #### `capitalize`
519
520 Capitalizes the first character of a string or array of strings and lowercases the remaining characters of each string.
521
522 Arguments: either a single string or an array as an input. *Type*: rvalue.
523
524 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
525
526 #### `ceiling`
527
528 Returns the smallest integer greater than or equal to the argument.
529
530 Arguments: A single numeric value.
531
532 *Type*: rvalue.
533
534 #### `chomp`
535
536 Removes the record separator from the end of a string or an array of strings; for example, 'hello\n' becomes 'hello'.
537
538 Arguments: a single string or array.
539
540 *Type*: rvalue.
541
542 #### `chop`
543
544 Returns a new string with the last character removed. If the string ends with '\r\n', both characters are removed. Applying `chop` to an empty string returns an empty string. To only remove record separators, use the `chomp` function.
545
546 Arguments: A string or an array of strings as input.
547
548 *Type*: rvalue.
549
550 #### `clamp`
551
552 Keeps value within the range [Min, X, Max] by sort based on integer value (parameter order doesn't matter). Strings are converted and compared numerically. Arrays of values are flattened into a list for further handling. For example:
553
554   * `clamp('24', [575, 187])` returns 187.
555   * `clamp(16, 88, 661)` returns 88.
556   * `clamp([4, 3, '99'])` returns 4.
557
558 Arguments: strings, arrays, or numerics.
559
560 *Type*: rvalue.
561
562 #### `concat`
563
564 Appends the contents of multiple arrays onto the first array given. For example:
565
566   * `concat(['1','2','3'],'4')` returns ['1','2','3','4'].
567   * `concat(['1','2','3'],'4',['5','6','7'])` returns ['1','2','3','4','5','6','7'].
568
569 *Type*: rvalue.
570
571 #### `convert_base`
572
573 Converts a given integer or base 10 string representing an integer to a specified base, as a string. For example:
574
575   * `convert_base(5, 2)` results in: '101'
576   * `convert_base('254', '16')` results in: 'fe'
577
578 #### `count`
579
580 If called with only an array, counts the number of elements that are **not** nil or `undef`. If called with a second argument, counts the number of elements in an array that matches the second argument.
581
582 *Type*: rvalue.
583
584 #### `deep_merge`
585
586 Recursively merges two or more hashes together and returns the resulting hash.
587
588 ```puppet
589 $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
590 $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
591 $merged_hash = deep_merge($hash1, $hash2)
592 ```
593
594 The resulting hash is equivalent to:
595
596 ```puppet
597 $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }
598 ```
599
600 If there is a duplicate key that is a hash, they are recursively merged. If there is a duplicate key that is not a hash, the key in the rightmost hash takes precedence.
601
602 *Type*: rvalue.
603
604 #### `defined_with_params`
605
606 Takes a resource reference and an optional hash of attributes. Returns `true` if a resource with the specified attributes has already been added to the catalog. Returns `false` otherwise.
607
608 ```puppet
609 user { 'dan':
610   ensure => present,
611 }
612
613 if ! defined_with_params(User[dan], {'ensure' => 'present' }) {
614   user { 'dan': ensure => present, }
615 }
616 ```
617
618 *Type*: rvalue.
619
620 #### `delete`
621
622 Deletes all instances of a given element from an array, substring from a string, or key from a hash.
623
624 For example:
625
626 * `delete(['a','b','c','b'], 'b')` returns ['a','c'].
627 * `delete('abracadabra', 'bra')` returns 'acada'.
628 * `delete({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}.
629 * `delete(['ab', 'b'], 'b')` returns ['ab'].
630
631 *Type*: rvalue.
632
633 #### `delete_at`
634
635 Deletes a determined indexed value from an array.
636
637 For example: `delete_at(['a','b','c'], 1)` returns ['a','c'].
638
639 *Type*: rvalue.
640
641 #### `delete_regex`
642
643 Deletes all instances of a given element from an array or hash that match a provided regular expression. A string is treated as a one-item array.
644
645 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
646
647
648 For example
649
650 * `delete_regex(['a','b','c','b'], 'b')` returns ['a','c'].
651 * `delete_regex({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}.
652 * `delete_regex(['abf', 'ab', 'ac'], '^ab.*')` returns ['ac'].
653 * `delete_regex(['ab', 'b'], 'b')` returns ['ab'].
654
655 *Type*: rvalue.
656
657 #### `delete_values`
658
659 Deletes all instances of a given value from a hash.
660
661 For example:
662
663 * `delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B')` returns {'a'=>'A','c'=>'C','B'=>'D'}
664
665 *Type*: rvalue.
666
667 #### `delete_undef_values`
668
669 Deletes all instances of the `undef` value from an array or hash.
670
671 For example:
672
673 * `$hash = delete_undef_values({a=>'A', b=>'', c=>`undef`, d => false})` returns {a => 'A', b => '', d => false}.
674
675 *Type*: rvalue.
676
677 #### `deprecation`
678
679 Prints deprecation warnings and logs a warning once for a given key:
680
681 ```puppet
682 deprecation(key, message)
683 ```
684
685 Arguments:
686
687 * A string specifying the key: To keep the number of messages low during the lifetime of a Puppet process, only one message per key is logged.
688 * A string specifying the message: the text to be logged.
689
690 *Type*: Statement.
691
692 **Settings that affect `deprecation`**
693
694 Other settings in Puppet affect the stdlib `deprecation` function:
695
696 * [`disable_warnings`](https://docs.puppet.com/puppet/latest/reference/configuration.html#disablewarnings)
697 * [`max_deprecations`](https://docs.puppet.com/puppet/latest/reference/configuration.html#maxdeprecations)
698 * [`strict`](https://docs.puppet.com/puppet/latest/reference/configuration.html#strict):
699
700     * `error`: Fails immediately with the deprecation message
701     * `off`: Output emits no messages.
702     * `warning`: Logs all warnings. This is the default setting.
703
704 * The environment variable `STDLIB_LOG_DEPRECATIONS`
705
706   Specifies whether or not to log deprecation warnings. This is especially useful for automated tests to avoid flooding your logs before you are ready to migrate.
707
708   This variable is Boolean, with the following effects:
709
710   * `true`: Functions log a warning.
711   * `false`: No warnings are logged.
712   * No value set: Puppet 4 emits warnings, but Puppet 3 does not.
713
714 #### `difference`
715
716 Returns the difference between two arrays. The returned array is a copy of the original array, removing any items that also appear in the second array.
717
718 For example:
719
720 * `difference(["a","b","c"],["b","c","d"])` returns ["a"].
721
722 *Type*: rvalue.
723
724 #### `dig`
725
726 > DEPRECATED: This function has been replaced with a built-in [`dig`](https://docs.puppet.com/puppet/latest/function.html#dig) function as of Puppet 4.5.0. Use [`dig44()`](#dig44) for backwards compatibility or use the new version.
727
728 Retrieves a value within multiple layers of hashes and arrays via an array of keys containing a path. The function goes through the structure by each path component and tries to return the value at the end of the path.
729
730 In addition to the required path argument, the function accepts the default argument. It is returned if the path is not correct, if no value was found, or if any other error has occurred.
731
732 ```ruby
733 $data = {
734   'a' => {
735     'b' => [
736       'b1',
737       'b2',
738       'b3',
739     ]
740   }
741 }
742
743 $value = dig($data, ['a', 'b', 2])
744 # $value = 'b3'
745
746 # with all possible options
747 $value = dig($data, ['a', 'b', 2], 'not_found')
748 # $value = 'b3'
749
750 # using the default value
751 $value = dig($data, ['a', 'b', 'c', 'd'], 'not_found')
752 # $value = 'not_found'
753 ```
754
755 1. **$data** The data structure we are working with.
756 2. **['a', 'b', 2]** The path array.
757 3. **'not_found'** The default value. It is returned if nothing is found.
758
759 Default value: `undef`.
760
761 *Type*: rvalue.
762
763 #### `dig44`
764
765 Retrieves a value within multiple layers of hashes and arrays via an array of keys containing a path. The function goes through the structure by each path component and tries to return the value at the end of the path.
766
767 In addition to the required path argument, the function accepts the default argument. It is returned if the path is incorrect, if no value was found, or if any other error has occurred.
768
769 ```ruby
770 $data = {
771   'a' => {
772     'b' => [
773       'b1',
774       'b2',
775       'b3',
776     ]
777   }
778 }
779
780 $value = dig44($data, ['a', 'b', 2])
781 # $value = 'b3'
782
783 # with all possible options
784 $value = dig44($data, ['a', 'b', 2], 'not_found')
785 # $value = 'b3'
786
787 # using the default value
788 $value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found')
789 # $value = 'not_found'
790 ```
791
792 *Type*: rvalue.
793
794 1. **$data** The data structure we are working with.
795 2. **['a', 'b', 2]** The path array.
796 3. **'not_found'** The default value. It will be returned if nothing is found.
797    (optional, defaults to `undef`)
798
799 #### `dirname`
800
801 Returns the `dirname` of a path. For example, `dirname('/path/to/a/file.ext')` returns '/path/to/a'.
802
803 *Type*: rvalue.
804
805 #### `dos2unix`
806
807 Returns the Unix version of the given string. Very useful when using a File resource with a cross-platform template.
808
809 ```puppet
810 file { $config_file:
811   ensure  => file,
812   content => dos2unix(template('my_module/settings.conf.erb')),
813 }
814 ```
815
816 See also [unix2dos](#unix2dos).
817
818 *Type*: rvalue.
819
820 #### `downcase`
821
822 Converts the case of a string or of all strings in an array to lowercase.
823
824 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
825
826 *Type*: rvalue.
827
828 #### `empty`
829
830 Returns `true` if the argument is an array or hash that contains no elements, or an empty string. Returns `false` when the argument is a numerical value.
831
832 *Type*: rvalue.
833
834 #### `enclose_ipv6`
835
836 Takes an array of IP addresses and encloses the ipv6 addresses with square brackets.
837
838 *Type*: rvalue.
839
840 #### `ensure_packages`
841
842 Takes a list of packages in an array or hash and installs them only if they don't already exist. Optionally takes a hash as a second parameter to be passed as the third argument to the `ensure_resource()` or `ensure_resources()` function.
843
844 *Type*: statement.
845
846 For an array:
847
848 ```puppet
849 ensure_packages(['ksh','openssl'], {'ensure' => 'present'})
850 ```
851
852 For a hash:
853
854 ```puppet
855 ensure_packages({'ksh' => { ensure => '20120801-1' } ,  'mypackage' => { source => '/tmp/myrpm-1.0.0.x86_64.rpm', provider => "rpm" }}, {'ensure' => 'present'})
856 ```
857
858 #### `ensure_resource`
859
860 Takes a resource type, title, and a hash of attributes that describe the resource(s).
861
862 ```
863 user { 'dan':
864   ensure => present,
865 }
866 ```
867
868 This example only creates the resource if it does not already exist:
869
870   `ensure_resource('user', 'dan', {'ensure' => 'present' })`
871
872 If the resource already exists, but does not match the specified parameters, this function attempts to recreate the resource, leading to a duplicate resource definition error.
873
874 An array of resources can also be passed in, and each will be created with the type and parameters specified if it doesn't already exist.
875
876 `ensure_resource('user', ['dan','alex'], {'ensure' => 'present'})`
877
878 *Type*: statement.
879
880 #### `ensure_resources`
881
882 Creates resource declarations from a hash, but doesn't conflict with resources that are already declared.
883
884 Specify a resource type and title and a hash of attributes that describe the resource(s).
885
886 ```puppet
887 user { 'dan':
888   gid => 'mygroup',
889   ensure => present,
890 }
891
892 ensure_resources($user)
893 ```
894
895 Pass in a hash of resources. Any listed resources that don't already exist will be created with the type and parameters specified:
896
897     ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } ,  'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'})
898
899 From Hiera backend:
900
901 ```yaml
902 userlist:
903   dan:
904     gid: 'mygroup'
905     uid: '600'
906   alex:
907     gid: 'mygroup'
908 ```
909
910 ```puppet
911 ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'})
912 ```
913
914 #### `fact`
915
916 Return the value of a given fact. Supports the use of dot-notation for referring to structured facts. If a fact requested does not exist, returns Undef.
917
918 Example usage:
919
920 ```puppet
921 fact('kernel')
922 fact('osfamily')
923 fact('os.architecture')
924 ```
925
926 Array indexing:
927
928 ```puppet
929 $first_processor  = fact('processors.models.0')
930 $second_processor = fact('processors.models.1')
931 ```
932
933 Fact containing a "." in the fact name:
934
935 ```puppet
936 fact('vmware."VRA.version"')
937 ```
938
939 #### `flatten`
940
941 Flattens deeply nested arrays and returns a single flat array as a result.
942
943 For example, `flatten(['a', ['b', ['c']]])` returns ['a','b','c'].
944
945 *Type*: rvalue.
946
947 #### `floor`
948
949 Returns the largest integer less than or equal to the argument.
950
951 Arguments: A single numeric value.
952
953 *Type*: rvalue.
954
955 #### `fqdn_rand_string`
956
957 Generates a random alphanumeric string, combining the `$fqdn` fact and an optional seed for repeatable randomness. Optionally, you can specify a character set for the function (defaults to alphanumeric).
958
959 *Usage:*
960
961 ```puppet
962 fqdn_rand_string(LENGTH, [CHARSET], [SEED])
963 ```
964
965 *Examples:*
966
967 ```puppet
968 fqdn_rand_string(10)
969 fqdn_rand_string(10, 'ABCDEF!@#$%^')
970 fqdn_rand_string(10, '', 'custom seed')
971 ```
972
973 Arguments:
974
975 * An integer, specifying the length of the resulting string.
976 * Optionally, a string specifying the character set.
977 * Optionally, a string specifying the seed for repeatable randomness.
978
979 *Type*: rvalue.
980
981 #### `fqdn_rotate`
982
983 Rotates an array or string a random number of times, combining the `$fqdn` fact and an optional seed for repeatable randomness.
984
985 *Usage:*
986
987 ```puppet
988 fqdn_rotate(VALUE, [SEED])
989 ```
990
991 *Examples:*
992
993 ```puppet
994 fqdn_rotate(['a', 'b', 'c', 'd'])
995 fqdn_rotate('abcd')
996 fqdn_rotate([1, 2, 3], 'custom seed')
997 ```
998
999 *Type*: rvalue.
1000
1001 #### `fqdn_uuid`
1002
1003 Returns a [RFC 4122](https://tools.ietf.org/html/rfc4122) valid version 5 UUID based on an FQDN string under the DNS namespace:
1004
1005   * fqdn_uuid('puppetlabs.com') returns '9c70320f-6815-5fc5-ab0f-debe68bf764c'
1006   * fqdn_uuid('google.com') returns '64ee70a4-8cc1-5d25-abf2-dea6c79a09c8'
1007
1008 *Type*: rvalue.
1009
1010 #### `get_module_path`
1011
1012 Returns the absolute path of the specified module for the current environment.
1013
1014 ```puppet
1015 $module_path = get_module_path('stdlib')
1016 ```
1017
1018 *Type*: rvalue.
1019
1020 #### `getparam`
1021
1022 Returns the value of a resource's parameter.
1023
1024 Arguments: A resource reference and the name of the parameter.
1025
1026 For example, the following returns 'param_value':
1027
1028 ```puppet
1029 define example_resource($param) {
1030 }
1031
1032 example_resource { "example_resource_instance":
1033   param => "param_value"
1034 }
1035
1036 getparam(Example_resource["example_resource_instance"], "param")
1037 ```
1038
1039 *Type*: rvalue.
1040
1041 #### `getvar`
1042
1043 Looks up a variable in a remote namespace.
1044
1045 For example:
1046
1047 ```puppet
1048 $foo = getvar('site::data::foo')
1049 # Equivalent to $foo = $site::data::foo
1050 ```
1051
1052 This is useful if the namespace itself is stored in a string:
1053
1054 ```puppet
1055 $datalocation = 'site::data'
1056 $bar = getvar("${datalocation}::bar")
1057 # Equivalent to $bar = $site::data::bar
1058 ```
1059
1060 *Type*: rvalue.
1061
1062 #### `glob`
1063
1064 Returns an array of strings of paths matching path patterns.
1065
1066 Arguments: A string or an array of strings specifying path patterns.
1067
1068 ```puppet
1069 $confs = glob(['/etc/**/*.conf', '/opt/**/*.conf'])
1070 ```
1071
1072 *Type*: rvalue.
1073
1074 #### `grep`
1075
1076 Searches through an array and returns any elements that match the provided regular expression.
1077
1078 For example, `grep(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['aaa','aaaddd'].
1079
1080 *Type*: rvalue.
1081
1082 #### `has_interface_with`
1083
1084 Returns a Boolean based on kind and value:
1085
1086   * macaddress
1087   * netmask
1088   * ipaddress
1089   * network
1090
1091 *Examples:*
1092
1093 ```puppet
1094 has_interface_with("macaddress", "x:x:x:x:x:x")
1095 has_interface_with("ipaddress", "127.0.0.1")    => true
1096 ```
1097
1098 If no kind is given, then the presence of the interface is checked:
1099
1100 ```puppet
1101 has_interface_with("lo")                        => true
1102 ```
1103
1104 *Type*: rvalue.
1105
1106 #### `has_ip_address`
1107
1108 Returns `true` if the client has the requested IP address on some interface. This function iterates through the `interfaces` fact and checks the `ipaddress_IFACE` facts, performing a simple string comparison.
1109
1110 Arguments: A string specifying an IP address.
1111
1112 *Type*: rvalue.
1113
1114 #### `has_ip_network`
1115
1116 Returns `true` if the client has an IP address within the requested network. This function iterates through the `interfaces` fact and checks the `network_IFACE` facts, performing a simple string comparision.
1117
1118 Arguments: A string specifying an IP address.
1119
1120 *Type*: rvalue.
1121
1122 #### `has_key`
1123
1124 Determines if a hash has a certain key value.
1125
1126 *Example*:
1127
1128 ```
1129 $my_hash = {'key_one' => 'value_one'}
1130 if has_key($my_hash, 'key_two') {
1131   notice('we will not reach here')
1132 }
1133 if has_key($my_hash, 'key_one') {
1134   notice('this will be printed')
1135 }
1136 ```
1137
1138 *Type*: rvalue.
1139
1140 #### `hash`
1141
1142 Converts an array into a hash.
1143
1144 For example, `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}.
1145
1146 *Type*: rvalue.
1147
1148 #### `intersection`
1149
1150 Returns an array an intersection of two.
1151
1152 For example, `intersection(["a","b","c"],["b","c","d"])` returns ["b","c"].
1153
1154 *Type*: rvalue.
1155
1156 #### `is_a`
1157
1158 Boolean check to determine whether a variable is of a given data type. This is equivalent to the `=~` type checks. This function is available only in Puppet 4, or in Puppet 3 with the "future" parser.
1159
1160 ```
1161 foo = 3
1162 $bar = [1,2,3]
1163 $baz = 'A string!'
1164
1165 if $foo.is_a(Integer) {
1166   notify  { 'foo!': }
1167 }
1168 if $bar.is_a(Array) {
1169   notify { 'bar!': }
1170 }
1171 if $baz.is_a(String) {
1172   notify { 'baz!': }
1173 }
1174 ```
1175
1176 * See the [the Puppet type system](https://docs.puppetlabs.com/latest/type.html#about-resource-types) for more information about types.
1177 * See the [`assert_type()`](https://docs.puppetlabs.com/latest/function.html#asserttype) function for flexible ways to assert the type of a value.
1178
1179 #### `is_absolute_path`
1180
1181 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1182
1183 Returns `true` if the given path is absolute.
1184
1185 *Type*: rvalue.
1186
1187 #### `is_array`
1188
1189 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1190
1191 Returns `true` if the variable passed to this function is an array.
1192
1193 *Type*: rvalue.
1194
1195 #### `is_bool`
1196
1197 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1198
1199 Returns `true` if the variable passed to this function is a Boolean.
1200
1201 *Type*: rvalue.
1202
1203 #### `is_domain_name`
1204
1205 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1206
1207 Returns `true` if the string passed to this function is a syntactically correct domain name.
1208
1209 *Type*: rvalue.
1210
1211 #### `is_email_address`
1212
1213 Returns true if the string passed to this function is a valid email address.
1214
1215 *Type*: rvalue.
1216
1217
1218 #### `is_float`
1219
1220 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1221
1222 Returns `true` if the variable passed to this function is a float.
1223
1224 *Type*: rvalue.
1225
1226 #### `is_function_available`
1227
1228 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1229
1230 Accepts a string as an argument and determines whether the Puppet runtime has access to a function by that name. It returns `true` if the function exists, `false` if not.
1231
1232 *Type*: rvalue.
1233
1234 #### `is_hash`
1235
1236 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1237
1238 Returns `true` if the variable passed to this function is a hash.
1239
1240 *Type*: rvalue.
1241
1242 #### `is_integer`
1243
1244 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1245
1246 Returns `true` if the variable returned to this string is an integer.
1247
1248 *Type*: rvalue.
1249
1250 #### `is_ip_address`
1251
1252 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1253
1254 Returns `true` if the string passed to this function is a valid IP address.
1255
1256 *Type*: rvalue.
1257
1258 #### `is_ipv6_address`
1259
1260 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1261
1262 Returns `true` if the string passed to this function is a valid IPv6 address.
1263
1264 *Type*: rvalue.
1265
1266 #### `is_ipv4_address`
1267
1268 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1269
1270 Returns `true` if the string passed to this function is a valid IPv4 address.
1271
1272 *Type*: rvalue.
1273
1274 #### `is_mac_address`
1275
1276 Returns `true` if the string passed to this function is a valid MAC address.
1277
1278 *Type*: rvalue.
1279
1280 #### `is_numeric`
1281
1282 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1283
1284 Returns `true` if the variable passed to this function is a number.
1285
1286 *Type*: rvalue.
1287
1288 #### `is_string`
1289
1290 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1291
1292 Returns `true` if the variable passed to this function is a string.
1293
1294 *Type*: rvalue.
1295
1296 #### `join`
1297
1298 Joins an array into a string using a separator. For example, `join(['a','b','c'], ",")` results in: "a,b,c".
1299
1300 *Type*: rvalue.
1301
1302 #### `join_keys_to_values`
1303
1304 Joins each key of a hash to that key's corresponding value with a separator, returning the result as strings.
1305
1306 If a value is an array, the key is prefixed to each element. The return value is a flattened array.
1307
1308 For example, `join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ")` results in ["a is 1","b is 2","b is 3"].
1309
1310 *Type*: rvalue.
1311
1312 #### `keys`
1313
1314 Returns the keys of a hash as an array.
1315
1316 *Type*: rvalue.
1317
1318 #### `length`
1319
1320 Returns the length of a given string, array or hash. Replaces the deprecated `size()` function.
1321
1322 *Type*: rvalue.
1323
1324 #### `loadyaml`
1325
1326 Loads a YAML file containing an array, string, or hash, and returns the data in the corresponding native data type.
1327
1328 For example:
1329
1330 ```puppet
1331 $myhash = loadyaml('/etc/puppet/data/myhash.yaml')
1332 ```
1333
1334 The second parameter is returned if the file was not found or could not be parsed.
1335
1336 For example:
1337
1338 ```puppet
1339 $myhash = loadyaml('no-file.yaml', {'default'=>'value'})
1340 ```
1341
1342 *Type*: rvalue.
1343
1344 #### `loadjson`
1345
1346 Loads a JSON file containing an array, string, or hash, and returns the data in the corresponding native data type.
1347
1348 For example:
1349
1350 ```puppet
1351 $myhash = loadjson('/etc/puppet/data/myhash.json')
1352 ```
1353
1354 The second parameter is returned if the file was not found or could not be parsed.
1355
1356 For example:
1357
1358 ```puppet
1359   $myhash = loadjson('no-file.json', {'default'=>'value'})
1360   ```
1361
1362 *Type*: rvalue.
1363
1364 #### `load_module_metadata`
1365
1366 Loads the metadata.json of a target module. Can be used to determine module version and authorship for dynamic support of modules.
1367
1368 ```puppet
1369 $metadata = load_module_metadata('archive')
1370 notify { $metadata['author']: }
1371 ```
1372
1373 When a module's metadata file is absent, the catalog compilation fails. To avoid this failure:
1374
1375 ```
1376 $metadata = load_module_metadata('mysql', true)
1377 if empty($metadata) {
1378   notify { "This module does not have a metadata.json file.": }
1379 }
1380 ```
1381
1382 *Type*: rvalue.
1383
1384 #### `lstrip`
1385
1386 Strips spaces to the left of a string.
1387
1388 *Type*: rvalue.
1389
1390 #### `max`
1391
1392 Returns the highest value of all arguments. Requires at least one argument.
1393
1394 Arguments: A numeric or a string representing a number.
1395
1396 *Type*: rvalue.
1397
1398 #### `member`
1399
1400 This function determines if a variable is a member of an array. The variable can be a string, an array, or a fixnum.
1401
1402 For example, `member(['a','b'], 'b')` and `member(['a','b','c'], ['b','c'])` return `true`, while `member(['a','b'], 'c')` and `member(['a','b','c'], ['c','d'])` return `false`.
1403
1404 *Note*: This function does not support nested arrays. If the first argument contains nested arrays, it will not recurse through them.
1405
1406 *Type*: rvalue.
1407
1408 #### `merge`
1409
1410 Merges two or more hashes together and returns the resulting hash.
1411
1412 *Example*:
1413
1414 ```puppet
1415 $hash1 = {'one' => 1, 'two' => 2}
1416 $hash2 = {'two' => 'dos', 'three' => 'tres'}
1417 $merged_hash = merge($hash1, $hash2)
1418 # The resulting hash is equivalent to:
1419 # $merged_hash =  {'one' => 1, 'two' => 'dos', 'three' => 'tres'}
1420 ```
1421
1422 When there is a duplicate key, the key in the rightmost hash takes precedence.
1423
1424 *Type*: rvalue.
1425
1426 #### `min`
1427
1428 Returns the lowest value of all arguments. Requires at least one argument.
1429
1430 Arguments: A numeric or a string representing a number.
1431
1432 *Type*: rvalue.
1433
1434 #### `num2bool`
1435
1436 Converts a number or a string representation of a number into a true Boolean. Zero or anything non-numeric becomes `false`. Numbers greater than 0 become `true`.
1437
1438 *Type*: rvalue.
1439
1440 #### `parsejson`
1441
1442 Converts a string of JSON into the correct Puppet structure (as a hash, array, string, integer, or a combination of such).
1443
1444 Arguments:
1445 * The JSON string to convert, as a first argument.
1446 * Optionally, the result to return if conversion fails, as a second error.
1447
1448 *Type*: rvalue.
1449
1450 #### `parseyaml`
1451
1452 Converts a string of YAML into the correct Puppet structure.
1453
1454 Arguments:
1455 * The YAML string to convert, as a first argument.
1456 * Optionally, the result to return if conversion fails, as a second error.
1457
1458 *Type*: rvalue.
1459
1460 #### `pick`
1461
1462 From a list of values, returns the first value that is not undefined or an empty string. Takes any number of arguments, and raises an error if all values are undefined or empty.
1463
1464 ```puppet
1465 $real_jenkins_version = pick($::jenkins_version, '1.449')
1466 ```
1467
1468 *Type*: rvalue.
1469
1470 #### `pick_default`
1471
1472 Returns the first value in a list of values. Unlike the `pick()` function, `pick_default()` does not fail if all arguments are empty. This allows it to use an empty value as default.
1473
1474 *Type*: rvalue.
1475
1476 #### `prefix`
1477
1478 Applies a prefix to all elements in an array, or to the keys in a hash.
1479
1480 For example:
1481
1482 * `prefix(['a','b','c'], 'p')` returns ['pa','pb','pc'].
1483 * `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'pa'=>'b','pb'=>'c','pc'=>'d'}.
1484
1485 *Type*: rvalue.
1486
1487 #### `pry`
1488
1489 Invokes a pry debugging session in the current scope object. Useful for debugging manifest code at specific points during a compilation. Should be used only when running `puppet apply` or running a Puppet master in the foreground. Requires the `pry` gem to be installed in Puppet's rubygems.
1490
1491 *Examples:*
1492
1493 ```puppet
1494 pry()
1495 ```
1496
1497 In a pry session, useful commands include:
1498
1499 * Run `catalog` to see the contents currently compiling catalog.
1500 * Run `cd catalog` and `ls` to see catalog methods and instance variables.
1501 * Run `@resource_table` to see the current catalog resource table.
1502
1503 #### `pw_hash`
1504
1505 Hashes a password using the crypt function. Provides a hash usable on most POSIX systems.
1506
1507 The first argument to this function is the password to hash. If it is `undef` or an empty string, this function returns `undef`.
1508
1509 The second argument to this function is which type of hash to use. It will be converted into the appropriate crypt(3) hash specifier. Valid hash types are:
1510
1511 |Hash type            |Specifier|
1512 |---------------------|---------|
1513 |MD5                  |1        |
1514 |SHA-256              |5        |
1515 |SHA-512 (recommended)|6        |
1516
1517 The third argument to this function is the salt to use.
1518
1519 This function uses the Puppet master's implementation of crypt(3). If your environment contains several different operating systems, ensure that they are compatible before using this function.
1520
1521 *Type*: rvalue.
1522
1523 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1524
1525 #### `range`
1526
1527 Extrapolates a range as an array when given in the form of '(start, stop)'. For example, `range("0", "9")` returns [0,1,2,3,4,5,6,7,8,9]. Zero-padded strings are converted to integers automatically, so `range("00", "09")` returns [0,1,2,3,4,5,6,7,8,9].
1528
1529 Non-integer strings are accepted:
1530
1531 * `range("a", "c")` returns ["a","b","c"].
1532 * `range("host01", "host10")` returns ["host01", "host02", ..., "host09", "host10"].
1533
1534 You must explicitly include trailing zeros, or the underlying Ruby function fails.
1535
1536 Passing a third argument causes the generated range to step by that interval. For example:
1537
1538 * `range("0", "9", "2")` returns ["0","2","4","6","8"].
1539
1540 *Type*: rvalue.
1541
1542 #### `regexpescape`
1543
1544 Regexp escape a string or array of strings. Requires either a single string or an array as an input.
1545
1546 *Type*: rvalue.
1547
1548 #### `reject`
1549
1550 Searches through an array and rejects all elements that match the provided regular expression.
1551
1552 For example, `reject(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['bbb','ccc'].
1553
1554 *Type*: rvalue.
1555
1556 #### `reverse`
1557
1558 Reverses the order of a string or array.
1559
1560 #### `round`
1561
1562  Rounds a number to the nearest integer
1563
1564 *Type*: rvalue.
1565
1566 #### `rstrip`
1567
1568 Strips spaces to the right of the string.
1569
1570 *Type*: rvalue.
1571
1572 #### `seeded_rand`
1573
1574 Takes an integer max value and a string seed value and returns a repeatable random integer smaller than max. Similar to `fqdn_rand`, but does not add node specific data to the seed.
1575
1576 *Type*: rvalue.
1577
1578 #### `shell_escape`
1579
1580 Escapes a string so that it can be safely used in a Bourne shell command line. Note that the resulting string should be used unquoted and is not intended for use in either double or single quotes. This function behaves the same as Ruby's `Shellwords.shellescape()` function; see the [Ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellescape).
1581
1582 For example:
1583
1584 ```puppet
1585 shell_escape('foo b"ar') => 'foo\ b\"ar'
1586 ```
1587
1588 *Type*: rvalue.
1589
1590 #### `shell_join`
1591
1592 Builds a command line string from a given array of strings. Each array item is escaped for Bourne shell. All items are then joined together, with a single space in between. This function behaves the same as Ruby's `Shellwords.shelljoin()` function; see the [Ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shelljoin).
1593
1594 For example:
1595
1596 ```puppet
1597 shell_join(['foo bar', 'ba"z']) => 'foo\ bar ba\"z'
1598 ```
1599
1600 *Type*: rvalue.
1601
1602 #### `shell_split`
1603
1604 Splits a string into an array of tokens. This function behaves the same as Ruby's `Shellwords.shellsplit()` function; see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellsplit).
1605
1606 *Example:*
1607
1608 ```puppet
1609 shell_split('foo\ bar ba\"z') => ['foo bar', 'ba"z']
1610 ```
1611
1612 *Type*: rvalue.
1613
1614 #### `shuffle`
1615
1616 Randomizes the order of a string or array elements.
1617
1618 *Type*: rvalue.
1619
1620 #### `size`
1621
1622 Returns the number of elements in a string, an array or a hash. This function will be deprecated in a future release. For Puppet 4, use the `length` function.
1623
1624 *Type*: rvalue.
1625
1626 #### `sort`
1627
1628 Sorts strings and arrays lexically.
1629
1630 *Type*: rvalue.
1631
1632 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1633
1634 #### `squeeze`
1635
1636 Replaces consecutive repeats (such as 'aaaa') in a string with a single character. Returns a new string.
1637
1638 *Type*: rvalue.
1639
1640 #### `str2bool`
1641
1642 Converts certain strings to a Boolean. This attempts to convert strings that contain the values '1', 'true', 't', 'y', or 'yes' to `true`. Strings that contain values '0', 'false', 'f', 'n', or 'no', or that are an empty string or undefined are converted to `false`. Any other value causes an error. These checks are case insensitive.
1643
1644 *Type*: rvalue.
1645
1646 #### `str2saltedsha512`
1647
1648 Converts a string to a salted-SHA512 password hash, used for OS X versions 10.7 or greater. Returns a hex version of a salted-SHA512 password hash, which can be inserted into Puppet manifests as a valid password attribute.
1649
1650 *Type*: rvalue.
1651
1652 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1653
1654 #### `strftime`
1655
1656 Returns formatted time.
1657
1658 For example, `strftime("%s")` returns the time since Unix epoch, and `strftime("%Y-%m-%d")` returns the date.
1659
1660 Arguments: A string specifying the time in `strftime` format. See the Ruby [strftime](https://ruby-doc.org/core-2.1.9/Time.html#method-i-strftime) documentation for details.
1661
1662 *Type*: rvalue.
1663
1664 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1665
1666 *Format:*
1667
1668 * `%a`: The abbreviated weekday name ('Sun')
1669 * `%A`: The full weekday name ('Sunday')
1670 * `%b`: The abbreviated month name ('Jan')
1671 * `%B`: The full month name ('January')
1672 * `%c`: The preferred local date and time representation
1673 * `%C`: Century (20 in 2009)
1674 * `%d`: Day of the month (01..31)
1675 * `%D`: Date (%m/%d/%y)
1676 * `%e`: Day of the month, blank-padded ( 1..31)
1677 * `%F`: Equivalent to %Y-%m-%d (the ISO 8601 date format)
1678 * `%h`: Equivalent to %b
1679 * `%H`: Hour of the day, 24-hour clock (00..23)
1680 * `%I`: Hour of the day, 12-hour clock (01..12)
1681 * `%j`: Day of the year (001..366)
1682 * `%k`: Hour, 24-hour clock, blank-padded ( 0..23)
1683 * `%l`: Hour, 12-hour clock, blank-padded ( 0..12)
1684 * `%L`: Millisecond of the second (000..999)
1685 * `%m`: Month of the year (01..12)
1686 * `%M`: Minute of the hour (00..59)
1687 * `%n`: Newline (\n)
1688 * `%N`: Fractional seconds digits, default is 9 digits (nanosecond)
1689   * `%3N`: Millisecond (3 digits)
1690   * `%6N`: Microsecond (6 digits)
1691   * `%9N`: Nanosecond (9 digits)
1692 * `%p`: Meridian indicator ('AM' or 'PM')
1693 * `%P`: Meridian indicator ('am' or 'pm')
1694 * `%r`: Time, 12-hour (same as %I:%M:%S %p)
1695 * `%R`: Time, 24-hour (%H:%M)
1696 * `%s`: Number of seconds since the Unix epoch, 1970-01-01 00:00:00 UTC.
1697 * `%S`: Second of the minute (00..60)
1698 * `%t`: Tab character ( )
1699 * `%T`: Time, 24-hour (%H:%M:%S)
1700 * `%u`: Day of the week as a decimal, Monday being 1. (1..7)
1701 * `%U`: Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
1702 * `%v`: VMS date (%e-%b-%Y)
1703 * `%V`: Week number of year according to ISO 8601 (01..53)
1704 * `%W`: Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
1705 * `%w`: Day of the week (Sunday is 0, 0..6)
1706 * `%x`: Preferred representation for the date alone, no time
1707 * `%X`: Preferred representation for the time alone, no date
1708 * `%y`: Year without a century (00..99)
1709 * `%Y`: Year with century
1710 * `%z`: Time zone as hour offset from UTC (e.g. +0900)
1711 * `%Z`: Time zone name
1712 * `%%`: Literal '%' character
1713
1714 #### `strip`
1715
1716 Removes leading and trailing whitespace from a string or from every string inside an array. For example, `strip("    aaa   ")` results in "aaa".
1717
1718 *Type*: rvalue.
1719
1720 #### `suffix`
1721
1722 Applies a suffix to all elements in an array or to all keys in a hash.
1723
1724 For example:
1725
1726 * `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp'].
1727 * `suffix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'ap'=>'b','bp'=>'c','cp'=>'d'}.
1728
1729 *Type*: rvalue.
1730
1731 #### `swapcase`
1732
1733 Swaps the existing case of a string. For example, `swapcase("aBcD")` results in "AbCd".
1734
1735 *Type*: rvalue.
1736
1737 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1738
1739 #### `time`
1740
1741 Returns the current Unix epoch time as an integer.
1742
1743 For example, `time()` returns something like '1311972653'.
1744
1745 *Type*: rvalue.
1746
1747 #### `to_bytes`
1748
1749 Converts the argument into bytes.
1750
1751 For example, "4 kB" becomes "4096".
1752
1753 Arguments: A single string.
1754
1755 *Type*: rvalue.
1756
1757 #### `try_get_value`
1758
1759 **DEPRECATED:** replaced by `dig()`.
1760
1761 Retrieves a value within multiple layers of hashes and arrays.
1762
1763 Arguments:
1764
1765 * A string containing a path, as the first argument. Provide this argument as a string of hash keys or array indexes starting with zero and separated by the path separator character (default "/"). This function goes through the structure by each path component and tries to return the value at the end of the path.
1766
1767 * A default argument as a second argument. This argument is returned if the path is not correct, if no value was found, or if any other error has occurred.
1768 * The path separator character as a last argument.
1769
1770 ```ruby
1771 $data = {
1772   'a' => {
1773     'b' => [
1774       'b1',
1775       'b2',
1776       'b3',
1777     ]
1778   }
1779 }
1780
1781 $value = try_get_value($data, 'a/b/2')
1782 # $value = 'b3'
1783
1784 # with all possible options
1785 $value = try_get_value($data, 'a/b/2', 'not_found', '/')
1786 # $value = 'b3'
1787
1788 # using the default value
1789 $value = try_get_value($data, 'a/b/c/d', 'not_found')
1790 # $value = 'not_found'
1791
1792 # using custom separator
1793 $value = try_get_value($data, 'a|b', [], '|')
1794 # $value = ['b1','b2','b3']
1795 ```
1796
1797 1. **$data** The data structure we are working with.
1798 2. **'a/b/2'** The path string.
1799 3. **'not_found'** The default value. It will be returned if nothing is found.
1800    (optional, defaults to *`undef`*)
1801 4. **'/'** The path separator character.
1802    (optional, defaults to *'/'*)
1803
1804 *Type*: rvalue.
1805
1806 #### `type3x`
1807
1808 **Deprecated**. This function will be removed in a future release.
1809
1810 Returns a string description of the type of a given value. The type can be a string, array, hash, float, integer, or Boolean. For Puppet 4, use the new type system instead.
1811
1812 Arguments:
1813
1814 * string
1815 * array
1816 * hash
1817 * float
1818 * integer
1819 * Boolean
1820
1821 *Type*: rvalue.
1822
1823 #### `type_of`
1824
1825 This function is provided for backwards compatibility, but the built-in [type() function](https://docs.puppet.com/puppet/latest/reference/function.html#type) provided by Puppet is preferred.
1826
1827 Returns the literal type of a given value. Requires Puppet 4. Useful for comparison of types with `<=` such as in `if type_of($some_value) <= Array[String] { ... }` (which is equivalent to `if $some_value =~ Array[String] { ... }`).
1828
1829 *Type*: rvalue.
1830
1831 #### `union`
1832
1833 Returns a union of two or more arrays, without duplicates.
1834
1835 For example, `union(["a","b","c"],["b","c","d"])` returns ["a","b","c","d"].
1836
1837 *Type*: rvalue.
1838
1839 #### `unique`
1840
1841 Removes duplicates from strings and arrays.
1842
1843 For example, `unique("aabbcc")` returns 'abc', and `unique(["a","a","b","b","c","c"])` returns ["a","b","c"].
1844
1845 *Type*: rvalue.
1846
1847 #### `unix2dos`
1848
1849 Returns the DOS version of a given string. Useful when using a File resource with a cross-platform template.
1850
1851 *Type*: rvalue.
1852
1853 ```puppet
1854 file { $config_file:
1855   ensure  => file,
1856   content => unix2dos(template('my_module/settings.conf.erb')),
1857 }
1858 ```
1859
1860 See also [dos2unix](#dos2unix).
1861
1862 #### `upcase`
1863
1864 Converts an object, array, or hash of objects to uppercase. Objects to be converted must respond to upcase.
1865
1866 For example, `upcase('abcd')` returns 'ABCD'.
1867
1868 *Type*: rvalue.
1869
1870 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1871
1872 #### `uriescape`
1873
1874 URLEncodes a string or array of strings.
1875
1876 Arguments: Either a single string or an array of strings.
1877
1878 *Type*: rvalue.
1879
1880 *Note:* This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater.
1881
1882 #### `validate_absolute_path`
1883
1884 Validates that a given string represents an absolute path in the filesystem. Works for Windows and Unix style paths.
1885
1886 The following values pass:
1887
1888 ```puppet
1889 $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet'
1890 validate_absolute_path($my_path)
1891 $my_path2 = '/var/lib/puppet'
1892 validate_absolute_path($my_path2)
1893 $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet','C:/Program Files/Puppet Labs/Puppet']
1894 validate_absolute_path($my_path3)
1895 $my_path4 = ['/var/lib/puppet','/usr/share/puppet']
1896 validate_absolute_path($my_path4)
1897 ```
1898
1899 The following values fail, causing compilation to terminate:
1900
1901 ```puppet
1902 validate_absolute_path(true)
1903 validate_absolute_path('../var/lib/puppet')
1904 validate_absolute_path('var/lib/puppet')
1905 validate_absolute_path([ 'var/lib/puppet', '/var/foo' ])
1906 validate_absolute_path([ '/var/lib/puppet', 'var/foo' ])
1907 $undefined = `undef`
1908 validate_absolute_path($undefined)
1909 ```
1910
1911 *Type*: statement.
1912
1913 #### `validate_array`
1914
1915 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1916
1917 Validates that all passed values are array data structures. Terminates catalog compilation if any value fails this check.
1918
1919 The following values pass:
1920
1921 ```puppet
1922 $my_array = [ 'one', 'two' ]
1923 validate_array($my_array)
1924 ```
1925
1926 The following values fail, causing compilation to terminate:
1927
1928 ```puppet
1929 validate_array(true)
1930 validate_array('some_string')
1931 $undefined = `undef`
1932 validate_array($undefined)
1933 ```
1934
1935 *Type*: statement.
1936
1937 #### `validate_augeas`
1938
1939 Validates a string using an Augeas lens.
1940
1941 Arguments:
1942
1943 * The string to test, as the first argument.
1944 * The name of the Augeas lens to use, as the second argument.
1945 * Optionally, a list of paths which should **not** be found in the file, as a third argument.
1946 * Optionally, an error message to raise and show to the user, as a fourth argument.
1947
1948 If Augeas fails to parse the string with the lens, the compilation terminates with a parse error.
1949
1950 The `$file` variable points to the location of the temporary file being tested in the Augeas tree.
1951
1952 For example, to make sure your $passwdcontent never contains user `foo`, include the third argument:
1953
1954 ```puppet
1955 validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo'])
1956 ```
1957
1958 To raise and display an error message, include the fourth argument:
1959
1960 ```puppet
1961 validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas')
1962 ```
1963
1964 *Type*: statement.
1965
1966 #### `validate_bool`
1967
1968 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
1969
1970 Validates that all passed values are either `true` or `false`.
1971 Terminates catalog compilation if any value fails this check.
1972
1973 The following values pass:
1974
1975 ```puppet
1976 $iamtrue = true
1977 validate_bool(true)
1978 validate_bool(true, true, false, $iamtrue)
1979 ```
1980
1981 The following values fail, causing compilation to terminate:
1982
1983 ```puppet
1984 $some_array = [ true ]
1985 validate_bool("false")
1986 validate_bool("true")
1987 validate_bool($some_array)
1988 ```
1989
1990 *Type*: statement.
1991
1992 #### `validate_cmd`
1993
1994 Validates a string with an external command.
1995
1996 Arguments:
1997 * The string to test, as the first argument.
1998 * The path to a test command, as the second argument. This argument takes a % as a placeholder for the file path (if no % placeholder is given, defaults to the end of the command). If the command is launched against a tempfile containing the passed string, or returns a non-null value, compilation will terminate with a parse error.
1999 * Optionally, an error message to raise and show to the user, as a third argument.
2000
2001 ```puppet
2002 # Defaults to end of path
2003 validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content')
2004 ```
2005
2006 ```puppet
2007 # % as file location
2008 validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content')
2009 ```
2010
2011 *Type*: statement.
2012
2013 #### `validate_domain_name`
2014
2015 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2016
2017 Validate that all values passed are syntactically correct domain names. Aborts catalog compilation if any value fails this check.
2018
2019 The following values pass:
2020
2021 ~~~
2022 $my_domain_name = 'server.domain.tld'
2023 validate_domain_name($my_domain_name)
2024 validate_domain_name('domain.tld', 'puppet.com', $my_domain_name)
2025 ~~~
2026
2027 The following values fail, causing compilation to abort:
2028
2029 ~~~
2030 validate_domain_name(1)
2031 validate_domain_name(true)
2032 validate_domain_name('invalid domain')
2033 validate_domain_name('-foo.example.com')
2034 validate_domain_name('www.example.2com')
2035 ~~~
2036
2037 *Type*: statement.
2038
2039 #### `validate_email_address`
2040
2041 Validate that all values passed are valid email addresses. Fail compilation if any value fails this check.
2042
2043 The following values will pass:
2044
2045 ~~~
2046 $my_email = "waldo@gmail.com"
2047 validate_email_address($my_email)
2048 validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email)
2049 ~~~
2050
2051 The following values will fail, causing compilation to abort:
2052
2053 ~~~
2054 $some_array = [ 'bad_email@/d/efdf.com' ]
2055 validate_email_address($some_array)
2056 ~~~
2057
2058 *Type*: statement.
2059
2060 #### `validate_hash`
2061
2062 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2063
2064 Validates that all passed values are hash data structures. Terminates catalog compilation if any value fails this check.
2065
2066 The following values will pass:
2067
2068 ```puppet
2069 $my_hash = { 'one' => 'two' }
2070 validate_hash($my_hash)
2071 ```
2072
2073 The following values will fail, causing compilation to terminate:
2074
2075 ```puppet
2076 validate_hash(true)
2077 validate_hash('some_string')
2078 $undefined = `undef`
2079 validate_hash($undefined)
2080 ```
2081
2082 *Type*: statement.
2083
2084 #### `validate_integer`
2085
2086 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2087
2088 Validates an integer or an array of integers. Terminates catalog compilation if any of the checks fail.
2089
2090 Arguments:
2091
2092 * An integer or an array of integers, as the first argument.
2093 * Optionally, a maximum, as the second argument. (All elements of) the first argument must be equal to or less than this maximum.
2094 * Optionally, a minimum, as the third argument. (All elements of) the first argument must be equal to or greater than than this maximum.
2095
2096 This function fails if the first argument is not an integer or array of integers, or if the second or third arguments are not convertable to an integer. However, if (and only if) a minimum is given, the second argument may be an empty string or `undef`, which serves as a placeholder to ensure the minimum check.
2097
2098 The following values pass:
2099
2100 ```puppet
2101 validate_integer(1)
2102 validate_integer(1, 2)
2103 validate_integer(1, 1)
2104 validate_integer(1, 2, 0)
2105 validate_integer(2, 2, 2)
2106 validate_integer(2, '', 0)
2107 validate_integer(2, `undef`, 0)
2108 $foo = `undef`
2109 validate_integer(2, $foo, 0)
2110 validate_integer([1,2,3,4,5], 6)
2111 validate_integer([1,2,3,4,5], 6, 0)
2112 ```
2113
2114 * Plus all of the above, but any combination of values passed as strings ('1' or "1").
2115 * Plus all of the above, but with (correct) combinations of negative integer values.
2116
2117 The following values fail, causing compilation to terminate:
2118
2119 ```puppet
2120 validate_integer(true)
2121 validate_integer(false)
2122 validate_integer(7.0)
2123 validate_integer({ 1 => 2 })
2124 $foo = `undef`
2125 validate_integer($foo)
2126 validate_integer($foobaridontexist)
2127
2128 validate_integer(1, 0)
2129 validate_integer(1, true)
2130 validate_integer(1, '')
2131 validate_integer(1, `undef`)
2132 validate_integer(1, , 0)
2133 validate_integer(1, 2, 3)
2134 validate_integer(1, 3, 2)
2135 validate_integer(1, 3, true)
2136 ```
2137
2138 * Plus all of the above, but any combination of values passed as strings (`false` or "false").
2139 * Plus all of the above, but with incorrect combinations of negative integer values.
2140 * Plus all of the above, but with non-integer items in arrays or maximum / minimum argument.
2141
2142 *Type*: statement.
2143
2144 #### `validate_ip_address`
2145
2146 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2147
2148 Validates that the argument is an IP address, regardless of whether it is an IPv4 or an IPv6 address. It also validates IP address with netmask.
2149
2150 Arguments: A string specifying an IP address.
2151
2152 The following values will pass:
2153
2154 ```puppet
2155 validate_ip_address('0.0.0.0')
2156 validate_ip_address('8.8.8.8')
2157 validate_ip_address('127.0.0.1')
2158 validate_ip_address('194.232.104.150')
2159 validate_ip_address('3ffe:0505:0002::')
2160 validate_ip_address('::1/64')
2161 validate_ip_address('fe80::a00:27ff:fe94:44d6/64')
2162 validate_ip_address('8.8.8.8/32')
2163 ```
2164
2165 The following values will fail, causing compilation to terminate:
2166
2167 ```puppet
2168 validate_ip_address(1)
2169 validate_ip_address(true)
2170 validate_ip_address(0.0.0.256)
2171 validate_ip_address('::1', {})
2172 validate_ip_address('0.0.0.0.0')
2173 validate_ip_address('3.3.3')
2174 validate_ip_address('23.43.9.22/64')
2175 validate_ip_address('260.2.32.43')
2176 ```
2177
2178
2179 #### `validate_legacy`
2180
2181 Validates a value against both a specified type and a deprecated validation function. Silently passes if both pass, errors if only one validation passes, and fails if both validations return false.
2182
2183 Arguments:
2184
2185 * The type to check the value against,
2186 * The full name of the previous validation function,
2187 * The value to be checked,
2188 * An unspecified number of arguments needed for the previous validation function.
2189
2190 Example:
2191
2192 ```puppet
2193 validate_legacy("Optional[String]", "validate_re", "Value to be validated", ["."])
2194 ```
2195
2196 This function supports updating modules from Puppet 3-style argument validation (using the stdlib `validate_*` functions) to Puppet 4 data types, without breaking functionality for those depending on Puppet 3-style validation.
2197
2198 > Note: This function is compatible only with Puppet 4.4.0 (PE 2016.1) and later.
2199
2200 ##### For module users
2201
2202 If you are running Puppet 4, the `validate_legacy` function can help you find and resolve deprecated Puppet 3 `validate_*` functions. These functions are deprecated as of stdlib version 4.13 and will be removed in a future version of stdlib.
2203
2204 Puppet 4 allows improved defined type checking using [data types](https://docs.puppet.com/puppet/latest/reference/lang_data.html). Data types avoid some of the problems with Puppet 3's `validate_*` functions, which were sometimes inconsistent. For example, [validate_numeric](#validate_numeric) unintentionally allowed not only numbers, but also arrays of numbers or strings that looked like numbers.
2205
2206 If you run Puppet 4 and use modules with deprecated `validate_*` functions, you might encounter deprecation messages. The `validate_legacy` function makes these differences visible and makes it easier to move to the clearer Puppet 4 syntax.
2207
2208 The deprecation messages you get can vary, depending on the modules and data that you use. These deprecation messages appear by default only in Puppet 4:
2209
2210 * `Notice: Accepting previously invalid value for target type '<type>'`: This message is informational only. You're using values that are allowed by the new type, but would have been invalid by the old validation function.
2211 * `Warning: This method is deprecated, please use the stdlib validate_legacy function`: The module has not yet upgraded to `validate_legacy`. Use the [deprecation](#deprecation) options to silence warnings for now, or submit a fix with the module's developer. See the information [for module developers](#for-module-developers) below for how to fix the issue.
2212 * `Warning: validate_legacy(<function>) expected <type> value, got <actual type>_`: Your code passes a value that was accepted by the Puppet 3-style validation, but will not be accepted by the next version of the module. Most often, you can fix this by removing quotes from numbers or booleans.
2213 * `Error: Evaluation Error: Error while evaluating a Resource Statement, Evaluation Error: Error while evaluating a Function Call, validate_legacy(<function>) expected <type> value, got <actual type>`: Your code passes a value that is not acceptable to either the new or the old style validation.
2214
2215 ##### For module developers
2216
2217 The `validate_legacy` function helps you move from Puppet 3 style validation to Puppet 4 validation without breaking functionality your module's users depend on.
2218
2219 Moving to Puppet 4 type validation allows much better defined type checking using [data types](https://docs.puppet.com/puppet/latest/reference/lang_data.html). Many of Puppet 3's `validate_*` functions have surprising holes in their validation. For example, [validate_numeric](#validate_numeric) allows not only numbers, but also arrays of numbers or strings that look like numbers, without giving you any control over the specifics.
2220
2221 For each parameter of your classes and defined types, choose a new Puppet 4 data type to use. In most cases, the new data type allows a different set of values than the original `validate_*` function. The situation then looks like this:
2222
2223 |              | `validate_` pass | `validate_` fail |
2224 | ------------ | ---------------- | ---------------- |
2225 | matches type | pass             | pass, notice     |
2226 | fails type   | pass, deprecated | fail             |
2227
2228 The code after the validation still has to handle all possible values for now, but users of your code can change their manifests to pass only values that match the new type.
2229
2230 For each `validate_*` function in stdlib, there is a matching `Stdlib::Compat::*` type that allows the appropriate set of values. See the documentation in the `types/` directory in the stdlib source code for caveats.
2231
2232 For example, given a class that should accept only numbers, like this:
2233
2234 ```puppet
2235 class example($value) {
2236   validate_numeric($value)
2237 ```
2238
2239 the resulting validation code looks like this:
2240
2241 ```puppet
2242 class example(
2243   Variant[Stdlib::Compat::Numeric, Numeric] $value
2244 ) {
2245   validate_legacy(Numeric, 'validate_numeric', $value)
2246 ```
2247
2248 Here, the type of `$value` is defined as `Variant[Stdlib::Compat::Numeric, Numeric]`, which allows any `Numeric` (the new type), as well as all values previously accepted by `validate_numeric` (through `Stdlib::Compat::Numeric`).
2249
2250 The call to `validate_legacy` takes care of triggering the correct log or fail message for you. It requires the new type, the previous validation function name, and all arguments to that function.
2251
2252 If your module still supported Puppet 3, this is a breaking change. Update your `metadata.json` requirements section to indicate that your module no longer supports Puppet 3, and bump the major version of your module. With this change, all existing tests for your module should still pass. Create additional tests for the new possible values.
2253
2254 As a breaking change, this is also a good time to call [`deprecation`](#deprecation) for any parameters you want to get rid of, or to add additional constraints on your parameters.
2255
2256 After releasing this version, you can release another breaking change release where you remove all compat types and all calls to `validate_legacy`. At that time, you can also go through your code and remove any leftovers dealing with the previously possible values.
2257
2258 Always note such changes in your CHANGELOG and README.
2259
2260 #### `validate_numeric`
2261
2262 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2263
2264 Validates a numeric value, or an array or string of numeric values. Terminates catalog compilation if any of the checks fail.
2265
2266 Arguments:
2267
2268 * A numeric value, or an array or string of numeric values.
2269 * Optionally, a maximum value. (All elements of) the first argument has to be less or equal to this max.
2270 * Optionally, a minimum value. (All elements of) the first argument has to be greater or equal to this min.
2271
2272 This function fails if the first argument is not a numeric (Integer or Float) or an array or string of numerics, or if the second and third arguments are not convertable to a numeric. If, and only if, a minimum is given, the second argument can be an empty string or `undef`, which serves as a placeholder to ensure the minimum check.
2273
2274 For passing and failing usage, see [`validate_integer`](#validate-integer). The same values pass and fail, except that `validate_numeric` also allows floating point values.
2275
2276 *Type*: statement.
2277
2278 #### `validate_re`
2279
2280 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2281
2282 Performs simple validation of a string against one or more regular expressions.
2283
2284 Arguments:
2285
2286 * The string to test, as the first argument. If this argument is not a string, compilation terminates. Use quotes to force stringification.
2287 * A stringified regular expression (without the // delimiters) or an array of regular expressions, as the second argument.
2288 * Optionally, the error message raised and shown to the user, as a third argument.
2289
2290 If none of the regular expressions in the second argument match the string passed in the first argument, compilation terminates with a parse error.
2291
2292 The following strings validate against the regular expressions:
2293
2294 ```puppet
2295 validate_re('one', '^one$')
2296 validate_re('one', [ '^one', '^two' ])
2297 ```
2298
2299 The following string fails to validate, causing compilation to terminate:
2300
2301 ```puppet
2302 validate_re('one', [ '^two', '^three' ])
2303 ```
2304
2305 To set the error message:
2306
2307 ```puppet
2308 validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7')
2309 ```
2310
2311 To force stringification, use quotes:
2312
2313   ```
2314   validate_re("${::operatingsystemmajrelease}", '^[57]$')
2315   ```
2316
2317 *Type*: statement.
2318
2319 #### `validate_slength`
2320
2321 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2322
2323 Validates that a string (or an array of strings) is less than or equal to a specified length
2324
2325 Arguments:
2326
2327 * A string or an array of strings, as a first argument.
2328 * A numeric value for maximum length, as a second argument.
2329 * Optionally, a numeric value for minimum length, as a third argument.
2330
2331   The following values pass:
2332
2333 ```puppet
2334 validate_slength("discombobulate",17)
2335 validate_slength(["discombobulate","moo"],17)
2336 validate_slength(["discombobulate","moo"],17,3)
2337 ```
2338
2339 The following values fail:
2340
2341 ```puppet
2342 validate_slength("discombobulate",1)
2343 validate_slength(["discombobulate","thermometer"],5)
2344 validate_slength(["discombobulate","moo"],17,10)
2345 ```
2346
2347 *Type*: statement.
2348
2349 #### `validate_string`
2350
2351 **Deprecated. Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy).**
2352
2353 Validates that all passed values are string data structures. Aborts catalog compilation if any value fails this check.
2354
2355 The following values pass:
2356
2357 ```puppet
2358 $my_string = "one two"
2359 validate_string($my_string, 'three')
2360 ```
2361
2362 The following values fail, causing compilation to terminate:
2363
2364 ```puppet
2365 validate_string(true)
2366 validate_string([ 'some', 'array' ])
2367 ```
2368
2369 *Note:* validate_string(`undef`) will not fail in this version of the functions API.
2370
2371 Instead, use:
2372
2373   ```
2374   if $var == `undef` {
2375     fail('...')
2376   }
2377   ```
2378
2379 *Type*: statement.
2380
2381 #### `validate_x509_rsa_key_pair`
2382
2383 Validates a PEM-formatted X.509 certificate and private key using OpenSSL.
2384 Verifies that the certificate's signature was created from the supplied key.
2385
2386 Fails catalog compilation if any value fails this check.
2387
2388 Arguments:
2389
2390 * An X.509 certificate as the first argument.
2391 * An RSA private key, as the second argument.
2392
2393 ```puppet
2394 validate_x509_rsa_key_pair($cert, $key)
2395 ```
2396
2397 *Type*: statement.
2398
2399 #### `values`
2400
2401 Returns the values of a given hash.
2402
2403 For example, given `$hash = {'a'=1, 'b'=2, 'c'=3} values($hash)` returns [1,2,3].
2404
2405 *Type*: rvalue.
2406
2407 #### `values_at`
2408
2409 Finds values inside an array based on location.
2410
2411 Arguments:
2412
2413 * The array you want to analyze, as the first argument.
2414 * Any combination of the following values, as the second argument:
2415   * A single numeric index
2416   * A range in the form of 'start-stop' (eg. 4-9)
2417   * An array combining the above
2418
2419 For example:
2420
2421 * `values_at(['a','b','c'], 2)` returns ['c'].
2422 * `values_at(['a','b','c'], ["0-1"])` returns ['a','b'].
2423 * `values_at(['a','b','c','d','e'], [0, "2-3"])` returns ['a','c','d'].
2424
2425 *Type*: rvalue.
2426
2427 #### `zip`
2428
2429 Takes one element from first array given and merges corresponding elements from second array given. This generates a sequence of n-element arrays, where *n* is one more than the count of arguments. For example, `zip(['1','2','3'],['4','5','6'])` results in ["1", "4"], ["2", "5"], ["3", "6"]. *Type*: rvalue.
2430
2431 ## Limitations
2432
2433 As of Puppet Enterprise 3.7, the stdlib module is no longer included in PE. PE users should install the most recent release of stdlib for compatibility with Puppet modules.
2434
2435 ### Version Compatibility
2436
2437 Versions | Puppet 2.6 | Puppet 2.7 | Puppet 3.x | Puppet 4.x |
2438 :---------------|:-----:|:---:|:---:|:----:
2439 **stdlib 2.x**  | **yes** | **yes** | no | no
2440 **stdlib 3.x**  | no    | **yes**  | **yes** | no
2441 **stdlib 4.x**  | no    | **yes**  | **yes** | no
2442 **stdlib 4.6+**  | no    | **yes**  | **yes** | **yes**
2443 **stdlib 5.x**  | no    | no  | **yes**  | **yes**
2444
2445 **stdlib 5.x**: When released, stdlib 5.x will drop support for Puppet 2.7.x. Please see [this discussion](https://github.com/puppetlabs/puppetlabs-stdlib/pull/176#issuecomment-30251414).
2446
2447 ## Development
2448
2449 Puppet Labs modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We can’t access the huge number of platforms and myriad hardware, software, and deployment configurations that Puppet is intended to serve. We want to keep it as easy as possible to contribute changes so that our modules work in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things. For more information, see our [module contribution guide](https://docs.puppetlabs.com/forge/contributing.html).
2450
2451 To report or research a bug with any part of this module, please go to
2452 [http://tickets.puppetlabs.com/browse/MODULES](http://tickets.puppetlabs.com/browse/MODULES).
2453
2454 ## Contributors
2455
2456 The list of contributors can be found at: [https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors](https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors).