source: other-projects/hathitrust/vagrant-hadoop-cluster/trunk/modules/stdlib/README.markdown@ 30903

Last change on this file since 30903 was 30903, checked in by davidb, 7 years ago

Vagrant provisioning files for a 4-node Hadoop cluster. See README.txt for more details

File size: 60.2 KB
Line 
1# stdlib
2
3#### Table of Contents
4
51. [Overview](#overview)
62. [Module Description - What the module does and why it is useful](#module-description)
73. [Setup - The basics of getting started with stdlib](#setup)
84. [Usage - Configuration options and additional functionality](#usage)
95. [Reference - An under-the-hood peek at what the module is doing and how](#reference)
105. [Limitations - OS compatibility, etc.](#limitations)
116. [Development - Guide for contributing to the module](#development)
12
13## Overview
14
15Adds a standard library of resources for Puppet modules.
16
17## Module Description
18
19This module provides a standard library of resources for the development of Puppet modules. Puppet modules make heavy use of this standard library. The stdlib module adds the following resources to Puppet:
20
21 * Stages
22 * Facts
23 * Functions
24 * Defined resource types
25 * Data Types
26 * Providers
27
28> *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.
29
30## Setup
31
32Installing the stdlib module adds the functions, facts, and resources of this standard library to Puppet.
33
34## Usage
35
36After you've installed stdlib, all of its functions, facts, and resources are available for module use or development.
37
38If you want to use a standardized set of run stages for Puppet, `include stdlib` in your manifest.
39
40* `stdlib`: 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
44The `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 ~~~
58 node default {
59 include stdlib
60 class { java: stage => 'runtime' }
61 }
62 ~~~
63
64## Reference
65
66### Classes
67
68#### Public Classes
69
70 The stdlib class has no parameters.
71
72#### Private Classes
73
74* `stdlib::stages`: Manages a standard set of run stages for Puppet. It is managed by the stdlib class and should not be declared independently.
75
76### Resource Types
77
78#### `file_line`
79
80Ensures 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.
81
82Example:
83
84 file_line { 'sudo_rule':
85 path => '/etc/sudoers',
86 line => '%sudo ALL=(ALL) ALL',
87 }
88
89 file_line { 'sudo_rule_nopw':
90 path => '/etc/sudoers',
91 line => '%sudonopw ALL=(ALL) NOPASSWD: ALL',
92 }
93
94In this example, Puppet ensures that both of the specified lines are contained in the file `/etc/sudoers`.
95
96Match Example:
97
98 file_line { 'bashrc_proxy':
99 ensure => present,
100 path => '/etc/bashrc',
101 line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
102 match => '^export\ HTTP_PROXY\=',
103 }
104
105In this code example, `match` looks for a line beginning with export followed by HTTP_PROXY and replaces it with the value in line.
106
107Match Example With `ensure => absent`:
108
109 file_line { 'bashrc_proxy':
110 ensure => absent,
111 path => '/etc/bashrc',
112 line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
113 match => '^export\ HTTP_PROXY\=',
114 match_for_absence => true,
115 }
116
117In this code example, `match` looks for a line beginning with export
118followed by HTTP_PROXY and delete it. If multiple lines match, an
119error will be raised unless the `multiple => true` parameter is set.
120
121**Autorequires:** If Puppet is managing the file that contains the line being managed, the `file_line` resource autorequires that file.
122
123##### Parameters
124
125All parameters are optional, unless otherwise noted.
126
127* `after`: Specifies the line after which Puppet adds any new lines using a regular expression. (Existing lines are added in place.) Valid options: String containing a regex. Default: Undefined.
128* `ensure`: Ensures whether the resource is present. Valid options: 'present', 'absent'. Default: 'present'.
129* `line`: **Required.** Sets the line to be added to the file located by the `path` parameter. Valid options: String. Default: Undefined.
130* `match`: Specifies a regular expression to run 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. Valid options: String containing a regex. Default: Undefined.
131* `match_for_absence`: An optional value to determine if match should be applied when `ensure => absent`. If set to true and match is set, the line that matches match will be 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`. Default: false.
132* `multiple`: Determines if `match` and/or `after` can change multiple lines. If set to false, an exception will be raised if more than one line matches. Valid options: 'true', 'false'. Default: Undefined.
133* `name`: Sets the name to use as the identity of the resource. This is necessary if you want the resource namevar to differ from the supplied `title` of the resource. Valid options: String. Default: Undefined.
134* `path`: **Required.** Defines the file in which Puppet will ensure the line specified by `line`. Must be an absolute path to the file.
135* `replace`: Defines whether the resource will overwrite an existing line that matches the `match` parameter. If set to false and a line is found matching the `match` param, the line will not be placed in the file. Valid options: true, false, yes, no. Default: true
136
137### Data Types
138
139#### `Stdlib::Absolutepath`
140
141A strict absolute path type. Uses a Variant of Unixpath and Windowspath types.
142
143Acceptable input examples: /var/log
144 /usr2/username/bin:/usr/local/bin:/usr/bin:.
145 C:\\WINDOWS\\System32
146Unacceptable input example: ../relative_path
147
148#### `Stdlib::Httpsurl`
149
150Matches https URLs.
151
152Acceptable input example: https://hello.com
153Unacceptable input example: httds://notquiteright.org
154
155#### `Stdlib::Httpurl`
156
157Matches both https and http URLs.
158
159Acceptable input example: https://hello.com
160 http://hello.com
161Unacceptable input example: httds://notquiteright.org
162
163#### `Stdlib::Unixpath`
164
165Matches paths on Unix type Operating Systems.
166
167Acceptable input example: /usr2/username/bin:/usr/local/bin:/usr/bin:.
168 /var/tmp
169Unacceptable input example: C:/whatever
170
171#### `Stdlib::Windowspath`
172
173Matches paths on Windows Operating systems.
174
175Acceptable input example: C:\\WINDOWS\\System32
176 C:\\
177 \\\\host\\windows
178Unacceptable input example: /usr2/username/bin:/usr/local/bin:/usr/bin:.
179
180### Functions
181
182#### `abs`
183
184Returns the absolute value of a number; for example, '-34.56' becomes '34.56'. Takes a single integer and float value as an argument. *Type*: rvalue.
185
186#### `any2array`
187
188Converts any object to an array containing that object. Empty argument lists are converted to an empty array. Arrays are left untouched. Hashes are converted to arrays of alternating keys and values. *Type*: rvalue.
189
190#### `base64`
191
192Converts 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')
193
194For backward compatibility, `method` will be set as `default` if not specified.
195
196*Examples:*
197~~~
198base64('encode', 'hello')
199base64('encode', 'hello', 'default')
200# return: "aGVsbG8=\n"
201
202base64('encode', 'hello', 'strict')
203# return: "aGVsbG8="
204
205base64('decode', 'aGVsbG8=')
206base64('decode', 'aGVsbG8=\n')
207base64('decode', 'aGVsbG8=', 'default')
208base64('decode', 'aGVsbG8=\n', 'default')
209base64('decode', 'aGVsbG8=', 'strict')
210# return: "hello"
211
212base64('encode', 'https://puppetlabs.com', 'urlsafe')
213# return: "aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ=="
214
215base64('decode', 'aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ==', 'urlsafe')
216# return: "https://puppetlabs.com"
217~~~
218
219*Type*: rvalue.
220
221#### `basename`
222
223Returns the `basename` of a path (optionally stripping an extension). For example:
224 * ('/path/to/a/file.ext') returns 'file.ext'
225 * ('relative/path/file.ext') returns 'file.ext'
226 * ('/path/to/a/file.ext', '.ext') returns 'file'
227
228*Type*: rvalue.
229
230#### `bool2num`
231
232Converts a boolean to a number. Converts values:
233 * 'false', 'f', '0', 'n', and 'no' to 0.
234 * 'true', 't', '1', 'y', and 'yes' to 1.
235 Requires a single boolean or string as an input. *Type*: rvalue.
236
237#### `bool2str`
238
239Converts 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'.
240
241*Examples:*
242~~~
243bool2str(true) => 'true'
244bool2str(true, 'yes', 'no') => 'yes'
245bool2str(false, 't', 'f') => 'f'
246~~~
247
248Requires a single boolean as input. *Type*: rvalue.
249
250#### `capitalize`
251
252Capitalizes the first character of a string or array of strings and lowercases the remaining characters of each string. Requires either a single string or an array as an input. *Type*: rvalue.
253
254#### `ceiling`
255
256Returns the smallest integer greater than or equal to the argument. Takes a single numeric value as an argument. *Type*: rvalue.
257
258#### `chomp`
259
260Removes the record separator from the end of a string or an array of strings; for example, 'hello\n' becomes 'hello'. Requires a single string or array as an input. *Type*: rvalue.
261
262#### `chop`
263
264Returns 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. If you want to merely remove record separators, then you should use the `chomp` function. Requires a string or an array of strings as input. *Type*: rvalue.
265
266#### `clamp`
267
268Keeps value within the range [Min, X, Max] by sort based on integer value (order of params doesn't matter). Takes strings, arrays or numerics. Strings are converted and compared numerically. Arrays of values are flattened into a list for further handling. For example:
269 * `clamp('24', [575, 187])` returns 187.
270 * `clamp(16, 88, 661)` returns 88.
271 * `clamp([4, 3, '99'])` returns 4.
272 *Type*: rvalue.
273
274#### `concat`
275
276Appends the contents of multiple arrays onto the first array given. For example:
277 * `concat(['1','2','3'],'4')` returns ['1','2','3','4'].
278 * `concat(['1','2','3'],'4',['5','6','7'])` returns ['1','2','3','4','5','6','7'].
279 *Type*: rvalue.
280
281#### `convert_base`
282
283Converts a given integer or base 10 string representing an integer to a specified base, as a string. For example:
284 * `convert_base(5, 2)` results in: '101'
285 * `convert_base('254', '16')` results in: 'fe'
286
287#### `count`
288
289If called with only an array, it counts the number of elements that are **not** nil/undef. If called with a second argument, counts the number of elements in an array that matches the second argument. *Type*: rvalue.
290
291#### `deep_merge`
292
293Recursively merges two or more hashes together and returns the resulting hash.
294 $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } }
295 $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } }
296 $merged_hash = deep_merge($hash1, $hash2)
297
298The resulting hash is equivalent to:
299 $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } }
300
301When there is a duplicate key that is a hash, they are recursively merged. When there is a duplicate key that is not a hash, the key in the rightmost hash will "win.".
302*Type*: rvalue, rvalue.
303
304#### `defined_with_params`
305
306Takes 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.
307
308 ~~~
309 user { 'dan':
310 ensure => present,
311 }
312
313 if ! defined_with_params(User[dan], {'ensure' => 'present' }) {
314 user { 'dan': ensure => present, }
315 }
316 ~~~
317
318*Type*: rvalue.
319
320#### `delete`
321
322Deletes all instances of a given element from an array, substring from a string, or key from a hash.
323
324For example, `delete(['a','b','c','b'], 'b')` returns ['a','c']; `delete('abracadabra', 'bra')` returns 'acada'. `delete({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}, `delete(['ab', 'b'], 'b')` returns ['ab'].
325
326*Type*: rvalue.
327
328#### `delete_at`
329
330Deletes a determined indexed value from an array. For example, `delete_at(['a','b','c'], 1)` returns ['a','c']. *Type*: rvalue.
331
332#### `delete_regex`
333
334Deletes all instances of a given element from an array or hash that match a provided regular expression. A string will be treated as a one-item array.
335
336For example, `delete_regex(['a','b','c','b'], 'b')` returns ['a','c']; `delete_regex({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1}, `delete_regex(['abf', 'ab', 'ac'], '^ab.*')` returns ['ac']. `delete_regex(['ab', 'b'], 'b')` returns ['ab'].
337
338*Type*: rvalue.
339
340#### `delete_values`
341
342Deletes all instances of a given value from a hash. For example, `delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B')` returns {'a'=>'A','c'=>'C','B'=>'D'} *Type*: rvalue.
343
344#### `delete_undef_values`
345
346Deletes all instances of the undef value from an array or hash. For example, `$hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false})` returns {a => 'A', b => '', d => false}. *Type*: rvalue.
347
348#### `deprecation`
349
350Prints deprecation warnings and logs a warning once for a given key:
351
352```
353deprecation(key, message)
354```
355
356* key: to keep the number of messages low, during the lifetime of a puppet process, only one message per key is logged.
357* message: the text to be logged.
358
359The Puppet settings '[disable_warnings](https://docs.puppet.com/puppet/latest/reference/configuration.html#disablewarnings)', '[max_deprecations](https://docs.puppet.com/puppet/latest/reference/configuration.html#maxdeprecations)', and '[strict](https://docs.puppet.com/puppet/latest/reference/configuration.html#strict)' affect this function. Set 'strict' to `error` to fail immediately with the deprecation message, `off` to output emit no messages at all, or `warning` (default) to log all warnings.
360
361Additionally you can set the environment variable `STDLIB_LOG_DEPRECATION` to decide whether or not to log deprecation warnings: if this environment variable is set to `true`, the functions log a warning, if it is set to `false`, no warnings are logged. If no value is set at all, Puppet 4 will emit warnings, while Puppet 3 will not. Using this setting is especially useful for automated tests to avoid flooding your logs before you are ready to migrate.
362
363*Type*: String, String.
364
365#### `difference`
366
367Returns 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. For example, `difference(["a","b","c"],["b","c","d"])` returns ["a"]. *Type*: rvalue.
368
369#### `dig`
370
371DEPRECATED: This function has been replaced in Puppet 4.5.0, use dig44() for backwards compatibility or use the new version.
372
373*Type*: rvalue.
374
375Retrieves 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.
376
377In 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.
378
379~~~ruby
380$data = {
381 'a' => {
382 'b' => [
383 'b1',
384 'b2',
385 'b3',
386 ]
387 }
388}
389
390$value = dig($data, ['a', 'b', 2])
391# $value = 'b3'
392
393# with all possible options
394$value = dig($data, ['a', 'b', 2], 'not_found')
395# $value = 'b3'
396
397# using the default value
398$value = dig($data, ['a', 'b', 'c', 'd'], 'not_found')
399# $value = 'not_found'
400~~~
401
4021. **$data** The data structure we are working with.
4032. **['a', 'b', 2]** The path array.
4043. **'not_found'** The default value. It will be returned if nothing is found.
405 (optional, defaults to *undef*)
406
407#### `dig44`
408
409*Type*: rvalue.
410
411Retrieves 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.
412
413In 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.
414
415~~~ruby
416$data = {
417 'a' => {
418 'b' => [
419 'b1',
420 'b2',
421 'b3',
422 ]
423 }
424}
425
426$value = dig44($data, ['a', 'b', 2])
427# $value = 'b3'
428
429# with all possible options
430$value = dig44($data, ['a', 'b', 2], 'not_found')
431# $value = 'b3'
432
433# using the default value
434$value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found')
435# $value = 'not_found'
436~~~
437
4381. **$data** The data structure we are working with.
4392. **['a', 'b', 2]** The path array.
4403. **'not_found'** The default value. It will be returned if nothing is found.
441 (optional, defaults to *undef*)
442
443#### `dirname`
444
445Returns the `dirname` of a path. For example, `dirname('/path/to/a/file.ext')` returns '/path/to/a'. *Type*: rvalue.
446
447#### `dos2unix`
448
449Returns the Unix version of the given string. Very useful when using a File resource with a cross-platform template. *Type*: rvalue.
450
451~~~
452file{$config_file:
453 ensure => file,
454 content => dos2unix(template('my_module/settings.conf.erb')),
455}
456~~~
457
458See also [unix2dos](#unix2dos).
459
460#### `downcase`
461
462Converts the case of a string or of all strings in an array to lowercase. *Type*: rvalue.
463
464#### `empty`
465
466Returns 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. *Type*: rvalue.
467
468#### `enclose_ipv6`
469
470Takes an array of ip addresses and encloses the ipv6 addresses with square brackets. *Type*: rvalue.
471
472#### `ensure_packages`
473
474Takes a list of packages array/hash and only installs them if they don't already exist. It optionally takes a hash as a second parameter to be passed as the third argument to the `ensure_resource()` or `ensure_resources()` function. *Type*: statement.
475
476For Array:
477
478 ensure_packages(['ksh','openssl'], {'ensure' => 'present'})
479
480For Hash:
481
482 ensure_packages({'ksh' => { ensure => '20120801-1' } , 'mypackage' => { source => '/tmp/myrpm-1.0.0.x86_64.rpm', provider => "rpm" }}, {'ensure' => 'present'})
483
484#### `ensure_resource`
485
486Takes a resource type, title, and a hash of attributes that describe the resource(s).
487
488~~~
489user { 'dan':
490 ensure => present,
491}
492~~~
493
494This example only creates the resource if it does not already exist:
495
496 `ensure_resource('user', 'dan', {'ensure' => 'present' })`
497
498If 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.
499
500An 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.
501
502 `ensure_resource('user', ['dan','alex'], {'ensure' => 'present'})`
503
504*Type*: statement.
505
506#### `ensure_resources`
507
508Takes a resource type, title (only hash), and a hash of attributes that describe the resource(s).
509
510~~~
511user { 'dan':
512 gid => 'mygroup',
513 ensure => present,
514}
515
516ensure_resources($user)
517~~~
518
519An hash of resources should be passed in and each will be created with the type and parameters specified if it doesn't already exist:
520
521 ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'})
522
523From Hiera Backend:
524
525~~~
526userlist:
527 dan:
528 gid: 'mygroup'
529 uid: '600'
530 alex:
531 gid: 'mygroup'
532
533ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'})
534~~~
535
536### `flatten`
537
538Flattens deeply nested arrays and returns a single flat array as a result. For example, `flatten(['a', ['b', ['c']]])` returns ['a','b','c']. *Type*: rvalue.
539
540#### `floor`
541
542Takes a single numeric value as an argument, and returns the largest integer less than or equal to the argument. *Type*: rvalue.
543
544#### `fqdn_rand_string`
545
546Generates a random alphanumeric string using an optionally-specified character set (default is alphanumeric), combining the `$fqdn` fact and an optional seed for repeatable randomness.
547
548*Usage:*
549~~~
550fqdn_rand_string(LENGTH, [CHARSET], [SEED])
551~~~
552*Examples:*
553~~~
554fqdn_rand_string(10)
555fqdn_rand_string(10, 'ABCDEF!@#$%^')
556fqdn_rand_string(10, '', 'custom seed')
557~~~
558
559*Type*: rvalue.
560
561#### `fqdn_rotate`
562
563Rotates an array or string a random number of times, combining the `$fqdn` fact and an optional seed for repeatable randomness.
564
565*Usage:*
566
567~~~
568fqdn_rotate(VALUE, [SEED])
569~~~
570
571*Examples:*
572
573~~~
574fqdn_rotate(['a', 'b', 'c', 'd'])
575fqdn_rotate('abcd')
576fqdn_rotate([1, 2, 3], 'custom seed')
577~~~
578
579*Type*: rvalue.
580
581#### `get_module_path`
582
583Returns the absolute path of the specified module for the current environment.
584
585 `$module_path = get_module_path('stdlib')`
586
587*Type*: rvalue.
588
589#### `getparam`
590
591Takes a resource reference and the name of the parameter, and returns the value of the resource's parameter.
592
593For example, the following returns 'param_value':
594
595 ~~~
596 define example_resource($param) {
597 }
598
599 example_resource { "example_resource_instance":
600 param => "param_value"
601 }
602
603 getparam(Example_resource["example_resource_instance"], "param")
604 ~~~
605
606*Type*: rvalue.
607
608#### `getvar`
609
610Looks up a variable in a remote namespace.
611
612For example:
613
614 ~~~
615 $foo = getvar('site::data::foo')
616 # Equivalent to $foo = $site::data::foo
617 ~~~
618
619This is useful if the namespace itself is stored in a string:
620
621 ~~~
622 $datalocation = 'site::data'
623 $bar = getvar("${datalocation}::bar")
624 # Equivalent to $bar = $site::data::bar
625 ~~~
626
627*Type*: rvalue.
628
629#### `grep`
630
631Searches through an array and returns any elements that match the provided regular expression. For example, `grep(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['aaa','aaaddd']. *Type*: rvalue.
632
633#### `has_interface_with`
634
635Returns a boolean based on kind and value:
636 * macaddress
637 * netmask
638 * ipaddress
639 * network
640
641*Examples:*
642
643 ~~~
644 has_interface_with("macaddress", "x:x:x:x:x:x")
645 has_interface_with("ipaddress", "127.0.0.1") => true
646 ~~~
647
648If no kind is given, then the presence of the interface is checked:
649
650 ~~~
651 has_interface_with("lo") => true
652 ~~~
653
654*Type*: rvalue.
655
656#### `has_ip_address`
657
658Returns '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. *Type*: rvalue.
659
660#### `has_ip_network`
661
662Returns '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. *Type*: rvalue.
663
664#### `has_key`
665
666Determines if a hash has a certain key value.
667
668*Example*:
669
670 ~~~
671 $my_hash = {'key_one' => 'value_one'}
672 if has_key($my_hash, 'key_two') {
673 notice('we will not reach here')
674 }
675 if has_key($my_hash, 'key_one') {
676 notice('this will be printed')
677 }
678 ~~~
679
680*Type*: rvalue.
681
682#### `hash`
683
684Converts an array into a hash. For example, `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}. *Type*: rvalue.
685
686#### `intersection`
687
688Returns an array an intersection of two. For example, `intersection(["a","b","c"],["b","c","d"])` returns ["b","c"]. *Type*: rvalue.
689
690#### `is_a`
691
692Boolean 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.
693
694 ~~~
695 foo = 3
696 $bar = [1,2,3]
697 $baz = 'A string!'
698
699 if $foo.is_a(Integer) {
700 notify { 'foo!': }
701 }
702 if $bar.is_a(Array) {
703 notify { 'bar!': }
704 }
705 if $baz.is_a(String) {
706 notify { 'baz!': }
707 }
708 ~~~
709
710See the [the Puppet type system](https://docs.puppetlabs.com/references/latest/type.html#about-resource-types) for more information about types.
711See the [`assert_type()`](https://docs.puppetlabs.com/references/latest/function.html#asserttype) function for flexible ways to assert the type of a value.
712
713#### `is_absolute_path`
714
715Returns 'true' if the given path is absolute. *Type*: rvalue.
716
717#### `is_array`
718
719Returns 'true' if the variable passed to this function is an array. *Type*: rvalue.
720
721#### `is_bool`
722
723Returns 'true' if the variable passed to this function is a boolean. *Type*: rvalue.
724
725#### `is_domain_name`
726
727Returns 'true' if the string passed to this function is a syntactically correct domain name. *Type*: rvalue.
728
729#### `is_float`
730
731Returns 'true' if the variable passed to this function is a float. *Type*: rvalue.
732
733#### `is_function_available`
734
735Accepts 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. *Type*: rvalue.
736
737#### `is_hash`
738
739Returns 'true' if the variable passed to this function is a hash. *Type*: rvalue.
740
741#### `is_integer`
742
743Returns 'true' if the variable returned to this string is an integer. *Type*: rvalue.
744
745#### `is_ip_address`
746
747Returns 'true' if the string passed to this function is a valid IP address. *Type*: rvalue.
748
749#### `is_ipv6_address`
750
751Returns 'true' if the string passed to this function is a valid IPv6 address. *Type*: rvalue.
752
753#### `is_ipv4_address`
754
755Returns 'true' if the string passed to this function is a valid IPv4 address. *Type*: rvalue.
756
757#### `is_mac_address`
758
759Returns 'true' if the string passed to this function is a valid MAC address. *Type*: rvalue.
760
761#### `is_numeric`
762
763Returns 'true' if the variable passed to this function is a number. *Type*: rvalue.
764
765#### `is_string`
766
767Returns 'true' if the variable passed to this function is a string. *Type*: rvalue.
768
769#### `join`
770
771Joins an array into a string using a separator. For example, `join(['a','b','c'], ",")` results in: "a,b,c". *Type*: rvalue.
772
773#### `join_keys_to_values`
774
775Joins each key of a hash to that key's corresponding value with a separator. Keys and values are cast to strings. The return value is an array in which each element is one joined key/value pair. For example, `join_keys_to_values({'a'=>1,'b'=>2}, " is ")` results in ["a is 1","b is 2"]. *Type*: rvalue.
776
777#### `keys`
778
779Returns the keys of a hash as an array. *Type*: rvalue.
780
781#### `loadyaml`
782
783Loads a YAML file containing an array, string, or hash, and returns the data in the corresponding native data type.
784
785For example:
786
787 ~~~
788 $myhash = loadyaml('/etc/puppet/data/myhash.yaml')
789 ~~~
790
791The second parameter will be returned if the file was not found or could not be parsed.
792
793For example:
794
795 ~~~
796 $myhash = loadyaml('no-file.yaml', {'default'=>'value'})
797 ~~~
798
799*Type*: rvalue.
800
801#### `loadjson`
802
803Loads a JSON file containing an array, string, or hash, and returns the data in the corresponding native data type.
804
805For example:
806
807 ~~~
808 $myhash = loadjson('/etc/puppet/data/myhash.json')
809 ~~~
810
811The second parameter will be returned if the file was not found or could not be parsed.
812
813For example:
814
815 ~~~
816 $myhash = loadjson('no-file.json', {'default'=>'value'})
817 ~~~
818
819*Type*: rvalue.
820
821#### `load_module_metadata`
822
823Loads the metadata.json of a target module. Can be used to determine module version and authorship for dynamic support of modules.
824
825 ~~~
826 $metadata = load_module_metadata('archive')
827 notify { $metadata['author']: }
828 ~~~
829
830If you do not want to fail the catalog compilation when a module's metadata file is absent:
831
832 ~~~
833 $metadata = load_module_metadata('mysql', true)
834 if empty($metadata) {
835 notify { "This module does not have a metadata.json file.": }
836 }
837 ~~~
838
839*Type*: rvalue.
840
841#### `lstrip`
842
843Strips spaces to the left of a string. *Type*: rvalue.
844
845#### `max`
846
847Returns the highest value of all arguments. Requires at least one argument. *Type*: rvalue.
848
849#### `member`
850
851This function determines if a variable is a member of an array. The variable can be either a string, array, or fixnum. 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'. *Note*: This function does not support nested arrays. If the first argument contains nested arrays, it will not recurse through them.
852
853*Type*: rvalue.
854
855#### `merge`
856
857Merges two or more hashes together and returns the resulting hash.
858
859*Example*:
860
861 ~~~
862 $hash1 = {'one' => 1, 'two' => 2}
863 $hash2 = {'two' => 'dos', 'three' => 'tres'}
864 $merged_hash = merge($hash1, $hash2)
865 # The resulting hash is equivalent to:
866 # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'}
867 ~~~
868
869When there is a duplicate key, the key in the rightmost hash "wins." *Type*: rvalue.
870
871#### `min`
872
873Returns the lowest value of all arguments. Requires at least one argument. *Type*: rvalue.
874
875#### `num2bool`
876
877Converts 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'. *Type*: rvalue.
878
879#### `parsejson`
880
881Converts a string of JSON into the correct Puppet structure. *Type*: rvalue. The optional second argument is returned if the data was not correct.
882
883#### `parseyaml`
884
885Converts a string of YAML into the correct Puppet structure. *Type*: rvalue. The optional second argument is returned if the data was not correct.
886
887#### `pick`
888
889From 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.
890
891 ~~~
892 $real_jenkins_version = pick($::jenkins_version, '1.449')
893 ~~~
894
895*Type*: rvalue.
896
897#### `pick_default`
898
899Returns the first value in a list of values. Contrary to the `pick()` function, the `pick_default()` does not fail if all arguments are empty. This allows it to use an empty value as default. *Type*: rvalue.
900
901#### `prefix`
902
903Applies a prefix to all elements in an array, or to the keys in a hash.
904For example:
905* `prefix(['a','b','c'], 'p')` returns ['pa','pb','pc']
906* `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'pa'=>'b','pb'=>'c','pc'=>'d'}.
907
908*Type*: rvalue.
909
910#### `assert_private`
911
912Sets the current class or definition as private. Calling the class or definition from outside the current module will fail.
913
914For example, `assert_private()` called in class `foo::bar` outputs the following message if class is called from outside module `foo`:
915
916 ~~~
917 Class foo::bar is private
918 ~~~
919
920 To specify the error message you want to use:
921
922 ~~~
923 assert_private("You're not supposed to do that!")
924 ~~~
925
926*Type*: statement.
927
928#### `pw_hash`
929
930Hashes a password using the crypt function. Provides a hash usable on most POSIX systems.
931
932The first argument to this function is the password to hash. If it is undef or an empty string, this function returns undef.
933
934The 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:
935
936|Hash type |Specifier|
937|---------------------|---------|
938|MD5 |1 |
939|SHA-256 |5 |
940|SHA-512 (recommended)|6 |
941
942The third argument to this function is the salt to use.
943
944*Type*: rvalue.
945
946**Note:** this 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.
947
948#### `range`
949
950Extrapolates 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].
951
952Non-integer strings are accepted; `range("a", "c")` returns ["a","b","c"], and `range("host01", "host10")` returns ["host01", "host02", ..., "host09", "host10"].
953NB Be explicit in including trailing zeros. Otherwise the underlying ruby function will fail.
954
955Passing a third argument will cause the generated range to step by that interval, e.g. `range("0", "9", "2")` returns ["0","2","4","6","8"].
956
957*Type*: rvalue.
958
959#### `regexpescape`
960
961Regexp escape a string or array of strings. Requires either a single string or an array as an input. *Type*: rvalue.
962
963#### `reject`
964
965Searches through an array and rejects all elements that match the provided regular expression. For example, `reject(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['bbb','ccc']. *Type*: rvalue.
966
967#### `reverse`
968
969Reverses the order of a string or array. *Type*: rvalue.
970
971#### `rstrip`
972
973Strips spaces to the right of the string. *Type*: rvalue.
974
975#### `seeded_rand`
976
977Takes an integer max value and a string seed value and returns a repeatable random integer smaller than max. Like `fqdn_rand`, but does not add node specific data to the seed. *Type*: rvalue.
978
979#### `shell_escape`
980
981Escapes 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 double quotes nor in single quotes. This function behaves the same as ruby's `Shellwords.shellescape()` function, also see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellescape).
982
983*Example:*
984~~~
985shell_escape('foo b"ar') => 'foo\ b\"ar'
986~~~
987
988*Type*: rvalue.
989
990#### `shell_join`
991
992Builds a command line string from the given array of strings. Each array item is escaped for Bourne shell. All items are
993then joined together, with a single space in between. This function behaves the same as ruby's `Shellwords.shelljoin()` function, also see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shelljoin).
994
995*Example:*
996~~~
997shell_join(['foo bar', 'ba"z']) => 'foo\ bar ba\"z'
998~~~
999
1000*Type*: rvalue.
1001
1002#### `shell_split`
1003
1004Splits a string into an array of tokens in the same way the Bourne shell does. This function behaves the same as ruby's `Shellwords.shellsplit()` function, also see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shellsplit).
1005
1006*Example:*
1007~~~
1008shell_split('foo\ bar ba\"z') => ['foo bar', 'ba"z']
1009~~~
1010
1011*Type*: rvalue.
1012
1013#### `shuffle`
1014
1015Randomizes the order of a string or array elements. *Type*: rvalue.
1016
1017#### `size`
1018
1019Returns the number of elements in a string, an array or a hash. *Type*: rvalue.
1020
1021#### `sort`
1022
1023Sorts strings and arrays lexically. *Type*: rvalue.
1024
1025#### `squeeze`
1026
1027Returns a new string where runs of the same character that occur in this set are replaced by a single character. *Type*: rvalue.
1028
1029#### `str2bool`
1030
1031Converts certain strings to a boolean. This attempts to convert strings that contain the values '1', 't', 'y', or 'yes' to true. Strings that contain values '0', 'f', 'n', or 'no', or that are an empty string or undefined are converted to false. Any other value causes an error. *Type*: rvalue.
1032
1033#### `str2saltedsha512`
1034
1035Converts a string to a salted-SHA512 password hash, used for OS X versions >= 10.7. Given any string, this function returns a hex version of a salted-SHA512 password hash, which can be inserted into your Puppet
1036manifests as a valid password attribute. *Type*: rvalue.
1037
1038#### `strftime`
1039
1040Returns formatted time. For example, `strftime("%s")` returns the time since Unix epoch, and `strftime("%Y-%m-%d")` returns the date. *Type*: rvalue.
1041
1042 *Format:*
1043
1044 * `%a`: The abbreviated weekday name ('Sun')
1045 * `%A`: The full weekday name ('Sunday')
1046 * `%b`: The abbreviated month name ('Jan')
1047 * `%B`: The full month name ('January')
1048 * `%c`: The preferred local date and time representation
1049 * `%C`: Century (20 in 2009)
1050 * `%d`: Day of the month (01..31)
1051 * `%D`: Date (%m/%d/%y)
1052 * `%e`: Day of the month, blank-padded ( 1..31)
1053 * `%F`: Equivalent to %Y-%m-%d (the ISO 8601 date format)
1054 * `%h`: Equivalent to %b
1055 * `%H`: Hour of the day, 24-hour clock (00..23)
1056 * `%I`: Hour of the day, 12-hour clock (01..12)
1057 * `%j`: Day of the year (001..366)
1058 * `%k`: Hour, 24-hour clock, blank-padded ( 0..23)
1059 * `%l`: Hour, 12-hour clock, blank-padded ( 0..12)
1060 * `%L`: Millisecond of the second (000..999)
1061 * `%m`: Month of the year (01..12)
1062 * `%M`: Minute of the hour (00..59)
1063 * `%n`: Newline (\n)
1064 * `%N`: Fractional seconds digits, default is 9 digits (nanosecond)
1065 * `%3N`: Millisecond (3 digits)
1066 * `%6N`: Microsecond (6 digits)
1067 * `%9N`: Nanosecond (9 digits)
1068 * `%p`: Meridian indicator ('AM' or 'PM')
1069 * `%P`: Meridian indicator ('am' or 'pm')
1070 * `%r`: Time, 12-hour (same as %I:%M:%S %p)
1071 * `%R`: Time, 24-hour (%H:%M)
1072 * `%s`: Number of seconds since the Unix epoch, 1970-01-01 00:00:00 UTC.
1073 * `%S`: Second of the minute (00..60)
1074 * `%t`: Tab character ( )
1075 * `%T`: Time, 24-hour (%H:%M:%S)
1076 * `%u`: Day of the week as a decimal, Monday being 1. (1..7)
1077 * `%U`: Week number of the current year, starting with the first Sunday as the first day of the first week (00..53)
1078 * `%v`: VMS date (%e-%b-%Y)
1079 * `%V`: Week number of year according to ISO 8601 (01..53)
1080 * `%W`: Week number of the current year, starting with the first Monday as the first day of the first week (00..53)
1081 * `%w`: Day of the week (Sunday is 0, 0..6)
1082 * `%x`: Preferred representation for the date alone, no time
1083 * `%X`: Preferred representation for the time alone, no date
1084 * `%y`: Year without a century (00..99)
1085 * `%Y`: Year with century
1086 * `%z`: Time zone as hour offset from UTC (e.g. +0900)
1087 * `%Z`: Time zone name
1088 * `%%`: Literal '%' character
1089
1090#### `strip`
1091
1092Removes leading and trailing whitespace from a string or from every string inside an array. For example, `strip(" aaa ")` results in "aaa". *Type*: rvalue.
1093
1094#### `suffix`
1095
1096Applies a suffix to all elements in an array, or to the keys in a hash.
1097For example:
1098* `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp']
1099* `suffix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'ap'=>'b','bp'=>'c','cp'=>'d'}.
1100
1101*Type*: rvalue.
1102
1103#### `swapcase`
1104
1105Swaps the existing case of a string. For example, `swapcase("aBcD")` results in "AbCd". *Type*: rvalue.
1106
1107#### `time`
1108
1109Returns the current Unix epoch time as an integer. For example, `time()` returns something like '1311972653'. *Type*: rvalue.
1110
1111#### `to_bytes`
1112
1113Converts the argument into bytes, for example "4 kB" becomes "4096". Takes a single string value as an argument. *Type*: rvalue.
1114
1115#### `try_get_value`
1116
1117*Type*: rvalue.
1118
1119DEPRECATED: replaced by `dig()`.
1120
1121Retrieves a value within multiple layers of hashes and arrays via a string containing a path. The path is a string of hash keys or array indexes starting with zero, separated by the path separator character (default "/"). The function goes through the structure by each path component and tries to return the value at the end of the path.
1122
1123In 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. The last argument can set the path separator character.
1124
1125~~~ruby
1126$data = {
1127 'a' => {
1128 'b' => [
1129 'b1',
1130 'b2',
1131 'b3',
1132 ]
1133 }
1134}
1135
1136$value = try_get_value($data, 'a/b/2')
1137# $value = 'b3'
1138
1139# with all possible options
1140$value = try_get_value($data, 'a/b/2', 'not_found', '/')
1141# $value = 'b3'
1142
1143# using the default value
1144$value = try_get_value($data, 'a/b/c/d', 'not_found')
1145# $value = 'not_found'
1146
1147# using custom separator
1148$value = try_get_value($data, 'a|b', [], '|')
1149# $value = ['b1','b2','b3']
1150~~~
1151
11521. **$data** The data structure we are working with.
11532. **'a/b/2'** The path string.
11543. **'not_found'** The default value. It will be returned if nothing is found.
1155 (optional, defaults to *undef*)
11564. **'/'** The path separator character.
1157 (optional, defaults to *'/'*)
1158
1159#### `type3x`
1160
1161Returns a string description of the type when passed a value. Type can be a string, array, hash, float, integer, or boolean. This function will be removed when Puppet 3 support is dropped and the new type system can be used. *Type*: rvalue.
1162
1163#### `type_of`
1164
1165Returns the literal type when passed a value. Requires the new parser. 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] { ... }`) *Type*: rvalue.
1166
1167#### `union`
1168
1169Returns a union of two or more arrays, without duplicates. For example, `union(["a","b","c"],["b","c","d"])` returns ["a","b","c","d"]. *Type*: rvalue.
1170
1171#### `unique`
1172
1173Removes duplicates from strings and arrays. For example, `unique("aabbcc")` returns 'abc', and `unique(["a","a","b","b","c","c"])` returns ["a","b","c"]. *Type*: rvalue.
1174
1175#### `unix2dos`
1176
1177Returns the DOS version of the given string. Very useful when using a File resource with a cross-platform template. *Type*: rvalue.
1178
1179~~~
1180file{$config_file:
1181 ensure => file,
1182 content => unix2dos(template('my_module/settings.conf.erb')),
1183}
1184~~~
1185
1186See also [dos2unix](#dos2unix).
1187
1188#### `upcase`
1189
1190Converts an object, array or hash of objects that respond to upcase to uppercase. For example, `upcase('abcd')` returns 'ABCD'. *Type*: rvalue.
1191
1192#### `uriescape`
1193
1194URLEncodes a string or array of strings. Requires either a single string or an array as an input. *Type*: rvalue.
1195
1196#### `validate_absolute_path`
1197
1198Validates that a given string represents an absolute path in the filesystem. Works for Windows and Unix style paths.
1199
1200The following values pass:
1201
1202~~~
1203$my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet'
1204validate_absolute_path($my_path)
1205$my_path2 = '/var/lib/puppet'
1206validate_absolute_path($my_path2)
1207$my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet','C:/Program Files/Puppet Labs/Puppet']
1208validate_absolute_path($my_path3)
1209$my_path4 = ['/var/lib/puppet','/usr/share/puppet']
1210validate_absolute_path($my_path4)
1211~~~
1212
1213The following values fail, causing compilation to abort:
1214
1215~~~
1216validate_absolute_path(true)
1217validate_absolute_path('../var/lib/puppet')
1218validate_absolute_path('var/lib/puppet')
1219validate_absolute_path([ 'var/lib/puppet', '/var/foo' ])
1220validate_absolute_path([ '/var/lib/puppet', 'var/foo' ])
1221$undefined = undef
1222validate_absolute_path($undefined)
1223~~~
1224
1225*Type*: statement.
1226
1227#### `validate_array`
1228
1229Validates that all passed values are array data structures. Aborts catalog compilation if any value fails this check.
1230
1231The following values pass:
1232
1233~~~
1234$my_array = [ 'one', 'two' ]
1235validate_array($my_array)
1236~~~
1237
1238The following values fail, causing compilation to abort:
1239
1240~~~
1241validate_array(true)
1242validate_array('some_string')
1243$undefined = undef
1244validate_array($undefined)
1245~~~
1246
1247*Type*: statement.
1248
1249#### `validate_augeas`
1250
1251Performs validation of a string using an Augeas lens. The first argument of this function should be the string to test, and the second argument should be the name of the Augeas lens to use. If Augeas fails to parse the string with the lens, the compilation aborts with a parse error.
1252
1253A third optional argument lists paths which should **not** be found in the file. The `$file` variable points to the location of the temporary file being tested in the Augeas tree.
1254
1255For example, to make sure your $passwdcontent never contains user `foo`:
1256
1257~~~
1258validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo'])
1259~~~
1260
1261To ensure that no users use the '/bin/barsh' shell:
1262
1263~~~
1264validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]']
1265~~~
1266
1267You can pass a fourth argument as the error message raised and shown to the user:
1268
1269~~~
1270validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas')
1271~~~
1272
1273*Type*: statement.
1274
1275#### `validate_bool`
1276
1277Validates that all passed values are either true or false. Aborts catalog compilation if any value fails this check.
1278
1279The following values will pass:
1280
1281~~~
1282$iamtrue = true
1283validate_bool(true)
1284validate_bool(true, true, false, $iamtrue)
1285~~~
1286
1287The following values will fail, causing compilation to abort:
1288
1289~~~
1290$some_array = [ true ]
1291validate_bool("false")
1292validate_bool("true")
1293validate_bool($some_array)
1294~~~
1295
1296*Type*: statement.
1297
1298#### `validate_cmd`
1299
1300Performs validation of a string with an external command. The first argument of this function should be a string to test, and the second argument should be a path to a test command taking a % as a placeholder for the file path (will default to the end of the command if no % placeholder given). If the command is launched against a tempfile containing the passed string, or returns a non-null value, compilation will abort with a parse error.
1301
1302If a third argument is specified, this will be the error message raised and seen by the user.
1303
1304~~~
1305# Defaults to end of path
1306validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content')
1307~~~
1308~~~
1309# % as file location
1310validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content')
1311~~~
1312
1313*Type*: statement.
1314
1315#### `validate_hash`
1316
1317Validates that all passed values are hash data structures. Aborts catalog compilation if any value fails this check.
1318
1319 The following values will pass:
1320
1321 ~~~
1322 $my_hash = { 'one' => 'two' }
1323 validate_hash($my_hash)
1324 ~~~
1325
1326 The following values will fail, causing compilation to abort:
1327
1328 ~~~
1329 validate_hash(true)
1330 validate_hash('some_string')
1331 $undefined = undef
1332 validate_hash($undefined)
1333 ~~~
1334
1335*Type*: statement.
1336
1337#### `validate_integer`
1338
1339Validates that the first argument is an integer (or an array of integers). Aborts catalog compilation if any of the checks fail.
1340
1341 The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max.
1342
1343 The third argument is optional and passes a minimum. (All elements of) the first argument has to be greater or equal to this min.
1344 If, and only if, a minimum is given, the second argument may be an empty string or undef, which will be handled to just check
1345 if (all elements of) the first argument are greater or equal to the given minimum.
1346
1347 It will fail if the first argument is not an integer or array of integers, and if arg 2 and arg 3 are not convertable to an integer.
1348
1349 The following values will pass:
1350
1351 ~~~
1352 validate_integer(1)
1353 validate_integer(1, 2)
1354 validate_integer(1, 1)
1355 validate_integer(1, 2, 0)
1356 validate_integer(2, 2, 2)
1357 validate_integer(2, '', 0)
1358 validate_integer(2, undef, 0)
1359 $foo = undef
1360 validate_integer(2, $foo, 0)
1361 validate_integer([1,2,3,4,5], 6)
1362 validate_integer([1,2,3,4,5], 6, 0)
1363 ~~~
1364
1365 * Plus all of the above, but any combination of values passed as strings ('1' or "1").
1366 * Plus all of the above, but with (correct) combinations of negative integer values.
1367
1368 The following values will fail, causing compilation to abort:
1369
1370 ~~~
1371 validate_integer(true)
1372 validate_integer(false)
1373 validate_integer(7.0)
1374 validate_integer({ 1 => 2 })
1375 $foo = undef
1376 validate_integer($foo)
1377 validate_integer($foobaridontexist)
1378
1379 validate_integer(1, 0)
1380 validate_integer(1, true)
1381 validate_integer(1, '')
1382 validate_integer(1, undef)
1383 validate_integer(1, , 0)
1384 validate_integer(1, 2, 3)
1385 validate_integer(1, 3, 2)
1386 validate_integer(1, 3, true)
1387 ~~~
1388
1389 * Plus all of the above, but any combination of values passed as strings ('false' or "false").
1390 * Plus all of the above, but with incorrect combinations of negative integer values.
1391 * Plus all of the above, but with non-integer items in arrays or maximum / minimum argument.
1392
1393 *Type*: statement.
1394
1395#### `validate_ip_address`
1396
1397Validates that the argument is an IP address, regardless of it is an IPv4 or an IPv6
1398address. It also validates IP address with netmask. The argument must be given as a string.
1399
1400The following values will pass:
1401
1402 ~~~
1403 validate_ip_address('0.0.0.0')
1404 validate_ip_address('8.8.8.8')
1405 validate_ip_address('127.0.0.1')
1406 validate_ip_address('194.232.104.150')
1407 validate_ip_address('3ffe:0505:0002::')
1408 validate_ip_address('::1/64')
1409 validate_ip_address('fe80::a00:27ff:fe94:44d6/64')
1410 validate_ip_address('8.8.8.8/32')
1411 ~~~
1412
1413The following values will fail, causing compilation to abort:
1414
1415 ~~~
1416 validate_ip_address(1)
1417 validate_ip_address(true)
1418 validate_ip_address(0.0.0.256)
1419 validate_ip_address('::1', {})
1420 validate_ip_address('0.0.0.0.0')
1421 validate_ip_address('3.3.3')
1422 validate_ip_address('23.43.9.22/64')
1423 validate_ip_address('260.2.32.43')
1424 ~~~
1425
1426
1427#### `validate_legacy`
1428
1429Validates 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.
1430
1431Accepts arguments for:
1432* the type to check the value against,
1433* the full name of the previous validation function,
1434* the value to be checked,
1435* an unspecified number of arguments needed for the previous validation function.
1436
1437Example:
1438
1439```
1440validate_legacy("Optional[String]", "validate_re", "Value to be validated", ["."])
1441```
1442
1443This 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.
1444
1445> Note: This function relies on internal APIs from Puppet 4.4.0 (PE 2016.1) onwards, and doesn't work on earlier versions.
1446
1447##### For module users
1448
1449If you are running Puppet 4 and receiving deprecation warnings about `validate_*` functions, the `validate_legacy` function can help you find and resolve the deprecated code.
1450
1451In Puppet 3, the `validate_*` functions were the only way to easily check the types of class and defined type arguments. Some of the functions provided additional helpers like [validate_numeric](#validate_numeric), which unintentionally allowed not only numbers, but also arrays of numbers. Puppet 4 allows much better defined type checking using [data types](https://docs.puppet.com/puppet/latest/reference/lang_data.html), without such unintentional effects. The `validate_legacy` function makes these differences visible and makes it easier to move to the clearer Puppet 4 syntax.
1452
1453Depending on the current state of development of the modules you use and the data you feed those modules, you'll encounter different messages:
1454
1455* `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.
1456* `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.
1457* `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.
1458* `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.
1459
1460##### For module developers
1461
1462Many `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. In contrast, Puppet 4 [data types](https://docs.puppet.com/puppet/latest/reference/lang_data.html) allows you to choose between `Numeric`, `Array[Numeric]`, or `Optional[Numeric]`. 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.
1463
1464For 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:
1465
1466| | `validate_` pass | `validate_` fail |
1467| ------------ | ---------------- | ---------------- |
1468| matches type | pass | pass, notice |
1469| fails type | pass, deprecated | fail |
1470
1471The 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.
1472
1473For 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.
1474
1475For example, given a class that should accept only numbers, like this:
1476
1477~~~
1478class example($value) {
1479 validate_numeric($value)
1480~~~
1481
1482the resulting validation code looks like this:
1483
1484~~~
1485class example(
1486 Variant[Stdlib::Compat::Numeric, Numeric] $value
1487) {
1488 validate_legacy(Numeric, 'validate_numeric', $value)
1489~~~
1490
1491Here, 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`).
1492
1493The 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.
1494
1495If 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.
1496
1497As 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.
1498
1499After 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.
1500
1501Always note such changes in your CHANGELOG and README.
1502
1503#### `validate_numeric`
1504
1505Validates that the first argument is a numeric value (or an array or string of numeric values). Aborts catalog compilation if any of the checks fail.
1506
1507 The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max.
1508
1509 The third argument is optional and passes a minimum. (All elements of) the first argument has to be greater or equal to this min.
1510 If, and only if, a minimum is given, the second argument may be an empty string or undef, which will be handled to just check
1511 if (all elements of) the first argument are greater or equal to the given minimum.
1512
1513 It will fail if the first argument is not a numeric (Integer or Float) or array of numerics, and if arg 2 and arg 3 are not convertable to a numeric.
1514
1515 For passing and failing usage, see `validate_integer()`. It is all the same for validate_numeric, yet now floating point values are allowed, too.
1516
1517*Type*: statement.
1518
1519#### `validate_re`
1520
1521Performs simple validation of a string against one or more regular expressions. The first argument of this function should be the string to
1522test, and the second argument should be a stringified regular expression (without the // delimiters) or an array of regular expressions. If none of the regular expressions match the string passed in, compilation aborts with a parse error.
1523
1524 You can pass a third argument as the error message raised and shown to the user.
1525
1526 The following strings validate against the regular expressions:
1527
1528 ~~~
1529 validate_re('one', '^one$')
1530 validate_re('one', [ '^one', '^two' ])
1531 ~~~
1532
1533 The following string fails to validate, causing compilation to abort:
1534
1535 ~~~
1536 validate_re('one', [ '^two', '^three' ])
1537 ~~~
1538
1539 To set the error message:
1540
1541 ~~~
1542 validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7')
1543 ~~~
1544
1545 Note: Compilation terminates if the first argument is not a string. Always use quotes to force stringification:
1546
1547 ~~~
1548 validate_re("${::operatingsystemmajrelease}", '^[57]$')
1549 ~~~
1550
1551*Type*: statement.
1552
1553#### `validate_slength`
1554
1555Validates that the first argument is a string (or an array of strings), and is less than or equal to the length of the second argument. It fails if the first argument is not a string or array of strings, or if the second argument is not convertable to a number. Optionally, a minimum string length can be given as the third argument.
1556
1557 The following values pass:
1558
1559 ~~~
1560 validate_slength("discombobulate",17)
1561 validate_slength(["discombobulate","moo"],17)
1562 validate_slength(["discombobulate","moo"],17,3)
1563 ~~~
1564
1565 The following values fail:
1566
1567 ~~~
1568 validate_slength("discombobulate",1)
1569 validate_slength(["discombobulate","thermometer"],5)
1570 validate_slength(["discombobulate","moo"],17,10)
1571 ~~~
1572
1573*Type*: statement.
1574
1575#### `validate_string`
1576
1577Validates that all passed values are string data structures. Aborts catalog compilation if any value fails this check.
1578
1579The following values pass:
1580
1581 ~~~
1582 $my_string = "one two"
1583 validate_string($my_string, 'three')
1584 ~~~
1585
1586 The following values fail, causing compilation to abort:
1587
1588 ~~~
1589 validate_string(true)
1590 validate_string([ 'some', 'array' ])
1591 ~~~
1592
1593*Note:* validate_string(undef) will not fail in this version of the functions API (incl. current and future parser).
1594
1595Instead, use:
1596
1597 ~~~
1598 if $var == undef {
1599 fail('...')
1600 }
1601 ~~~
1602
1603*Type*: statement.
1604
1605#### `validate_x509_rsa_key_pair`
1606
1607Validates a PEM-formatted X.509 certificate and private key using OpenSSL.
1608Verifies that the certficate's signature was created from the supplied key.
1609
1610Fails catalog compilation if any value fails this check.
1611
1612Takes two arguments, the first argument must be a X.509 certificate and the
1613second must be an RSA private key:
1614
1615 ~~~
1616 validate_x509_rsa_key_pair($cert, $key)
1617 ~~~
1618
1619*Type*: statement.
1620
1621#### `values`
1622
1623Returns the values of a given hash. For example, given `$hash = {'a'=1, 'b'=2, 'c'=3} values($hash)` returns [1,2,3].
1624
1625*Type*: rvalue.
1626
1627#### `values_at`
1628
1629Finds values inside an array based on location. The first argument is the array you want to analyze, and the second argument can be a combination of:
1630
1631 * A single numeric index
1632 * A range in the form of 'start-stop' (eg. 4-9)
1633 * An array combining the above
1634
1635 For example, `values_at(['a','b','c'], 2)` returns ['c']; `values_at(['a','b','c'], ["0-1"])` returns ['a','b']; and `values_at(['a','b','c','d','e'], [0, "2-3"])` returns ['a','c','d'].
1636
1637*Type*: rvalue.
1638
1639#### `zip`
1640
1641Takes 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.
1642
1643## Limitations
1644
1645As 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.
1646
1647###Version Compatibility
1648
1649Versions | Puppet 2.6 | Puppet 2.7 | Puppet 3.x | Puppet 4.x |
1650:---------------|:-----:|:---:|:---:|:----:
1651**stdlib 2.x** | **yes** | **yes** | no | no
1652**stdlib 3.x** | no | **yes** | **yes** | no
1653**stdlib 4.x** | no | **yes** | **yes** | no
1654**stdlib 4.6+** | no | **yes** | **yes** | **yes**
1655**stdlib 5.x** | no | no | **yes** | **yes**
1656
1657**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).
1658
1659## Development
1660
1661Puppet 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).
1662
1663To report or research a bug with any part of this module, please go to
1664[http://tickets.puppetlabs.com/browse/MODULES](http://tickets.puppetlabs.com/browse/MODULES).
1665
1666## Contributors
1667
1668The list of contributors can be found at: [https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors](https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors).
Note: See TracBrowser for help on using the repository browser.