Compare commits

...

241 commits

Author SHA1 Message Date
David Schmitt
9224143da2 Merge pull request #618 from ntpttr/fix/master/modules-3568
(MODULES-3568) Move dig to dig44 and deprecate dig
2016-07-13 09:50:30 +01:00
TP Honey
e723c7c292 Merge pull request #619 from DavidS/modulesync
(MAINT) modulesync [067d08a]
2016-07-11 09:23:42 +01:00
Nate Potter
a2f980d44d (MODULES-3568) Move dig to dig44 and deprecate dig
A new version of dig was introduced in Puppet 4.5.0 that
isn't compatible with the stdlib version of dig. To maintain
backwards compatibility and ensure that tests for stdlib aren't
broken, this patch renames dig to dig44 and adds a deprecation
warning to the stdlib dig function.
2016-07-08 08:53:24 -07:00
David Schmitt
be70aeba33 (MODULES-3581) modulesync [067d08a] 2016-07-08 13:43:12 +01:00
Helen
9465eeaea7 Merge pull request #616 from DavidS/modules-3435-fix-stdlib-symlinks
(MODULES-3435) remove symlinks
2016-07-01 12:41:08 +01:00
David Schmitt
daa80f168f (MODULES-3435) Fix gitignore and fixtures directory
This change more accurately reflects what is being ignored and what's
required as fixtures.
2016-07-01 12:03:59 +01:00
David Schmitt
5c51463c1f Fix load_module_metadata and loadjson tests to pass with fully deployed module
When replacing the lib/ and manifests/ symlinks in the fixtures with
a proper top-level symlink, puppet 4 starts loading the metadata.json
before loading functions, which confuses these tests. Added more specific
expectations, and provide data for that call.
2016-07-01 12:03:59 +01:00
TP Honey
6bab96ec26 Merge pull request #615 from DavidS/modules-3543-update-tests-and-function
(MODULES-3543) Fixup defined_with_params to work on all puppet versions
2016-06-30 11:47:00 +01:00
David Schmitt
3f86e3a731 (MODULES-3543) Fixup defined_with_params to work on all puppet versions 2016-06-30 11:10:24 +01:00
TP Honey
70d543e66a Merge pull request #614 from DavidS/MODULES-3543-fix-defined_with_params
(MODULES-3543) Fix define_with_params to handle undef properly
2016-06-30 09:55:49 +01:00
David Schmitt
af875b11ff (MODULES-3543) Fix define_with_params to handle undef properly
As described in PUP-6422,

	ensure_resources('File[/tmp/a]', { owner => undef })

would not actually create the file. This fixes it, and adds tests to prove
it.
2016-06-29 21:33:00 +01:00
Hunter Haugen
50cf8bd5b7 Merge pull request #610 from bmjen/modules-3507
(MODULES-3507) Updates file_line path validation
2016-06-29 07:15:39 -07:00
David Schmitt
7053868eaf Merge pull request #612 from puppetlabs/modulesync
{maint} modulesync 0794b2c
2016-06-29 11:42:35 +01:00
tphoney
d401d7f252 {maint} modulesync 0794b2c 2016-06-29 10:42:31 +01:00
Bryan Jen
7b1250478c (MODULES-3507) Updates file_line path validation 2016-06-28 16:45:56 -07:00
tphoney
098e82e694 {maint} modulesync changes for puppet-lint 2.0.0 2016-06-28 16:36:03 +01:00
JT (Jonny)
b7e1f8974b Merge pull request #605 from jyaworski/delete_optional_param
Add delete_regex
2016-05-16 15:34:25 +01:00
Joseph Yaworski
dd71c02880 Add a delete_regex function
To maintain backwards compatibility, add a delete_regex function instead
of modifying delete itself.
2016-05-13 13:25:35 -04:00
Bryan Jen
ecfdbb2690 Merge pull request #600 from dmitryilyin/master
Add the default value to the "loadyaml" function
2016-05-12 14:14:14 -07:00
Hunter Haugen
7a008a70b6 Merge pull request #606 from stbenjam/MODULES-3354
(MODULES-3354) Use 1.8.7 hash in validate_email_address function
2016-05-11 16:48:12 -07:00
Hunter Haugen
1b00c3bf3d Merge pull request #604 from rjw1/patch-1
Add a missing s in the ensure_packages hash example
2016-05-11 15:55:01 -07:00
Stephen Benjamin
f47df3b4b5 (MODULES-3354) Use 1.8.7 hash in validate_email_address function 2016-05-11 15:52:50 -04:00
bob
8f1efdad22 Add a missing s in the ensure_packages hash example 2016-05-11 10:52:25 +01:00
Bryan Jen
b2165dfc34 Merge pull request #601 from petems/MODULES-1439-any2bool_added
(MODULES-1439) Adds any2bool function
2016-05-05 10:13:10 -07:00
Bryan Jen
f46c9fdbce Merge pull request #592 from jyaworski/fix_delete
Use reject instead of delete_if
2016-05-04 09:13:20 -07:00
Joseph Yaworski
540546b9b4 Use reject instead of delete_if 2016-05-04 11:32:10 -04:00
Bryan Jen
f48747b8af Merge pull request #603 from puppetlabs/4.12.x
Mergeback 4.12.x
2016-05-03 15:09:33 -07:00
Peter Souter
420f76d8dc (MODULES-1439) Adds any2bool function
* Basically a combination of `string2bool` and `num2bool`
2016-05-02 20:04:56 +01:00
Joris
9e1f74f3fc Expose the functions of ruby's built-in Shellwords module (#580)
* Add shell_escape function, shell_join function & shell_split function
2016-04-28 18:44:30 +01:00
Jean B
2a75ed08a1 Merge pull request #602 from hunner/unbreakline
Remove hard linebreaks
2016-04-28 10:38:00 -07:00
Hunter Haugen
db6e2f81b4 Remove hard linebreaks 2016-04-27 15:34:19 -07:00
Dmitry Ilyin
870a272cee Add the default value to the "loadyaml" function
This value will be returned if the is no file
to load or a file could not be parsed.
It's similar to the "parseyaml" function's
default value.

Add the "loadjson" function too
2016-04-26 21:58:29 +03:00
Helen
fc18517905 Merge pull request #599 from hunner/fix_delete
Undo changing delete() to delete regex matches
2016-04-26 16:24:32 +01:00
Hunter Haugen
19752a7ff3 Remove todo for delete() and update spec
This spec should verify that substring matches are not removed in the
future
2016-04-25 14:36:53 -07:00
Hunter Haugen
232de137f1 Revert "Add support for regular expressions to delete"
This reverts commit 0d46515b57.

It introduced backwards-incompatible functionality.
2016-04-25 14:33:43 -07:00
Greg Hardy
24797bb5ad Merge pull request #593 from puppetlabs/update-msync
Update to newest modulesync_configs [9ca280f]
2016-04-19 11:45:08 +01:00
David Schmitt
ee6413b95a Update to newest modulesync_configs [9ca280f] 2016-04-18 20:15:09 +01:00
Helen
27236a73b2 Merge pull request #598 from DavidS/MODULES-3271-legacy-ruby
(MODULES-3271) Ensure that is_email_address works on unsupported rubies
2016-04-18 11:52:26 +01:00
David Schmitt
79c871322f (MODULES-3271) Ensure that is_email_address works on unsupported rubies 2016-04-18 09:46:30 +01:00
Helen
768b6ce9f4 Merge pull request #596 from tphoney/4.12.0_release_prep
4.12.0 release prep
2016-04-15 13:33:49 +01:00
tphoney
cf171a7279 4.12.0 release prep 2016-04-15 13:32:04 +01:00
Helen
d9f65387c9 Merge pull request #595 from tphoney/4.12.0_release
master to 4.12.x
2016-04-15 13:29:23 +01:00
Bryan Jen
085035dcce (FM-5000) Release prep for 4.12.0. 2016-04-15 13:21:44 +01:00
Hunter Haugen
733508677d Merge pull request #591 from jyaworski/delete_regex
Add support for regular expressions to delete
2016-04-12 10:41:48 -07:00
Joseph Yaworski
0d46515b57 Add support for regular expressions to delete 2016-04-12 13:10:39 -04:00
Hunter Haugen
e3a6e2c601 Merge pull request #590 from alext/fix_concat_with_hash
(MODULES-3246) Fix concat with Hash arguments.
2016-04-11 15:02:58 -07:00
TP Honey
60864fd39b Merge pull request #583 from jyaworski/validate_email_address
Add validate_email_address function
2016-04-11 16:04:25 +01:00
Joseph Yaworski
bfe6cf68b3 Add validate_email_address function 2016-04-10 22:28:03 -04:00
Alex Tomlins
44596e73da (MODULES-3246) Fix concat with Hash arguments.
85d5ead Updated the concat function so that it wouldn't modify the
original array. A side-effect of this change is that it now always calls
`Array()` on the second argument. If thit is a Hash, this results in
`to_a` being called on the hash, which converts it to an array or
tuples. This is undesired.

Update the behaviour so that it doesn't (indirectly) call `to_a` on
anything, instead test for the type of the argument, wrapping it in an
array if it's not already an array.
2016-04-08 13:42:13 +01:00
Hunter Haugen
be1ff3f09e Merge pull request #585 from jearls/MODULES-2370-update-validate-to-not-require-line-when-matching-for-absence
[MODULES-2370] file_line.rb: Fix `line` attribute validation
2016-04-07 15:10:07 -07:00
Hunter Haugen
6248d241bc Merge pull request #582 from derekmceachern/bug/master/spec_test_typo
MODULES-3201 - Fixed typo 'absense' to 'absence'
2016-04-07 14:53:02 -07:00
TP Honey
0624c3f806 Merge pull request #589 from puppetlabs/modulesync-update
Multiple updates to stdlib and its testsuite
2016-04-07 16:01:25 +01:00
David Schmitt
5639828bff (maint) also catch Psych::SyntaxError
Psych::SyntaxError is a RuntimeException. This still needs to
catch that. This was uncovered by the recent move to catch StandardError
rather than the catchall Exception that was here before.
2016-04-07 12:31:06 +01:00
David Schmitt
3860512d56 (maint) remove failing test
This removes the failing test special casing for puppet 4.
2016-04-07 12:31:06 +01:00
David Schmitt
27458aff98 (maint) Update to current modulesync_configs [953280c]
This removes much of the assorted cruft that accumulated in the
unmanaged files and moves the remaining necessary parts to
spec_helper_local.
2016-04-07 12:31:06 +01:00
Bryan Jen
c5486aba62 Merge pull request #586 from ffrank/dont_catch_exception
catch StandardError rather than the gratuitous Exception
2016-03-29 09:13:46 -07:00
Hunter Haugen
29961218a7 Merge pull request #587 from bmjen/4.12.0_prep
(FM-5000) Release prep for 4.12.0.
2016-03-28 17:46:45 -07:00
Bryan Jen
e6a3436fd0 (FM-5000) Release prep for 4.12.0. 2016-03-28 17:42:22 -07:00
Felix Frank
0cea94a82e catch StandardError rather than the gratuitous Exception 2016-03-29 01:59:54 +02:00
Johnson Earls
7e408ca797 [MODULES-2370] file_line.rb: Fix line attribute validation
`file_line` type: During validation, do not require `line` attribute if:
* `ensure` is `absent`,
* `match` is not empty,
* and `match_for_absence` is `true`.

Also update `spec` tests to reflect this.
2016-03-28 21:26:01 +00:00
Bryan Jen
b63849c786 Merge pull request #579 from sulaweyo/patch-2
Add check if Gem is defined
2016-03-28 11:44:00 -07:00
Derek McEachern
eca43f41cd Fixed typo 'absense' to 'absence' 2016-03-24 14:23:05 -05:00
Bryan Jen
db2a321434 Merge pull request #581 from vicinus/master
improve suffix function to support the same feature set as prefix
2016-03-23 08:24:37 -07:00
Reinhard Vicinus
85ff2a28a8 improve suffix function to support the same feature set as prefix 2016-03-22 16:24:09 +01:00
Hunter Haugen
b6383d259c Merge pull request #576 from yadavnikhil/master
ensure_packages.rb: Modifed to pass hiera parameters (as hash,array) as first argument
2016-03-17 09:25:38 -07:00
Sledge Sulaweyo
be6d4d2ffb Add check if Gem is defined
On e.g. Ubuntu 12.04 LTS Gem is not there by default so i added a check to not fail in that fact if this is the case.
2016-03-17 07:36:44 +01:00
Hunter Haugen
52f6af3acc Merge pull request #578 from bmjen/fqdn-rand-fix
(maint) Fixes fqdn_rand_string tests
2016-03-16 14:06:15 -07:00
Bryan Jen
7943b25ec1 (maint) Fixes fqdn_rand_string tests
Puppet 4.4.0 and later has changed fqdn_rand to use a higher ceiling
(PUP-5646), the tests for fqdn_rand_string needed to be updated to
reflect the new expected output.
2016-03-16 13:57:36 -07:00
Hunter Haugen
72f6e379a6 Merge pull request #577 from EmilienM/enclose_ipv6
Add enclose_ipv6 function
2016-03-15 16:48:50 -07:00
Nikhil Yadav
0da9ca7e4a Add ensure_resources() function
New function "ensure_resources()" to support passing hash as parameter OR from hiera backend

This new function is extension of ensure_resource() which will now support to pass multiple values as hash/array OR from hiera backend variables in title argument with additional parameters needed.

It will
process multiple values for a resource type from the passed argument & pass each entry (type, title, params) to ensure_resource() in required format for further processing.
Now user can have duplicate resource check functionality extended to multiple entries with this new function.

Use:
For multiple resources using
hash:
ensure_resources('user', {'dan' => { gid => 'mygroup', uid =>'600' } ,  'alex' => { gid => 'mygroup' }}, {'ensure' =>'present'})

From Hiera Backend:

userlist:
  dan:
    gid: 'mygroup'

uid: '600'
  alex:
 gid: 'mygroup'

Call:
ensure_resources('user',hiera_hash('userlist'), {'ensure' => 'present'})

ensure_packages()
Modified to also support Hash type argument for packages

This modification will call newly added ensure_resources() for processing Hash as second argument.
The original functionality remains same for Array type arguments.

Use:
hiera:

packagelist:
  ksh:
    ensure: latest
  mlocate: {}
  myrpm:
    provider: rpm
    source: "/tmp/myrpm-1.0.0.x86_64.rpm"
    install_options:
      --prefix:
        /users/home
  openssl:
    provider: rpm
    source: "/tmp/openssl-1.0.1e-42.el7.x86_64.rpm"

Call:
ensure_packages($packagelist)
2016-03-15 09:29:38 +05:30
Emilien Macchi
0378336f9c Add enclose_ipv6 function
Copy a function from puppetlabs/apache, created by Benedikt Bock by
55cc3b4e8f4bc859a1255cb57be2c7923005d822 .

This function enclose IPv6 addresses in square brackets.
It takes an array of ip addresses and encloses the ipv6 addresses with
square brackets.

Co-Authored-By: Benedikt Bock <benedikt_bock@web.de>
2016-03-13 18:20:49 -04:00
Hunter Haugen
69ca8d09c6 Merge pull request #570 from gfidente/master
Add is_ipv4_address and is_ipv6_address functions
2016-02-18 10:32:25 -08:00
TP Honey
2c3beace24 Merge pull request #575 from guessi/extend_base64_function_support
Extend Base64() function support
2016-02-18 15:47:04 +00:00
guessi
dc64e721ee Extend Base64() function support 2016-02-18 23:38:19 +08:00
Hunter Haugen
e2206fd153 Merge pull request #573 from Yelp/pl-dig
Add dig function
2016-02-16 12:26:51 -08:00
TP Honey
c83a70e674 Merge pull request #574 from DavidS/fm-4046-update-msync
(FM-4046) Update to current msync configs [006831f]
2016-02-16 18:53:34 +00:00
David Schmitt
8f037d23b2 (FM-4046) Update to current msync configs [006831f]
This moves all copyright statements to the NOTICE file in accordance with the ASFs guidelines on applying the Apache-2.0 license.
2016-02-16 16:33:53 +00:00
Maksym Melnychok
3169a43f4c Add dig() function
Deprecates #try_get_value()
2016-02-16 00:51:28 -08:00
Hunter Haugen
990e1d7575 Merge pull request #569 from DavidS/fm-4049-update-msync
(FM-4049) update to modulesync_configs
2016-01-27 08:36:03 -08:00
David Schmitt
7ff944daa0 (FM-4049) Update to current msync configs [2c99161] 2016-01-27 14:48:13 +00:00
Giulio Fidente
d85aec41a3 Add is_ipv4_address and is_ipv6_address functions
These are useful when making decisions based on the type of IP
address received.
2016-01-22 18:01:49 +01:00
JT (Jonny)
2a510169d6 Merge pull request #568 from mattbostock/fix_docs
Fix reference to validate_bool in function
2016-01-20 15:35:00 +00:00
Matt Bostock
b7df76cf7a Fix reference to validate_bool in function
The documentation in `validate_ip_address` references `validate_bool`,
but I believe this should read `validate_ip_address` instead, which
makes more sense.

Looks like this was copied from `validate_ipv4_address`, which I fixed
in 7b068781.
2016-01-19 16:22:01 +00:00
David Schmitt
e5be901e0e Merge pull request #567 from alechenninger/add-test-for-basename-with-scheme
Add test for basename on path with scheme
2016-01-18 09:23:51 +00:00
Alec Henninger
1659d478b9 Add test for basename on path with scheme 2016-01-16 11:55:25 -05:00
David Schmitt
4eba9364f1 Merge pull request #566 from puppetlabs/4.11.x
4.11.0 merge back
2016-01-12 14:41:49 +00:00
David Schmitt
f875770245 Merge pull request #552 from mattbostock/add_x509_rsa_key_pair
Add a function to validate an x509 RSA key pair
2016-01-08 11:13:16 +00:00
Matt Bostock
41f9319bbd Change order of tests to be more logical
Put the tests using a valid certificate fixture together and put tests
using a valid key fixture together.
2016-01-08 11:09:45 +00:00
Matt Bostock
4acba73b00 Test certificate and key with a truncated middle
Test a valid certificate and valid key that have had 48 characters
removed from their middle, to simulate a malformed certificate and key.

Suggested by @DavidS in https://github.com/puppetlabs/puppetlabs-stdlib/pull/552
2016-01-08 11:09:45 +00:00
Matt Bostock
97320ab421 Add a function to validate an x509 RSA key pair
Add a function to validate an x509 RSA certificate and key pair, as
commonly used for TLS certificates.

The rationale behind this is that we store our TLS certificates and
private keys in Hiera YAML files, and poor indentation or formatting in
the YAML file could cause a valid certificate to be considered invalid.

Will cause the Puppet run to fail if:

- an invalid certificate is detected
- an invalid RSA key is detected
- the certificate does not match the key, i.e. the certificate
  has not been signed by the supplied key

The test certificates I've used in the spec tests were generated using
the Go standard library:

    $ go run $GOROOT/src/crypto/tls/generate_cert.go -host localhost

Example output:

    ==> cache-1.router: Error: Not a valid RSA key: Neither PUB key nor PRIV key:: nested asn1 error at /var/govuk/puppet/modules/nginx/manifests/config/ssl.pp:30 on node cache-1.router.dev.gov.uk
2016-01-08 11:09:45 +00:00
David Schmitt
fdf3f22e24 Merge pull request #565 from tphoney/4.11.0_tweak
minor tweak to 4.11.0 adding debian 8 to metadata
2016-01-07 11:15:39 +00:00
tphoney
33b79f3497 minor tweak to 4.11.0 adding debian 8 to metadata 2016-01-07 10:54:48 +00:00
David Schmitt
9cce93054a Merge pull request #545 from mpolenchuk/master
Add clamp function
2016-01-04 15:35:42 +00:00
Jesse Lovelace
39644a69af Merge pull request #564 from tphoney/4.11.0_prep
4.11.0 prep
2015-12-31 11:34:44 -05:00
Michael Polenchuk
27782242bc Add clamp function
Clamp keeps value within the range.
Employ of soft() makes the whole thing is independant of order.
2015-12-31 12:46:07 +03:00
tphoney
00973036b2 4.11.0 prep 2015-12-30 13:45:05 +00:00
Bryan Jen
0073c6d8de Merge pull request #553 from logicminds/absolute_path
adds new parser called is_absolute_path
2015-12-21 17:41:55 -07:00
TP Honey
1c6ae4793f Merge pull request #561 from DavidS/fix-package_provider
Allow package_provider fact to resolve on PE 3.x
2015-12-21 16:54:20 +00:00
David Schmitt
35b5d6bcc1 Allow package_provider fact to resolve on PE 3.x
PE 3.x emits a puppetversion fact in the format "3.x.x (Puppet Enterprise 3.x.x)". This fact causes an error when invoked on PE 3.x: Could not retrieve fact='package_provider', resolution='<anonymous>': Malformed version number string 3.8.1 (Puppet Enterprise 3.8.1

This fix has been tested on PE 3.8.2 and should work for PE 3.3, 3.7, and 3.8.

Original-fix-by: Alex Harden <aharden@gmail.com>
2015-12-18 17:38:04 +00:00
TP Honey
8ea26c4c45 Merge pull request #559 from DavidS/fm-3802-fix-ensure_resource-test
(FM-3802) make ensure_resource test of packages
2015-12-17 13:59:52 +00:00
David Schmitt
02965b89e5 (FM-3802) make ensure_resource test of packages
This ensures that the test passes independently of changes to rubygems.
2015-12-17 13:50:15 +00:00
Corey Osman
1da820e61e refactors the validate_absolute_path to utilize the is_absolute_path 2015-12-15 23:24:17 -08:00
Corey Osman
1b048ff9d6 adds new parser called is_absolute_path
* is_absolute_path returns boolean true if the given path
    is absolute, returns false otherwise.
  * works for windows and unix
2015-12-15 23:24:17 -08:00
Jesse Lovelace
d2ae00cd5f Merge pull request #558 from puppetlabs/4.10.x
4.10.x mergeback
2015-12-15 14:53:01 -06:00
Bryan Jen
0b4822be3d Merge pull request #557 from jbondpdx/4.10.x
edits to README
2015-12-14 15:06:08 -07:00
jbondpdx
8fcefcfdb1 more carriage returns 2015-12-14 13:35:23 -08:00
jbondpdx
802e3adf16 more carriage returns, no 2015-12-14 11:57:01 -08:00
jbondpdx
d00bccc96f removing mid-line carriage returns 2015-12-14 11:50:51 -08:00
jbondpdx
4abc6e6e3b edits to README 2015-12-14 11:19:53 -08:00
Bryan Jen
9a1d8be10d Merge pull request #556 from HelenCampbell/4.10.0_prep
Changelog and versionbump for 4.10.0
2015-12-11 13:26:46 -07:00
Helen Campbell
964e24a637 Changelog and versionbump for 4.10.0 2015-12-11 20:08:25 +00:00
Bryan Jen
93600e45b0 Merge pull request #554 from kjetilho/ticket/2886-seeded_rand
(#2886) seeded_rand: new function
2015-12-10 11:54:10 -07:00
TP Honey
7a745deec6 Merge pull request #555 from puppetlabs/4.9.x
4.9.x Mergeback
2015-12-08 15:47:14 +00:00
Kjetil Torgrim Homme
8aecd63378 (#2886) seeded_rand: new function
seeded_rand is needed for repeatable randomness across nodes in a cluster
2015-12-08 14:59:12 +01:00
Bryan Jen
88a9a314c3 Merge pull request #546 from jdevesa/validate_ip
Add validator for any IP address
2015-11-30 11:10:57 -07:00
Jaume Devesa
fe23e01a4b Add validator for any IP address
Provide a validator for IP addresses, regardless they are IPv4 or IPv6,
and its documentation.
2015-11-30 17:34:00 +01:00
Bryan Jen
f684fb817c Merge pull request #550 from tphoney/release_4.9.1
4.9.1 release prep
2015-11-24 18:06:43 -07:00
tphoney
01c42d5212 4.9.1 release prep 2015-11-24 15:33:02 +00:00
David Schmitt
06b2cfbf73 Merge pull request #551 from mattbostock/fix_ipv4_doc
Fix reference to validate_bool in IP4 function
2015-11-24 10:41:30 +00:00
Matt Bostock
7b068781a5 Fix reference to validate_bool in IP4 function
The documentation in `validate_ipv4_address` references `validate_bool`,
but I believe this should read `validate_ipv4_address` instead, which
makes more sense.
2015-11-23 23:45:55 +00:00
Hunter Haugen
ef0c13b1af Merge pull request #548 from bmjen/ruby187
Fix Gemfile to work with ruby 1.8.7
2015-11-20 12:44:27 -08:00
Bryan Jen
c43924682a Fix Gemfile to work with ruby 1.8.7 2015-11-20 12:14:30 -07:00
Bryan Jen
0d2020001d Merge pull request #543 from ghoneycutt/patch-2
Use absolute class name in example
2015-11-20 09:09:52 -07:00
Bryan Jen
13e307b2c6 Merge pull request #547 from reidmv/fm_3773
(FM-3773) Fix root_home fact on AIX 5.x
2015-11-20 09:07:56 -07:00
Reid Vandewiele
13e5d467c9 (FM-3773) Fix root_home fact on AIX 5.x
The -C (capital C) flag to lsuser is incorrect. It should be -c
(lowercase).

this commit updates the aix root_home fact to use `lsuser -c`, rather
than `lsuser -C`.
2015-11-19 15:44:52 -08:00
David Schmitt
61333cfc48 Merge pull request #544 from HelenCampbell/readmeaddition
pick_default addition to readme
2015-11-09 15:17:01 +00:00
Helen Campbell
99db982741 pick_default addition to readme 2015-11-09 15:14:34 +00:00
Garrett Honeycutt
dc9b81d87e Use absolute class name in example 2015-11-06 12:19:21 -05:00
Helen
5d8a5ac631 Merge pull request #542 from greg0ire/patch-1
use properly encoded characters
2015-11-06 16:45:29 +00:00
Grégoire Paris
7fdc312348 use properly encoded characters
This is more severe than it sounds. These characters make puppet fail with the following message : 

> Error 400 on SERVER: "\xC3" on US-ASCII
2015-11-03 17:04:10 +01:00
David Schmitt
45ec648cdf Merge pull request #541 from mattflaschen/patch-1
Fix capitalize docs
2015-10-28 10:15:08 +00:00
Matt Flaschen
1421aa4a87 Fix capitalize docs
Capitalize lower-cases the remaining characters (due to the Ruby function having this behavior); document this, and make minor wording tweaks.
2015-10-27 18:09:18 -04:00
David Schmitt
143d4aa7be Merge pull request #540 from marrero984/update_str2bool_readme
(#2183) updated str2bool readme wording
2015-10-23 09:51:56 +01:00
marrero984
2c3c6fde98 (#2183) updated str2bool readme wording 2015-10-22 14:02:13 -07:00
David Schmitt
2db7440c67 Merge pull request #538 from mmckinst/bool2str_enhance
add functionality to bool2str function
2015-10-16 09:31:01 +01:00
Mark McKinstry
6de1a6e062 add functionality to bool2str to return strings of your choice for a boolean 2015-10-15 22:22:10 -04:00
Hunter Haugen
39126a7bc8 Merge pull request #539 from mentat/MODULES-2696
Add check to ensure regex does not throw for none type.
2015-10-15 10:23:02 -07:00
Jesse Lovelace
6aa7f2db99 Add check to ensure regex does not throw for none type.
Add a quick check to ensure puppetversion value is not nil and supporting test.
2015-10-15 11:27:03 -05:00
David Schmitt
57a8485223 Merge pull request #537 from cmurphy/fix_load_module_metadata
Fix load module metadata
2015-10-15 09:44:12 +01:00
Colleen Murphy
25410c4598 Let load_module_metadata succeed on empty file
Some modules or module versions don't have a metadata.json file, but we
might still want to use the load_module_metadata function on them. The
lack of a file can still give us important information. For example, it
might tell us that the version of the module installed is "very old"
even if we can't read the version number directly. This patch adds a
parameter to let the user specify if an empty file is acceptable. To
preserve backwards compatibility it does not change the current default
behavior, which is to raise an error if metadata.json does not exist.
2015-10-14 16:16:01 -07:00
Colleen Murphy
0f8df10084 Rename load_module_metadata test path
`rake spec` only finds test files that end in _spec.rb, so this test
was not being run. Correct the path name so that the test runs
properly.
2015-10-14 15:59:09 -07:00
TP Honey
5b3c623394 Merge pull request #536 from DavidS/improve-file_line-docs
(MODULES-2421) improve description of file_line
2015-10-14 12:46:19 +01:00
David Schmitt
ad173f2d05 (MODULES-2421) improve description of file_line
This mostly needed extraction of the existing doc strings from
the type.
2015-10-13 15:03:26 +01:00
David Schmitt
4e62223801 Merge pull request #535 from martinpfeifer/package_provider_fact
prevent deprecation warning about the allow_virtual parameter
2015-10-13 10:18:59 +01:00
Martin Pfeifer
d73fd3c5ef prevent deprecation warning about the allow_virtual parameter 2015-10-13 10:08:01 +02:00
Bryan Jen
e1a9bf5063 Merge pull request #534 from asasfu/feature/package_provider_fact
Add package_provider fact
2015-10-01 10:27:51 -07:00
David Schmitt
76db98120a Merge pull request #533 from HelenCampbell/MODULES-2614-Improved
Modules 2614 improved numeric value handling on empty function
2015-09-28 17:11:10 +01:00
Helen Campbell
c7c4d41a82 Added acceptance test and updated readme 2015-09-28 16:18:56 +01:00
Roman Mueller
6f1d164da6 Check for numeric values as empty fails on those 2015-09-28 16:01:11 +01:00
Helen
48b658fc1c Merge pull request #532 from DavidS/fix-is_a-readme
(FM-3701) Update README for is_a
2015-09-28 11:16:28 +01:00
David Schmitt
bfa21edbae (FM-3701) Update README for is_a 2015-09-28 11:12:25 +01:00
David Schmitt
39e81aa8b5 Merge pull request #531 from asasfu/improvement/service_provider_fact
fixup-PR#506 Speed improvements in facter resolution
2015-09-28 10:09:17 +01:00
Adam S
440245d40d fixup-PR#506 Speed improvements in facter resolution
This is to improve speed on Facter resolution of service_provider fact
that was just introduced in PR# 506.  The improvements go from 280ms
resolution time approx. down to 2ms resolution time approx. by adding
requires statements.
2015-09-25 18:06:00 -07:00
Adam S
ce6e8679b6 Add package_provider fact
This adds a package_provider fact for situations where we need to be
able to know the client's package provider in a simple way.  Situations
such as: package { 'name': install_options => [] }  As those tend to be
package provider specific options.
2015-09-25 17:55:21 -07:00
Hunter Haugen
4d1bca3359 Merge pull request #506 from binford2k/feature/service_provider_fact
Add a service_provider fact
2015-09-24 10:55:39 -07:00
David Schmitt
6bb1c27b99 Merge pull request #530 from HelenCampbell/MODULES-2614
Adding update to empty function readme
2015-09-23 11:38:53 +01:00
Helen Campbell
92b068ad20 Adding update to empty function readme 2015-09-23 11:27:48 +01:00
Bryan Jen
cebb9f333f Merge pull request #528 from mhaskel/is_a_fixes
Update is_a acceptance tests to only run on puppet4
2015-09-21 16:33:22 -07:00
Morgan Haskel
b20239e796 Update is_a acceptance tests to only run on puppet4 2015-09-21 14:12:25 -07:00
Bryan Jen
97bd656efb Merge pull request #527 from mhaskel/511_compatibility
Fix backwards compatibility from #511
2015-09-21 11:20:35 -07:00
Morgan Haskel
799c38e14e Fix backwards compatibility from #511
Maintain the old behavior in the case where the optional second
parameter isn't passed. Also, adding arity is backwards incompatible since
stdlib still supports 2.7, so remove that.
2015-09-21 11:11:21 -07:00
Hunter Haugen
9b1932c538 Merge pull request #526 from DavidS/improve-validate_re-docs
(MAINT) validate_re: Clarify docs and error message
2015-09-17 12:12:12 -07:00
David Schmitt
55ece7815a (MAINT) validate_re: Clarify docs and error message 2015-09-17 18:48:32 +01:00
David Schmitt
399ce03f68 Merge pull request #524 from binford2k/docs/intersection_truthiness
Clarify what an empty intersection looks like.
2015-09-14 19:36:56 +01:00
Ben Ford
169f8af506 Clarify what an empty intersection looks like. 2015-09-14 11:25:38 -07:00
Bryan Jen
0ea0e40228 Merge pull request #523 from DavidS/modules-2516-is_a
(MODULES-2561) add is_a function
2015-09-14 10:49:50 -07:00
Bryan Jen
c0df8192ee Merge pull request #511 from dmitryilyin/parseyaml_default
[MODULES-2462] Improve parseyaml function
2015-09-14 10:40:35 -07:00
David Schmitt
00c881d0da (MODULES-2516) Adds an is_a() function
The data type system is very hard to understand. Many people don't
understand why

    type_of([1,2,3]) == Array

will fail, but

    type_of([1,2,3]) <= Array

passes. This does a simpler validation that doesn't rely on explicit
data types. Instead, use

    $foo = [1,2,3]
    if $foo.is_a(Array) {
      notify { 'This is an array': }
    }

This is based on code by Ben Ford <ben.ford@puppetlabs.com>.

  * Added acceptance tests
  * Added dispatch
  * Improved unit tests
  * Added docs to README
2015-09-14 18:26:25 +01:00
TP Honey
2a7a93ffb4 Merge pull request #518 from logicminds/case_insensitive
accept any case of boolean strings
2015-09-09 11:20:18 +01:00
TP Honey
00b11c20c8 Merge pull request #519 from dmitryilyin/fetch
[MAINT] Improve 'try_get_value' readme
2015-09-08 11:15:45 +01:00
Dmitry Ilyin
411978db32 [MAINT] Improve 'try_get_value' readme 2015-09-04 19:24:15 +03:00
Corey Osman
f2f2db4795 accept any case of boolean strings
* previously the str2bool function did not accept 'TRUE' as a bool
    type.  This causes the function to now accept TRUE, FALSE strings
    as a boolean type in order to be converted to a proper boolean.
  * This would also cause Y,N, YES, NO to be accepted as boolean types
    as well.
2015-09-04 08:09:26 -07:00
Jonathan Tripathy
05c6587d85 Release Prep 4.9.0 2015-09-03 15:17:32 +01:00
TP Honey
6a1afae97e Merge pull request #517 from DavidS/try_get_value-acceptance
(MAINT) fix up try_get_value acceptance test
2015-09-02 13:42:11 +01:00
David Schmitt
5ef5c6629f (MAINT) fix up try_get_value acceptance test 2015-09-02 13:34:15 +01:00
David Schmitt
64267eb650 Merge pull request #513 from dmitryilyin/fetch
Add a new function "try_get_value"
2015-09-02 09:23:46 +01:00
Dmitry Ilyin
823a352f0f Add a new function "try_get_value"
* Extracts a value from a deeply-nested data structure
* Returns default if a value could not be extracted
2015-09-01 21:45:44 +03:00
David Schmitt
9352db77a6 Merge pull request #515 from jfautley/ticket/MODULES-2478-support_root_home_fact_on_AIX
(MODULES-2478) Make root_home fact work on AIX using native lsuser command
2015-09-01 08:31:31 +01:00
Jon Fautley
6c2a003f21 (MODULES-2478) Support root_home fact on AIX through "lsuser" command
Squashed, and amended test for comment lines.
2015-08-28 15:21:13 +01:00
TP Honey
b10978703a Merge pull request #514 from DavidS/add-convert_base
Adds a convert_base function, which can convert numbers between bases
2015-08-27 10:50:29 +01:00
fhats
2d4f5aa4d9 Adds a convert_base function, which can convert numbers between bases
Squashed, improved docs, updated error handling and unit tests by David S.
2015-08-27 10:42:13 +01:00
Dmitry Ilyin
eb948c4a0d [MODULES-2462] Improve parseyaml function
* Add default value support
  Second argument will be returned if yaml cannot be parsed
  instead of false value
* Update tests
2015-08-25 21:41:03 +03:00
David Schmitt
1bed010dbb Merge pull request #512 from Jetroid/consistentreadme
Consistent Readme
2015-08-25 10:51:39 +01:00
Jetroid
ba345abfb7 Add consistent *Type* information
Remove trailing whitespace

Two functions had not been given any *Type* information. This commit fixes that.
2015-08-25 10:35:57 +01:00
Morgan Haskel
da0e063af6 Merge pull request #510 from DavidS/base64-unit-tests
(MAINT) improve base64 unit tests
2015-08-24 13:47:24 -07:00
David Schmitt
aa23894dd3 (MAINT) improve base64 unit tests 2015-08-24 20:13:33 +01:00
David Schmitt
24e57b5d28 Merge pull request #507 from Jetroid/mod2456
(MODULES-2456) Modify union to accept more than two arrays
2015-08-24 14:36:20 +01:00
Jetroid
1d9189d860 (MODULE-2456) Modify union to accept more than two arrays
Add spec tests to test the new functionality:
 *Case for 3 arrays.
 *Case for 4 arrays.
Modify README to note new functionality.

This is for issue MODULE-2456, follow the precedent of MODULE-444.

This change allows union to be much more useful, unioning many arrays
in one line rather than in n lines. Additionally, as this is only added
functionality, and does not affect the 2 array case that all modules
currently using array are using, it should not affect any existing
modules utilizing union.

This is now useful, for example, for merging many arrays of resources
(eg: packages.) to generate just one list with no duplicates, to avoid
duplicate resource declarations.
2015-08-24 14:24:10 +01:00
Ben Ford
66e118a92a Add a service_provider fact
This returns the default provider Puppet will choose to manage services
on this system by instantiating a dummy service resource type and
returning the provider chosen.

Co-Authored-By: Simon Fraser University <asa188@sfu.ca>
2015-08-19 15:05:47 -07:00
David Schmitt
1d89df906e Merge pull request #505 from gibbsoft/dos2unix
(MODULES-2410) Add new functions dos2unix and unix2dos
2015-08-14 13:51:51 +01:00
Nigel Gibbs
4cbe846750 (MODULES-2410) Add new functions dos2unix and unix2dos 2015-08-14 13:30:01 +01:00
Bryan Jen
e84090df1d Merge pull request #499 from jearls/2370-use-match-for-ensure-absent
[MODULES-2370] allow `match` parameter to influence `ensure => absent` behavior.
2015-08-13 10:14:13 -07:00
Morgan Haskel
605fffd852 Merge pull request #503 from puppetlabs/4.8.x
Mergeback 4.8.x
2015-08-12 14:33:07 -07:00
Hunter Haugen
57275061ab Add puppet_version back to spec_helper 2015-08-11 19:52:43 -07:00
Morgan Haskel
a72918f675 Merge pull request #502 from hunner/fix_after
Sometimes this exits 1
2015-08-11 16:23:52 -07:00
Hunter Haugen
9baca7f755 Sometimes this exits 1 2015-08-11 16:23:06 -07:00
TP Honey
cf5d4ff34b Merge pull request #501 from hunner/bug_helper
Fix extraneous end
2015-08-11 16:43:58 +01:00
Hunter Haugen
0a58b9382c Fix extraneous end 2015-08-11 08:29:48 -07:00
Bryan Jen
a56e119f18 Merge pull request #500 from hunner/prep_4.8.0
Prep 4.8.0
2015-08-10 16:48:57 -07:00
Hunter Haugen
dfa98b89f7 Prep 4.8.0 2015-08-10 16:30:27 -07:00
Johnson Earls
9bacf14ca2 allow match parameter to influence ensure => absent behavior.
Split the `destroy` method of the file_type::ruby provider into two
private methods:  `handle_destroy_line` which is the same as the previous
`destroy` method, and `handle_destroy_with_match` which will destroy any
line which matches the `match` parameter, raising an error if multiple
lines match and the `multiple` parameter is not `true`.  This new
behavior is only used if the new boolean parameter `match_for_absence`
is `true` (it defaults to `false`).
2015-08-06 13:44:32 -07:00
Bryan Jen
061d0c29fc Merge pull request #497 from domcleal/tickets/master/MODULES-2316
(MODULES-2316) Change file_type boolean parameter to symbols
2015-08-06 11:00:17 -07:00
Dominic Cleal
a7adcda803 (MODULES-2316) Change file_type boolean parameter to symbols
Puppet's boolean parameter type is only available in Puppet 3.3 and
higher, so change file_type's new "replace" parameter to a regular
parameter with true and false as possible values.  This matches the
existing "multiple" parameter.
2015-08-04 09:59:53 +01:00
Hunter Haugen
e815da5962 Merge pull request #483 from nibalizer/load_metadata_json
Add load_metadata_json function
2015-07-31 14:12:56 -07:00
Spencer Krum
f411ee7119 Add load_metadata_json function
This function loads the metadata.json into a puppet variable. This enables a number of neat things such as:

* Which version of the module am I using? 2.x? 3.x?
* Which author of the module am I using? puppetlabs? example42?
2015-07-30 15:51:54 -07:00
Hunter Haugen
d1f6c5c553 Merge pull request #496 from pizzaops/master
Remove colorful language from module.
2015-07-30 15:14:23 -07:00
Zee Alexander
aca29129cb Remove colorful language from module. 2015-07-30 15:11:26 -07:00
Bryan Jen
ebf73482e5 Merge pull request #494 from CENGN/fix/master/file_line_replace
[#puppethack] Adding replace attribute to file_line
2015-07-30 13:34:26 -07:00
Bryan Jen
41a7297cb7 Merge pull request #495 from puppetlabs/4.7.x
4.7.x
2015-07-30 13:33:44 -07:00
Raymond Maika
35e92645f7 (MODULES-2024) Adding replace attribute to file_line 2015-07-30 14:55:32 -04:00
TP Honey
956c329a8a Merge pull request #493 from DavidS/fixup-acceptance-testing
(maint) use puppet's utility function instead of API that's not avail…
2015-07-30 11:12:01 +01:00
David Schmitt
44c4bad392 (maint) use puppet's utility function instead of API that's not available on all rubies 2015-07-30 10:46:38 +01:00
Hunter Haugen
ac0b096d49 Merge pull request #492 from DavidS/fixup-acceptance-testing
Fixup acceptance testing
2015-07-29 10:58:41 -07:00
David Schmitt
4d889cbcb6 Merge pull request #491 from ekohl/style-fixes
Style fixes
2015-07-27 09:49:04 +01:00
Ewoud Kohl van Wijngaarden
c7403a4e05 Style fixes 2015-07-25 13:34:31 +02:00
David Schmitt
a8d7563a44 (main) clean up fqdn_rand acceptance tests to work on windows 2015-07-22 17:30:39 +01:00
David Schmitt
24b1cd78db (maint) Remove failing acceptance test for ensure_packages
This only duplicates what's already being tested in ensure_packages_spec.rb
but doesn't work on all our supported platforms.
2015-07-22 12:21:31 +01:00
David Schmitt
dca8bdba59 Merge pull request #489 from gcmalloc/master
adding support for hash in the size function
2015-07-22 11:57:16 +01:00
gcmalloc
5c79107863 adding support for hash in the size function 2015-07-22 12:11:52 +02:00
Morgan Haskel
f996a38d11 Merge pull request #490 from hunner/fix_specifier
disable pw_hash test on sles, as it only supports md5
2015-07-21 14:44:50 -07:00
Hunter Haugen
615227918a disable pw_hash test on sles, as it only supports md5 2015-07-21 14:43:34 -07:00
David Schmitt
dde8aa095a Merge pull request #487 from liv3d/fix_docs_in_upcase
Fix documentation error in upcase
2015-07-21 09:23:57 +01:00
Hunter Haugen
21feb4b1f1 Merge pull request #488 from cyberious/master
(maint) Fix test to not assume is_pe fact on > 4.0.0 puppet
2015-07-20 16:28:57 -07:00
Travis Fields
78e8c73671 (maint) Fix test to not assume is_pe fact on > 4.0.0 puppet 2015-07-20 15:51:39 -07:00
Dan Offord
939aceffad Fix documentation error in upcase
The documentation example shows an incorrect response when using the
function, this PR corrects the example to agree with what the function
actually does.
2015-07-20 18:00:09 +01:00
David Schmitt
1282649b91 Merge pull request #481 from tphoney/release_4.7.0
prep work for 4.7.0
2015-07-15 14:12:46 +01:00
tphoney
14709d625b prep work for 4.7.0
add new improvements

puppet4 changes for testing
2015-07-15 14:06:34 +01:00
David Schmitt
a022441289 Merge pull request #485 from ghoneycutt/patch-2
Clarify that third argument to ensure_resource() is a hash
2015-07-14 09:47:22 +01:00
Garrett Honeycutt
f485e6e2eb Clarify that third argument to ensure_resource() is a hash 2015-07-12 20:11:36 -04:00
TP Honey
01fe9dc15c Merge pull request #484 from mhaskel/use_puppet_install_helper
Use puppet_install_helper
2015-07-10 17:17:09 +01:00
Morgan Haskel
224b644003 Use puppet_install_helper 2015-07-09 17:11:10 -07:00
TP Honey
a2026bf13b Merge pull request #475 from DavidS/document-puppet4-compat
Document puppet 4 compatability in 4.6
2015-07-09 18:30:26 +01:00
Morgan Haskel
07c38e518a Merge pull request #482 from DavidS/document_validate_slength_3rd_arg
Add validate_slength's optional 3rd arg to README
2015-07-09 10:20:37 -07:00
Hunter Haugen
b2aed66226 Merge pull request #479 from mklette/master
catch and rescue from looking up non-existent facts
2015-07-09 10:20:01 -07:00
Alexander Fisher
c64ecfb0c3 Add validate_slength's optional 3rd arg to README 2015-07-09 18:13:19 +01:00
Mathias Klette
e96a818782 catch and rescue from looking up non-existent facts when looking for 'kind'
facter (2.x) only provides facts without interface suffix for
 * ipaddress
 * netmask

'macaddress' and 'network' facts will always have the related interface
name appended. in turns lookupvar throws errors when strict_variables is
enabled.
2015-06-24 15:02:02 +02:00
David Schmitt
f820bb1560 Merge pull request #478 from drewfisher314/ticket/2134-add-solaris-12
Add support for Solaris 12
2015-06-22 10:27:10 +01:00
Drew Fisher
a6dcb23f89 Add support for Solaris 12 2015-06-19 17:14:21 -06:00
Travis Fields
67bc57bcb6 Merge pull request #477 from mhaskel/aio_fix
AIO uses puppet 4 so should return true for is_future_parser_enabled
2015-06-19 14:48:16 -07:00
Morgan Haskel
5381dbd4b4 AIO uses puppet 4 so should return true for is_future_parser_enabled 2015-06-19 14:29:42 -07:00
David Schmitt
771320a830 Document puppet 4 compatability in 4.6 2015-06-18 14:51:35 +01:00
171 changed files with 4413 additions and 901 deletions

5
.gitattributes vendored Normal file
View file

@ -0,0 +1,5 @@
#This file is generated by ModuleSync, do not edit.
*.rb eol=lf
*.erb eol=lf
*.pp eol=lf
*.sh eol=lf

24
.gitignore vendored
View file

@ -1,12 +1,14 @@
/pkg/
/Gemfile.lock
/vendor/
/spec/fixtures/manifests/*
/spec/fixtures/modules/*
!/spec/fixtures/modules/stdlib
!/spec/fixtures/modules/stdlib/*
/.vagrant/
/.bundle/
/coverage/
/.idea/
#This file is generated by ModuleSync, do not edit.
pkg/
Gemfile.lock
vendor/
spec/fixtures/
.vagrant/
.bundle/
coverage/
log/
.idea/
*.iml
!spec/fixtures/
spec/fixtures/manifests/site.pp
spec/fixtures/modules/*

4
.rspec
View file

@ -1,4 +1,2 @@
--color
--format
progress
--backtrace
--format documentation

View file

@ -1,9 +1,7 @@
---
.travis.yml:
script: "\"bundle exec rake validate && bundle exec rake lint && bundle exec rake spec SPEC_OPTS='--color --format documentation'\""
Rakefile:
unmanaged: true
Gemfile:
unmanaged: true
spec/spec_helper.rb:
unmanaged: true
.gitignore:
paths:
- '!spec/fixtures/'
- 'spec/fixtures/manifests/site.pp'
- 'spec/fixtures/modules/*'

View file

@ -1,21 +1,35 @@
#This file is generated by ModuleSync, do not edit.
---
sudo: false
language: ruby
cache: bundler
bundler_args: --without system_tests
script: "bundle exec rake validate && bundle exec rake lint && bundle exec rake spec SPEC_OPTS='--color --format documentation'"
script: "bundle exec rake validate lint spec"
matrix:
fast_finish: true
include:
- rvm: 1.8.7
- rvm: 2.1.6
dist: trusty
env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_set=docker/ubuntu-14.04
script: bundle exec rake beaker
services: docker
sudo: required
- rvm: 2.1.6
dist: trusty
env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_set=docker/centos-7
script: bundle exec rake beaker
services: docker
sudo: required
- rvm: 2.1.6
bundler_args: --without system_tests
env: PUPPET_GEM_VERSION="~> 4.0" STRICT_VARIABLES="yes"
- rvm: 2.1.5
bundler_args: --without system_tests
env: PUPPET_GEM_VERSION="~> 3.0" FUTURE_PARSER="yes"
- rvm: 2.1.5
bundler_args: --without system_tests
env: PUPPET_GEM_VERSION="~> 3.0"
- rvm: 1.9.3
bundler_args: --without system_tests
env: PUPPET_GEM_VERSION="~> 3.0"
- rvm: 2.1.5
env: PUPPET_GEM_VERSION="~> 3.0"
- rvm: 2.1.5
env: PUPPET_GEM_VERSION="~> 3.0" FUTURE_PARSER="yes"
- rvm: 2.1.6
env: PUPPET_GEM_VERSION="~> 4.0" STRICT_VARIABLES="yes"
notifications:
email: false

View file

@ -1,3 +1,143 @@
## Supported Release 4.12.0
###Summary
This release provides several new functions, bugfixes, modulesync changes, and some documentation updates.
####Features
- Adds `clamp`. This function keeps values within a specified range.
- Adds `validate_x509_rsa_key_pair`. This function validates an x509 RSA certificate and key pair.
- Adds `dig`. This function performs a deep lookup in nested hashes or arrays.
- Extends the `base64` support to fit `rfc2045` and `rfc4648`.
- Adds `is_ipv6_address` and `is_ipv4_address`. These functions validate the specified ipv4 or ipv6 addresses.
- Adds `enclose_ipv6`. This function encloses IPv6 addresses in square brackets.
- Adds `ensure_resources`. This function takes a list of resources and creates them if they do not exist.
- Extends `suffix` to support applying a suffix to keys in a hash.
- Apply modulesync changes.
- Add validate_email_address function.
####Bugfixes
- Fixes `fqdn_rand_string` tests, since Puppet 4.4.0 and later have a higher `fqdn_rand` ceiling.
- (MODULES-3152) Adds a check to `package_provider` to prevent failures if Gem is not installed.
- Fixes to README.md.
- Fixes catch StandardError rather than the gratuitous Exception
- Fixes file_line attribute validation.
- Fixes concat with Hash arguments.
## Supported Release 4.11.0
###Summary
Provides a validate_absolute_paths and Debian 8 support. There is a fix to the is_package_provider fact and a test improvement.
####Features
- Adds new parser called is_absolute_path
- Supports Debian 8
####Bugfixes
- Allow package_provider fact to resolve on PE 3.x
####Improvements
- ensures that the test passes independently of changes to rubygems for ensure_resource
##2015-12-15 - Supported Release 4.10.0
###Summary
Includes the addition of several new functions and considerable improvements to the existing functions, tests and documentation. Includes some bug fixes which includes compatibility, test and fact issues.
####Features
- Adds service_provider fact
- Adds is_a() function
- Adds package_provider fact
- Adds validate_ip_address function
- Adds seeded_rand function
####Bugfixes
- Fix backwards compatibility from an improvement to the parseyaml function
- Renaming of load_module_metadata test to include _spec.rb
- Fix root_home fact on AIX 5.x, now '-c' rather than '-C'
- Fixed Gemfile to work with ruby 1.8.7
####Improvements
- (MODULES-2462) Improvement of parseyaml function
- Improvement of str2bool function
- Improvement to readme
- Improvement of intersection function
- Improvement of validate_re function
- Improved speed on Facter resolution of service_provider
- empty function now handles numeric values
- Package_provider now prevents deprecation warning about the allow_virtual parameter
- load_module_metadata now succeeds on empty file
- Check added to ensure puppetversion value is not nil
- Improvement to bool2str to return a string of choice using boolean
- Improvement to naming convention in validate_ipv4_address function
## Supported Release 4.9.1
###Summary
Small release for support of newer PE versions. This increments the version of PE in the metadata.json file.
##2015-09-08 - Supported Release 4.9.0
###Summary
This release adds new features including the new functions dos2unix, unix2dos, try_get_value, convert_base as well as other features and improvements.
####Features
- (MODULES-2370) allow `match` parameter to influence `ensure => absent` behavior
- (MODULES-2410) Add new functions dos2unix and unix2dos
- (MODULE-2456) Modify union to accept more than two arrays
- Adds a convert_base function, which can convert numbers between bases
- Add a new function "try_get_value"
####Bugfixes
- n/a
####Improvements
- (MODULES-2478) Support root_home fact on AIX through "lsuser" command
- Acceptance test improvements
- Unit test improvements
- Readme improvements
## 2015-08-10 - Supported Release 4.8.0
### Summary
This release adds a function for reading metadata.json from any module, and expands file\_line's abilities.
#### Features
- New parameter `replace` on `file_line`
- New function `load_module_metadata()` to load metadata.json and return the content as a hash.
- Added hash support to `size()`
#### Bugfixes
- Fix various docs typos
- Fix `file_line` resource on puppet < 3.3
##2015-06-22 - Supported Release 4.7.0
###Summary
Adds Solaris 12 support along with improved Puppet 4 support. There are significant test improvements, and some minor fixes.
####Features
- Add support for Solaris 12
####Bugfixes
- Fix for AIO Puppet 4
- Fix time for ruby 1.8.7
- Specify rspec-puppet version
- range() fix for typeerror and missing functionality
- Fix pw_hash() on JRuby < 1.7.17
- fqdn_rand_string: fix argument error message
- catch and rescue from looking up non-existent facts
- Use puppet_install_helper, for Puppet 4
####Improvements
- Enforce support for Puppet 4 testing
- fqdn_rotate/fqdn_rand_string acceptance tests and implementation
- Simplify mac address regex
- validate_integer, validate_numeric: explicitely reject hashes in arrays
- Readme edits
- Remove all the pops stuff for rspec-puppet
- Sync via modulesync
- Add validate_slength optional 3rd arg
- Move tests directory to examples directory
##2015-04-14 - Supported Release 4.6.0
###Summary
@ -293,7 +433,7 @@ This is a supported release
* Add an ensure\_packages function. (8a8c09e)
##### 2012-11-23 - Erik Dalén <dalen@spotify.com> - 3.2.0
##### 2012-11-23 - Erik Dalén <dalen@spotify.com> - 3.2.0
* (#17797) min() and max() functions (9954133)
@ -390,7 +530,7 @@ This is a supported release
* Add support for a 'match' parameter to file\_line (a06c0d8)
##### 2012-08-07 - Erik Dalén <dalen@spotify.com> - 2.4.0
##### 2012-08-07 - Erik Dalén <dalen@spotify.com> - 2.4.0
* (#15872) Add to\_bytes function (247b69c)

View file

@ -159,7 +159,7 @@ If you already have those gems installed, make sure they are up-to-date:
With all dependencies in place and up-to-date we can now run the tests:
```shell
% rake spec
% bundle exec rake spec
```
This will execute all the [rspec tests](http://rspec-puppet.com/) tests
@ -178,8 +178,8 @@ installed on your system.
You can run them by issuing the following command
```shell
% rake spec_clean
% rspec spec/acceptance
% bundle exec rake spec_clean
% bundle exec rspec spec/acceptance
```
This will now download a pre-fabricated image configured in the [default node-set](./spec/acceptance/nodesets/default.yml),
@ -208,11 +208,9 @@ review.
Additional Resources
====================
* [Getting additional help](http://puppetlabs.com/community/get-help)
* [Getting additional help](http://puppet.com/community/get-help)
* [Writing tests](http://projects.puppetlabs.com/projects/puppet/wiki/Development_Writing_Tests)
* [Patchwork](https://patchwork.puppetlabs.com)
* [Writing tests](https://docs.puppet.com/guides/module_guides/bgtm.html#step-three-module-testing)
* [General GitHub documentation](http://help.github.com/)

66
Gemfile
View file

@ -1,54 +1,40 @@
source ENV['GEM_SOURCE'] || 'https://rubygems.org'
#This file is generated by ModuleSync, do not edit.
def location_for(place, fake_version = nil)
source ENV['GEM_SOURCE'] || "https://rubygems.org"
def location_for(place, version = nil)
if place =~ /^(git[:@][^#]*)#(.*)/
[fake_version, { :git => $1, :branch => $2, :require => false }].compact
[version, { :git => $1, :branch => $2, :require => false}].compact
elsif place =~ /^file:\/\/(.*)/
['>= 0', { :path => File.expand_path($1), :require => false }]
['>= 0', { :path => File.expand_path($1), :require => false}]
else
[place, { :require => false }]
[place, version, { :require => false}].compact
end
end
group :development, :unit_tests do
gem 'rake', '~> 10.1.0', :require => false
gem 'rspec', '~> 3.1.0', :require => false
gem 'rspec-puppet', '~> 2.2', :require => false
gem 'mocha', :require => false
# keep for its rake task for now
gem 'puppetlabs_spec_helper', :require => false
gem 'puppet-lint', :require => false
gem 'metadata-json-lint', :require => false
gem 'pry', :require => false
gem 'simplecov', :require => false
gem 'json', :require => false
gem 'metadata-json-lint', :require => false
gem 'puppet_facts', :require => false
gem 'puppetlabs_spec_helper', :require => false
gem 'rspec-puppet', '>= 2.3.2', :require => false
gem 'simplecov', :require => false
gem 'puppet-blacksmith', :require => false
gem 'rest-client', '~> 1.8.0', :require => false
end
beaker_version = ENV['BEAKER_VERSION']
beaker_rspec_version = ENV['BEAKER_RSPEC_VERSION']
group :system_tests do
if beaker_version
gem 'beaker', *location_for(beaker_version)
end
if beaker_rspec_version
gem 'beaker-rspec', *location_for(beaker_rspec_version)
else
gem 'beaker-rspec', :require => false
end
gem 'serverspec', :require => false
gem 'beaker-rspec', *location_for(ENV['BEAKER_RSPEC_VERSION'] || '>= 3.4')
gem 'beaker', *location_for(ENV['BEAKER_VERSION'])
gem 'serverspec', :require => false
gem 'beaker-puppet_install_helper', :require => false
gem 'master_manipulator', :require => false
gem 'beaker-hostgenerator', *location_for(ENV['BEAKER_HOSTGENERATOR_VERSION'])
end
facterversion = ENV['GEM_FACTER_VERSION'] || ENV['FACTER_GEM_VERSION']
if facterversion
gem 'facter', *location_for(facterversion)
else
gem 'facter', :require => false
end
gem 'facter', *location_for(ENV['FACTER_GEM_VERSION'])
gem 'puppet', *location_for(ENV['PUPPET_GEM_VERSION'])
puppetversion = ENV['GEM_PUPPET_VERSION'] || ENV['PUPPET_GEM_VERSION']
if puppetversion
gem 'puppet', *location_for(puppetversion)
else
gem 'puppet', :require => false
end
# vim:ft=ruby
if File.exists? "#{__FILE__}.local"
eval(File.read("#{__FILE__}.local"), binding)
end

209
LICENSE
View file

@ -1,19 +1,202 @@
Copyright (C) 2011 Puppet Labs Inc
and some parts:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (C) 2011 Krzysztof Wilczynski
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Puppet Labs can be contacted at: info@puppetlabs.com
1. Definitions.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
http://www.apache.org/licenses/LICENSE-2.0
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

23
NOTICE Normal file
View file

@ -0,0 +1,23 @@
stdlib puppet module
Copyright (C) 2011-2016 Puppet Labs, Inc.
and some parts:
Copyright (C) 2011 Krzysztof Wilczynski
Puppet Labs can be contacted at: info@puppetlabs.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -76,30 +76,63 @@ The `stdlib::stages` class declares various run stages for deploying infrastruct
### Types
#### `file_line`
Ensures that a given line, including whitespace at the beginning and end, is contained within a file. If the line is not contained in the given file, Puppet will add the line. Multiple resources can be declared to manage multiple lines in the same file. You can also use `match` to replace existing lines.
~~~
file_line { 'sudo_rule':
path => '/etc/sudoers',
line => '%sudo ALL=(ALL) ALL',
}
file_line { 'sudo_rule_nopw':
path => '/etc/sudoers',
line => '%sudonopw ALL=(ALL) NOPASSWD: ALL',
}
~~~
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.
Example:
file_line { 'sudo_rule':
path => '/etc/sudoers',
line => '%sudo ALL=(ALL) ALL',
}
file_line { 'sudo_rule_nopw':
path => '/etc/sudoers',
line => '%sudonopw ALL=(ALL) NOPASSWD: ALL',
}
In this example, Puppet ensures that both of the specified lines are contained in the file `/etc/sudoers`.
Match Example:
file_line { 'bashrc_proxy':
ensure => present,
path => '/etc/bashrc',
line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
match => '^export\ HTTP_PROXY\=',
}
In this code example, `match` looks for a line beginning with export followed by HTTP_PROXY and replaces it with the value in line.
Match Example With `ensure => absent`:
file_line { 'bashrc_proxy':
ensure => absent,
path => '/etc/bashrc',
line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
match => '^export\ HTTP_PROXY\=',
match_for_absence => true,
}
In this code example, `match` looks for a line beginning with export
followed by HTTP_PROXY and delete it. If multiple lines match, an
error will be raised unless the `multiple => true` parameter is set.
**Autorequires:** If Puppet is managing the file that contains the line being managed, the `file_line` resource autorequires that file.
##### Parameters
All parameters are optional, unless otherwise noted.
* `after`: Specifies the line after which Puppet will add any new lines. (Existing lines are added in place.) Valid options: String. Default: Undefined.
* `after`: Specifies the line after which Puppet adds any new lines. (Existing lines are added in place.) Valid options: String. Default: Undefined.
* `ensure`: Ensures whether the resource is present. Valid options: 'present', 'absent'. Default: 'present'.
* `line`: **Required.** Sets the line to be added to the file located by the `path` parameter. Valid options: String. Default: Undefined.
* `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. Valid options: String containing a regex. Default: Undefined.
* `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.
* `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. Default: false.
* `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.
* `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.
* `path`: **Required.** Defines the file in which Puppet will ensure the line specified by `line`. Must be an absolute path to the file.
* `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
### Functions
@ -113,7 +146,34 @@ Converts any object to an array containing that object. Empty argument lists are
#### `base64`
Converts a string to and from base64 encoding. Requires an action ('encode', 'decode') and either a plain or base64-encoded string. *Type*: rvalue.
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')
For backward compatibility, `method` will be set as `default` if not specified.
*Examples:*
~~~
base64('encode', 'hello')
base64('encode', 'hello', 'default')
# return: "aGVsbG8=\n"
base64('encode', 'hello', 'strict')
# return: "aGVsbG8="
base64('decode', 'aGVsbG8=')
base64('decode', 'aGVsbG8=\n')
base64('decode', 'aGVsbG8=', 'default')
base64('decode', 'aGVsbG8=\n', 'default')
base64('decode', 'aGVsbG8=', 'strict')
# return: "hello"
base64('encode', 'https://puppetlabs.com', 'urlsafe')
# return: "aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ=="
base64('decode', 'aHR0cHM6Ly9wdXBwZXRsYWJzLmNvbQ==', 'urlsafe')
# return: "https://puppetlabs.com"
~~~
*Type*: rvalue.
#### `basename`
@ -131,9 +191,22 @@ Converts a boolean to a number. Converts values:
* 'true', 't', '1', 'y', and 'yes' to 1.
Requires a single boolean or string as an input. *Type*: rvalue.
#### `bool2str`
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'.
*Examples:*
~~~
bool2str(true) => 'true'
bool2str(true, 'yes', 'no') => 'yes'
bool2str(false, 't', 'f') => 'f'
~~~
Requires a single boolean as input. *Type*: rvalue.
#### `capitalize`
Capitalizes the first letter of a string or array of strings. Requires either a single string or an array as an input. *Type*: rvalue.
Capitalizes 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.
#### `ceiling`
@ -147,6 +220,14 @@ Removes the record separator from the end of a string or an array of strings; fo
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. 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.
#### `clamp`
Keeps 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:
* `clamp('24', [575, 187])` returns 187.
* `clamp(16, 88, 661)` returns 88.
* `clamp([4, 3, '99'])` returns 4.
*Type*: rvalue.
#### `concat`
Appends the contents of multiple arrays onto the first array given. For example:
@ -154,6 +235,12 @@ Appends the contents of multiple arrays onto the first array given. For example:
* `concat(['1','2','3'],'4',['5','6','7'])` returns ['1','2','3','4','5','6','7'].
*Type*: rvalue.
#### `convert_base`
Converts a given integer or base 10 string representing an integer to a specified base, as a string. For example:
* `convert_base(5, 2)` results in: '101'
* `convert_base('254', '16')` results in: 'fe'
#### `count`
If 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.
@ -176,12 +263,24 @@ Takes a resource reference and an optional hash of attributes. Returns 'true' if
#### `delete`
Deletes all instances of a given element from an array, substring from a string, or key from a hash. For 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}. *Type*: rvalue.
Deletes all instances of a given element from an array, substring from a string, or key from a hash.
For 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'].
*Type*: rvalue.
#### `delete_at`
Deletes a determined indexed value from an array. For example, `delete_at(['a','b','c'], 1)` returns ['a','c']. *Type*: rvalue.
#### `delete_regex`
Deletes 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.
For 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'].
*Type*: rvalue.
#### `delete_values`
Deletes 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.
@ -194,25 +293,124 @@ Deletes all instances of the undef value from an array or hash. For example, `$h
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. For example, `difference(["a","b","c"],["b","c","d"])` returns ["a"]. *Type*: rvalue.
#### `dig`
DEPRECATED: This function has been replaced in Puppet 4.5.0, use dig44() for backwards compatibility or use the new version.
*Type*: rvalue.
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.
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.
~~~ruby
$data = {
'a' => {
'b' => [
'b1',
'b2',
'b3',
]
}
}
$value = dig($data, ['a', 'b', 2])
# $value = 'b3'
# with all possible options
$value = dig($data, ['a', 'b', 2], 'not_found')
# $value = 'b3'
# using the default value
$value = dig($data, ['a', 'b', 'c', 'd'], 'not_found')
# $value = 'not_found'
~~~
1. **$data** The data structure we are working with.
2. **['a', 'b', 2]** The path array.
3. **'not_found'** The default value. It will be returned if nothing is found.
(optional, defaults to *undef*)
#### `dig44`
*Type*: rvalue.
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.
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.
~~~ruby
$data = {
'a' => {
'b' => [
'b1',
'b2',
'b3',
]
}
}
$value = dig44($data, ['a', 'b', 2])
# $value = 'b3'
# with all possible options
$value = dig44($data, ['a', 'b', 2], 'not_found')
# $value = 'b3'
# using the default value
$value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found')
# $value = 'not_found'
~~~
1. **$data** The data structure we are working with.
2. **['a', 'b', 2]** The path array.
3. **'not_found'** The default value. It will be returned if nothing is found.
(optional, defaults to *undef*)
#### `dirname`
Returns the `dirname` of a path. For example, `dirname('/path/to/a/file.ext')` returns '/path/to/a'. *Type*: rvalue.
#### `dos2unix`
Returns the Unix version of the given string. Very useful when using a File resource with a cross-platform template. *Type*: rvalue.
~~~
file{$config_file:
ensure => file,
content => dos2unix(template('my_module/settings.conf.erb')),
}
~~~
See also [unix2dos](#unix2dos).
#### `downcase`
Converts the case of a string or of all strings in an array to lowercase. *Type*: rvalue.
#### `empty`
Returns 'true' if the variable is empty. *Type*: rvalue.
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. *Type*: rvalue.
#### `enclose_ipv6`
Takes an array of ip addresses and encloses the ipv6 addresses with square brackets. *Type*: rvalue.
#### `ensure_packages`
Takes a list of packages 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()` function. *Type*: statement.
Takes 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.
For Array:
ensure_packages(['ksh','openssl'], {'ensure' => 'present'})
For Hash:
ensure_packages({'ksh' => { ensure => '20120801-1' } , 'mypackage' => { source => '/tmp/myrpm-1.0.0.x86_64.rpm', provider => "rpm" }}, {'ensure' => 'present'})
#### `ensure_resource`
Takes a resource type, title, and a list of attributes that describe a resource.
Takes a resource type, title, and a hash of attributes that describe the resource(s).
~~~
user { 'dan':
@ -232,7 +430,37 @@ An array of resources can also be passed in, and each will be created with the t
*Type*: statement.
#### `flatten`
#### `ensure_resources`
Takes a resource type, title (only hash), and a hash of attributes that describe the resource(s).
~~~
user { 'dan':
gid => 'mygroup',
ensure => present,
}
ensure_resources($user)
~~~
An hash of resources should be passed in and each will be created with the type and parameters specified if it doesn't already exist:
ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'})
From Hiera Backend:
~~~
userlist:
dan:
gid: 'mygroup'
uid: '600'
alex:
gid: 'mygroup'
ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'})
~~~
### `flatten`
Flattens deeply nested arrays and returns a single flat array as a result. For example, `flatten(['a', ['b', ['c']]])` returns ['a','b','c']. *Type*: rvalue.
@ -262,10 +490,13 @@ fqdn_rand_string(10, '', 'custom seed')
Rotates an array or string a random number of times, combining the `$fqdn` fact and an optional seed for repeatable randomness.
*Usage:*
~~~
fqdn_rotate(VALUE, [SEED])
~~~
*Examples:*
~~~
fqdn_rotate(['a', 'b', 'c', 'd'])
fqdn_rotate('abcd')
@ -383,6 +614,33 @@ Converts an array into a hash. For example, `hash(['a',1,'b',2,'c',3])` returns
Returns an array an intersection of two. For example, `intersection(["a","b","c"],["b","c","d"])` returns ["b","c"]. *Type*: rvalue.
#### `is_a`
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.
~~~
foo = 3
$bar = [1,2,3]
$baz = 'A string!'
if $foo.is_a(Integer) {
notify { 'foo!': }
}
if $bar.is_a(Array) {
notify { 'bar!': }
}
if $baz.is_a(String) {
notify { 'baz!': }
}
~~~
See the [the Puppet type system](https://docs.puppetlabs.com/references/latest/type.html#about-resource-types) for more information about types.
See the [`assert_type()`](https://docs.puppetlabs.com/references/latest/function.html#asserttype) function for flexible ways to assert the type of a value.
#### `is_absolute_path`
Returns 'true' if the given path is absolute. *Type*: rvalue.
#### `is_array`
Returns 'true' if the variable passed to this function is an array. *Type*: rvalue.
@ -415,6 +673,14 @@ Returns 'true' if the variable returned to this string is an integer. *Type*: rv
Returns 'true' if the string passed to this function is a valid IP address. *Type*: rvalue.
#### `is_ipv6_address`
Returns 'true' if the string passed to this function is a valid IPv6 address. *Type*: rvalue.
#### `is_ipv4_address`
Returns 'true' if the string passed to this function is a valid IPv4 address. *Type*: rvalue.
#### `is_mac_address`
Returns 'true' if the string passed to this function is a valid MAC address. *Type*: rvalue.
@ -441,12 +707,62 @@ Returns the keys of a hash as an array. *Type*: rvalue.
#### `loadyaml`
Loads a YAML file containing an array, string, or hash, and returns the data in the corresponding native data type. For example:
Loads a YAML file containing an array, string, or hash, and returns the data in the corresponding native data type.
For example:
~~~
$myhash = loadyaml('/etc/puppet/data/myhash.yaml')
~~~
The second parameter will be returned if the file was not found or could not be parsed.
For example:
~~~
$myhash = loadyaml('no-file.yaml', {'default'=>'value'})
~~~
*Type*: rvalue.
#### `loadjson`
Loads a JSON file containing an array, string, or hash, and returns the data in the corresponding native data type.
For example:
~~~
$myhash = loadjson('/etc/puppet/data/myhash.json')
~~~
The second parameter will be returned if the file was not found or could not be parsed.
For example:
~~~
$myhash = loadjson('no-file.json', {'default'=>'value'})
~~~
*Type*: rvalue.
#### `load_module_metadata`
Loads the metadata.json of a target module. Can be used to determine module version and authorship for dynamic support of modules.
~~~
$metadata = load_module_metadata('archive')
notify { $metadata['author']: }
~~~
If you do not want to fail the catalog compilation when a module's metadata file is absent:
~~~
$metadata = load_module_metadata('mysql', true)
if empty($metadata) {
notify { "This module does not have a metadata.json file.": }
}
~~~
*Type*: rvalue.
#### `lstrip`
@ -459,7 +775,7 @@ Returns the highest value of all arguments. Requires at least one argument. *Typ
#### `member`
This 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.
This 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.
*Type*: rvalue.
@ -489,11 +805,11 @@ Converts a number or a string representation of a number into a true boolean. Ze
#### `parsejson`
Converts a string of JSON into the correct Puppet structure. *Type*: rvalue.
Converts a string of JSON into the correct Puppet structure. *Type*: rvalue. The optional second argument is returned if the data was not correct.
#### `parseyaml`
Converts a string of YAML into the correct Puppet structure. *Type*: rvalue.
Converts a string of YAML into the correct Puppet structure. *Type*: rvalue. The optional second argument is returned if the data was not correct.
#### `pick`
@ -505,12 +821,16 @@ From a list of values, returns the first value that is not undefined or an empty
*Type*: rvalue.
#### `pick_default`
Returns 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.
#### `prefix`
Applies a prefix to all elements in an array, or to the keys in a hash.
For example:
Applies a prefix to all elements in an array, or to the keys in a hash.
For example:
* `prefix(['a','b','c'], 'p')` returns ['pa','pb','pc']
* `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'pa'=>'b','pb'=>'c','pc'=>'d'}.
* `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'pa'=>'b','pb'=>'c','pc'=>'d'}.
*Type*: rvalue.
@ -548,6 +868,8 @@ The second argument to this function is which type of hash to use. It will be co
The third argument to this function is the salt to use.
*Type*: rvalue.
**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.
#### `range`
@ -572,13 +894,51 @@ Reverses the order of a string or array. *Type*: rvalue.
Strips spaces to the right of the string. *Type*: rvalue.
#### `seeded_rand`
Takes 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.
#### `shell_escape`
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 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).
*Example:*
~~~
shell_escape('foo b"ar') => 'foo\ b\"ar'
~~~
*Type*: rvalue.
#### `shell_join`
Builds a command line string from the 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, also see the [ruby documentation](http://ruby-doc.org/stdlib-2.3.0/libdoc/shellwords/rdoc/Shellwords.html#method-c-shelljoin).
*Example:*
~~~
shell_join(['foo bar', 'ba"z']) => 'foo\ bar ba\"z'
~~~
*Type*: rvalue.
#### `shell_split`
Splits 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).
*Example:*
~~~
shell_split('foo\ bar ba\"z') => ['foo bar', 'ba"z']
~~~
*Type*: rvalue.
#### `shuffle`
Randomizes the order of a string or array elements. *Type*: rvalue.
#### `size`
Returns the number of elements in a string or an array. *Type*: rvalue.
Returns the number of elements in a string, an array or a hash. *Type*: rvalue.
#### `sort`
@ -590,7 +950,7 @@ Returns a new string where runs of the same character that occur in this set are
#### `str2bool`
Converts a string to a boolean. This attempts to convert strings that contain values such as '1', 't', 'y', and 'yes' to 'true' and strings that contain values such as '0', 'f', 'n', and 'no' to 'false'. *Type*: rvalue.
Converts 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.
#### `str2saltedsha512`
@ -655,7 +1015,12 @@ Removes leading and trailing whitespace from a string or from every string insid
#### `suffix`
Applies a suffix to all elements in an array. For example, `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp']. *Type*: rvalue.
Applies a suffix to all elements in an array, or to the keys in a hash.
For example:
* `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp']
* `suffix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'ap'=>'b','bp'=>'c','cp'=>'d'}.
*Type*: rvalue.
#### `swapcase`
@ -669,6 +1034,50 @@ Returns the current Unix epoch time as an integer. For example, `time()` returns
Converts the argument into bytes, for example "4 kB" becomes "4096". Takes a single string value as an argument. *Type*: rvalue.
#### `try_get_value`
*Type*: rvalue.
DEPRECATED: replaced by `dig()`.
Retrieves 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.
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. The last argument can set the path separator character.
~~~ruby
$data = {
'a' => {
'b' => [
'b1',
'b2',
'b3',
]
}
}
$value = try_get_value($data, 'a/b/2')
# $value = 'b3'
# with all possible options
$value = try_get_value($data, 'a/b/2', 'not_found', '/')
# $value = 'b3'
# using the default value
$value = try_get_value($data, 'a/b/c/d', 'not_found')
# $value = 'not_found'
# using custom separator
$value = try_get_value($data, 'a|b', [], '|')
# $value = ['b1','b2','b3']
~~~
1. **$data** The data structure we are working with.
2. **'a/b/2'** The path string.
3. **'not_found'** The default value. It will be returned if nothing is found.
(optional, defaults to *undef*)
4. **'/'** The path separator character.
(optional, defaults to *'/'*)
#### `type3x`
Returns 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.
@ -679,12 +1088,25 @@ Returns the literal type when passed a value. Requires the new parser. Useful fo
#### `union`
Returns a union of two arrays, without duplicates. For example, `union(["a","b","c"],["b","c","d"])` returns ["a","b","c","d"].
Returns 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.
#### `unique`
Removes 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.
#### `unix2dos`
Returns the DOS version of the given string. Very useful when using a File resource with a cross-platform template. *Type*: rvalue.
~~~
file{$config_file:
ensure => file,
content => unix2dos(template('my_module/settings.conf.erb')),
}
~~~
See also [dos2unix](#dos2unix).
#### `upcase`
Converts an object, array or hash of objects that respond to upcase to uppercase. For example, `upcase('abcd')` returns 'ABCD'. *Type*: rvalue.
@ -888,10 +1310,42 @@ Validates that the first argument is an integer (or an array of integers). Abort
* Plus all of the above, but any combination of values passed as strings ('false' or "false").
* Plus all of the above, but with incorrect combinations of negative integer values.
* Plus all of the above, but with non-integer crap in arrays or maximum / minimum argument.
* Plus all of the above, but with non-integer items in arrays or maximum / minimum argument.
*Type*: statement.
#### `validate_ip_address`
Validates that the argument is an IP address, regardless of it is an IPv4 or an IPv6
address. It also validates IP address with netmask. The argument must be given as a string.
The following values will pass:
~~~
validate_ip_address('0.0.0.0')
validate_ip_address('8.8.8.8')
validate_ip_address('127.0.0.1')
validate_ip_address('194.232.104.150')
validate_ip_address('3ffe:0505:0002::')
validate_ip_address('::1/64')
validate_ip_address('fe80::a00:27ff:fe94:44d6/64')
validate_ip_address('8.8.8.8/32')
~~~
The following values will fail, causing compilation to abort:
~~~
validate_ip_address(1)
validate_ip_address(true)
validate_ip_address(0.0.0.256)
validate_ip_address('::1', {})
validate_ip_address('0.0.0.0.0')
validate_ip_address('3.3.3')
validate_ip_address('23.43.9.22/64')
validate_ip_address('260.2.32.43')
~~~
#### `validate_numeric`
Validates that the first argument is a numeric value (or an array of numeric values). Aborts catalog compilation if any of the checks fail.
@ -934,17 +1388,24 @@ test, and the second argument should be a stringified regular expression (withou
validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7')
~~~
Note: Compilation terminates if the first argument is not a string. Always use quotes to force stringification:
~~~
validate_re("${::operatingsystemmajrelease}", '^[57]$')
~~~
*Type*: statement.
#### `validate_slength`
Validates 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 arg 2 is not convertable to a number.
Validates 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.
The following values pass:
~~~
validate_slength("discombobulate",17)
validate_slength(["discombobulate","moo"],17)
validate_slength(["discombobulate","moo"],17,3)
~~~
The following values fail:
@ -952,6 +1413,7 @@ Validates that the first argument is a string (or an array of strings), and is l
~~~
validate_slength("discombobulate",1)
validate_slength(["discombobulate","thermometer"],5)
validate_slength(["discombobulate","moo"],17,10)
~~~
*Type*: statement.
@ -986,9 +1448,25 @@ Instead, use:
*Type*: statement.
#### `validate_x509_rsa_key_pair`
Validates a PEM-formatted X.509 certificate and private key using OpenSSL.
Verifies that the certficate's signature was created from the supplied key.
Fails catalog compilation if any value fails this check.
Takes two arguments, the first argument must be a X.509 certificate and the
second must be an RSA private key:
~~~
validate_x509_rsa_key_pair($cert, $key)
~~~
*Type*: statement.
#### `values`
Returns the values of a given hash. For example, given `$hash = {'a'=1, 'b'=2, 'c'=3} values($hash)` returns [1,2,3].
Returns the values of a given hash. For example, given `$hash = {'a'=1, 'b'=2, 'c'=3} values($hash)` returns [1,2,3].
*Type*: rvalue.
@ -1008,7 +1486,7 @@ Finds values inside an array based on location. The first argument is the array
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.
##Limitations
## Limitations
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.
@ -1019,21 +1497,18 @@ Versions | Puppet 2.6 | Puppet 2.7 | Puppet 3.x | Puppet 4.x |
**stdlib 2.x** | **yes** | **yes** | no | no
**stdlib 3.x** | no | **yes** | **yes** | no
**stdlib 4.x** | no | **yes** | **yes** | no
**stdlib 4.6+** | no | **yes** | **yes** | **yes**
**stdlib 5.x** | no | no | **yes** | **yes**
**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).
##Development
## Development
Puppet Labs modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We cant 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)
Puppet Labs modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We cant 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).
To report or research a bug with any part of this module, please go to
[http://tickets.puppetlabs.com/browse/PUP](http://tickets.puppetlabs.com/browse/PUP).
##Contributors
The list of contributors can be found at: https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors
## Contributors
The list of contributors can be found at: [https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors](https://github.com/puppetlabs/puppetlabs-stdlib/graphs/contributors).

View file

@ -1,7 +1,42 @@
require 'rubygems'
# keep for compatibility for now
require 'puppetlabs_spec_helper/rake_tasks'
require 'puppet_blacksmith/rake_tasks'
require 'puppet-lint/tasks/puppet-lint'
PuppetLint.configuration.send('disable_80chars')
PuppetLint.configuration.ignore_paths = ["spec/**/*.pp", "pkg/**/*.pp"]
require 'puppetlabs_spec_helper/rake_tasks'
PuppetLint.configuration.fail_on_warnings = true
PuppetLint.configuration.send('relative')
PuppetLint.configuration.send('disable_140chars')
PuppetLint.configuration.send('disable_class_inherits_from_params_class')
PuppetLint.configuration.send('disable_documentation')
PuppetLint.configuration.send('disable_single_quote_string_with_variables')
PuppetLint.configuration.ignore_paths = ["spec/**/*.pp", "pkg/**/*.pp", "bundle/**/*", "vendor/**/*"]
desc 'Generate pooler nodesets'
task :gen_nodeset do
require 'beaker-hostgenerator'
require 'securerandom'
require 'fileutils'
agent_target = ENV['TEST_TARGET']
if ! agent_target
STDERR.puts 'TEST_TARGET environment variable is not set'
STDERR.puts 'setting to default value of "redhat-64default."'
agent_target = 'redhat-64default.'
end
master_target = ENV['MASTER_TEST_TARGET']
if ! master_target
STDERR.puts 'MASTER_TEST_TARGET environment variable is not set'
STDERR.puts 'setting to default value of "redhat7-64mdcl"'
master_target = 'redhat7-64mdcl'
end
targets = "#{master_target}-#{agent_target}"
cli = BeakerHostGenerator::CLI.new([targets])
nodeset_dir = "tmp/nodesets"
nodeset = "#{nodeset_dir}/#{targets}-#{SecureRandom.uuid}.yaml"
FileUtils.mkdir_p(nodeset_dir)
File.open(nodeset, 'w') do |fh|
fh.print(cli.execute)
end
puts nodeset
end

View file

@ -1,8 +1,8 @@
# This is a simple smoke test
# of the file_line resource type.
file { '/tmp/dansfile':
ensure => present
}->
ensure => file,
} ->
file_line { 'dans_line':
line => 'dan is awesome',
path => '/tmp/dansfile',

View file

@ -1,4 +1,4 @@
include stdlib
include ::stdlib
info('has_interface_with(\'lo\'):', has_interface_with('lo'))
info('has_interface_with(\'loX\'):', has_interface_with('loX'))
info('has_interface_with(\'ipaddress\', \'127.0.0.1\'):', has_interface_with('ipaddress', '127.0.0.1'))
@ -7,4 +7,3 @@ info('has_interface_with(\'network\', \'127.0.0.0\'):', has_interface_with('netw
info('has_interface_with(\'network\', \'128.0.0.0\'):', has_interface_with('network', '128.0.0.0'))
info('has_interface_with(\'netmask\', \'255.0.0.0\'):', has_interface_with('netmask', '255.0.0.0'))
info('has_interface_with(\'netmask\', \'256.0.0.0\'):', has_interface_with('netmask', '256.0.0.0'))

View file

@ -1,3 +1,3 @@
include stdlib
include ::stdlib
info('has_ip_address(\'192.168.1.256\'):', has_ip_address('192.168.1.256'))
info('has_ip_address(\'127.0.0.1\'):', has_ip_address('127.0.0.1'))

View file

@ -1,4 +1,3 @@
include stdlib
include ::stdlib
info('has_ip_network(\'127.0.0.0\'):', has_ip_network('127.0.0.0'))
info('has_ip_network(\'128.0.0.0\'):', has_ip_network('128.0.0.0'))

1
examples/init.pp Normal file
View file

@ -0,0 +1 @@
include ::stdlib

View file

@ -48,7 +48,7 @@ class Facter::Util::DotD
end
end
end
rescue Exception => e
rescue StandardError => e
Facter.warn("Failed to handle #{file} as text facts: #{e.class}: #{e}")
end
@ -65,7 +65,7 @@ class Facter::Util::DotD
setcode { v }
end
end
rescue Exception => e
rescue StandardError => e
Facter.warn("Failed to handle #{file} as json facts: #{e.class}: #{e}")
end
@ -77,7 +77,7 @@ class Facter::Util::DotD
setcode { v }
end
end
rescue Exception => e
rescue StandardError => e
Facter.warn("Failed to handle #{file} as yaml facts: #{e.class}: #{e}")
end
@ -106,7 +106,7 @@ class Facter::Util::DotD
end
end
end
rescue Exception => e
rescue StandardError => e
Facter.warn("Failed to handle #{file} as script facts: #{e.class}: #{e}")
Facter.debug(e.backtrace.join("\n\t"))
end

View file

@ -0,0 +1,21 @@
# Fact: package_provider
#
# Purpose: Returns the default provider Puppet will choose to manage packages
# on this system
#
# Resolution: Instantiates a dummy package resource and return the provider
#
# Caveats:
#
require 'puppet/type'
require 'puppet/type/package'
Facter.add(:package_provider) do
setcode do
if defined? Gem and Gem::Version.new(Facter.value(:puppetversion).split(' ')[0]) >= Gem::Version.new('3.6')
Puppet::Type.type(:package).newpackage(:name => 'dummy', :allow_virtual => 'true')[:provider].to_s
else
Puppet::Type.type(:package).newpackage(:name => 'dummy')[:provider].to_s
end
end
end

View file

@ -10,8 +10,13 @@
#
Facter.add("pe_version") do
setcode do
pe_ver = Facter.value("puppetversion").match(/Puppet Enterprise (\d+\.\d+\.\d+)/)
pe_ver[1] if pe_ver
puppet_ver = Facter.value("puppetversion")
if puppet_ver != nil
pe_ver = puppet_ver.match(/Puppet Enterprise (\d+\.\d+\.\d+)/)
pe_ver[1] if pe_ver
else
nil
end
end
end

View file

@ -30,3 +30,16 @@ Facter.add(:root_home) do
hash['dir'].strip
end
end
Facter.add(:root_home) do
confine :kernel => :aix
root_home = nil
setcode do
str = Facter::Util::Resolution.exec("lsuser -c -a home root")
str && str.split("\n").each do |line|
next if line =~ /^#/
root_home = line.split(/:/)[1]
end
root_home
end
end

View file

@ -0,0 +1,17 @@
# Fact: service_provider
#
# Purpose: Returns the default provider Puppet will choose to manage services
# on this system
#
# Resolution: Instantiates a dummy service resource and return the provider
#
# Caveats:
#
require 'puppet/type'
require 'puppet/type/service'
Facter.add(:service_provider) do
setcode do
Puppet::Type.type(:service).newservice(:name => 'dummy')[:provider].to_s
end
end

View file

@ -0,0 +1,32 @@
# Boolean check to determine whether a variable is of a given data type. This is equivalent to the `=~` type checks.
#
# @example how to check a data type
# # check a data type
# foo = 3
# $bar = [1,2,3]
# $baz = 'A string!'
#
# if $foo.is_a(Integer) {
# notify { 'foo!': }
# }
# if $bar.is_a(Array) {
# notify { 'bar!': }
# }
# if $baz.is_a(String) {
# notify { 'baz!': }
# }
#
# See the documentation for "The Puppet Type System" for more information about types.
# See the `assert_type()` function for flexible ways to assert the type of a value.
#
Puppet::Functions.create_function(:is_a) do
dispatch :is_a do
param 'Any', :value
param 'Type', :type
end
def is_a(value, type)
# See puppet's lib/puppet/pops/evaluator/evaluator_impl.rb eval_MatchExpression
Puppet::Pops::Types::TypeCalculator.instance?(type, value)
end
end

View file

@ -0,0 +1,55 @@
#
# any2bool.rb
#
module Puppet::Parser::Functions
newfunction(:any2bool, :type => :rvalue, :doc => <<-EOS
This converts 'anything' to a boolean. In practise it does the following:
* Strings such as Y,y,1,T,t,TRUE,yes,'true' will return true
* Strings such as 0,F,f,N,n,FALSE,no,'false' will return false
* Booleans will just return their original value
* Number (or a string representation of a number) > 0 will return true, otherwise false
* undef will return false
* Anything else will return true
EOS
) do |arguments|
raise(Puppet::ParseError, "any2bool(): Wrong number of arguments " +
"given (#{arguments.size} for 1)") if arguments.size < 1
# If argument is already Boolean, return it
if !!arguments[0] == arguments[0]
return arguments[0]
end
arg = arguments[0]
if arg == nil
return false
end
if arg == :undef
return false
end
valid_float = !!Float(arg) rescue false
if arg.is_a?(Numeric)
return function_num2bool( [ arguments[0] ] )
end
if arg.is_a?(String)
if valid_float
return function_num2bool( [ arguments[0] ] )
else
return function_str2bool( [ arguments[0] ] )
end
end
return true
end
end
# vim: set ts=2 sw=2 et :

View file

@ -6,14 +6,19 @@ module Puppet::Parser::Functions
Usage:
$encodestring = base64('encode','thestring')
$decodestring = base64('decode','dGhlc3RyaW5n')
$encodestring = base64('encode', 'thestring')
$decodestring = base64('decode', 'dGhlc3RyaW5n')
# explicitly define encode/decode method: default, strict, urlsafe
$method = 'default'
$encodestring = base64('encode', 'thestring', $method)
$decodestring = base64('decode', 'dGhlc3RyaW5n', $method)
ENDHEREDOC
require 'base64'
raise Puppet::ParseError, ("base64(): Wrong number of arguments (#{args.length}; must be = 2)") unless args.length == 2
raise Puppet::ParseError, ("base64(): Wrong number of arguments (#{args.length}; must be >= 2)") unless args.length >= 2
actions = ['encode','decode']
@ -25,11 +30,37 @@ module Puppet::Parser::Functions
raise Puppet::ParseError, ("base64(): the second argument must be a string to base64")
end
method = ['default','strict','urlsafe']
if args.length <= 2
chosenMethod = 'default'
else
chosenMethod = args[2]
end
unless method.include?(chosenMethod)
raise Puppet::ParseError, ("base64(): the third argument must be one of 'default', 'strict', or 'urlsafe'")
end
case args[0]
when 'encode'
result = Base64.encode64(args[1])
case chosenMethod
when 'default'
result = Base64.encode64(args[1])
when 'strict'
result = Base64.strict_encode64(args[1])
when 'urlsafe'
result = Base64.urlsafe_encode64(args[1])
end
when 'decode'
result = Base64.decode64(args[1])
case chosenMethod
when 'default'
result = Base64.decode64(args[1])
when 'strict'
result = Base64.strict_decode64(args[1])
when 'urlsafe'
result = Base64.urlsafe_decode64(args[1])
end
end
return result

View file

@ -4,15 +4,29 @@
module Puppet::Parser::Functions
newfunction(:bool2str, :type => :rvalue, :doc => <<-EOS
Converts a boolean to a string.
Converts a boolean to a string using optionally supplied arguments. The
optional second and third arguments represent what true and false will be
converted to respectively. If only one argument is given, it will be
converted from a boolean to a string containing 'true' or 'false'.
*Examples:*
bool2str(true) => 'true'
bool2str(true, 'yes', 'no') => 'yes'
bool2str(false, 't', 'f') => 'f'
Requires a single boolean as an input.
EOS
) do |arguments|
raise(Puppet::ParseError, "bool2str(): Wrong number of arguments " +
"given (#{arguments.size} for 1)") if arguments.size < 1
unless arguments.size == 1 or arguments.size == 3
raise(Puppet::ParseError, "bool2str(): Wrong number of arguments " +
"given (#{arguments.size} for 3)")
end
value = arguments[0]
true_string = arguments[1] || 'true'
false_string = arguments[2] || 'false'
klass = value.class
# We can have either true or false, and nothing else
@ -20,7 +34,11 @@ module Puppet::Parser::Functions
raise(Puppet::ParseError, 'bool2str(): Requires a boolean to work with')
end
return value.to_s
unless [true_string, false_string].all?{|x| x.kind_of?(String)}
raise(Puppet::ParseError, "bool2str(): Requires strings to convert to" )
end
return value ? true_string : false_string
end
end

View file

@ -0,0 +1,30 @@
#
# clamp.rb
#
module Puppet::Parser::Functions
newfunction(:clamp, :type => :rvalue, :arity => -2, :doc => <<-EOS
Clamps value to a range.
EOS
) do |args|
args.flatten!
raise(Puppet::ParseError, 'clamp(): Wrong number of arguments, ' +
'need three to clamp') if args.size != 3
# check values out
args.each do |value|
case [value.class]
when [String]
raise(Puppet::ParseError, "clamp(): Required explicit numeric (#{value}:String)") unless value =~ /^\d+$/
when [Hash]
raise(Puppet::ParseError, "clamp(): The Hash type is not allowed (#{value})")
end
end
# convert to numeric each element
# then sort them and get a middle value
args.map{ |n| n.to_i }.sort[1]
end
end

View file

@ -31,7 +31,7 @@ Would result in:
arguments.shift
arguments.each do |x|
result = result + Array(x)
result = result + (x.is_a?(Array) ? x : [x])
end
return result

View file

@ -0,0 +1,35 @@
module Puppet::Parser::Functions
newfunction(:convert_base, :type => :rvalue, :arity => 2, :doc => <<-'ENDHEREDOC') do |args|
Converts a given integer or base 10 string representing an integer to a specified base, as a string.
Usage:
$binary_repr = convert_base(5, 2) # $binary_repr is now set to "101"
$hex_repr = convert_base("254", "16") # $hex_repr is now set to "fe"
ENDHEREDOC
raise Puppet::ParseError, ("convert_base(): First argument must be either a string or an integer") unless (args[0].is_a?(Integer) or args[0].is_a?(String))
raise Puppet::ParseError, ("convert_base(): Second argument must be either a string or an integer") unless (args[1].is_a?(Integer) or args[1].is_a?(String))
if args[0].is_a?(String)
raise Puppet::ParseError, ("convert_base(): First argument must be an integer or a string corresponding to an integer in base 10") unless args[0] =~ /^[0-9]+$/
end
if args[1].is_a?(String)
raise Puppet::ParseError, ("convert_base(): First argument must be an integer or a string corresponding to an integer in base 10") unless args[1] =~ /^[0-9]+$/
end
number_to_convert = args[0]
new_base = args[1]
number_to_convert = number_to_convert.to_i()
new_base = new_base.to_i()
raise Puppet::ParseError, ("convert_base(): base must be at least 2 and must not be greater than 36") unless new_base >= 2 and new_base <= 36
return number_to_convert.to_s(new_base)
end
end

View file

@ -26,7 +26,10 @@ ENDOFDOC
ret = false
if resource = findresource(reference.to_s)
matches = params.collect do |key, value|
resource[key] == value
# eql? avoids bugs caused by monkeypatching in puppet
resource_is_undef = resource[key].eql?(:undef) || resource[key].nil?
value_is_undef = value.eql?(:undef) || value.nil?
(resource_is_undef && value_is_undef) || (resource[key] == value)
end
ret = params.empty? || !matches.include?(false)
end

View file

@ -2,8 +2,6 @@
# delete.rb
#
# TODO(Krzysztof Wilczynski): We need to add support for regular expression ...
module Puppet::Parser::Functions
newfunction(:delete, :type => :rvalue, :doc => <<-EOS
Deletes all instances of a given element from an array, substring from a
@ -25,10 +23,8 @@ string, or key from a hash.
EOS
) do |arguments|
if (arguments.size != 2) then
raise(Puppet::ParseError, "delete(): Wrong number of arguments "+
"given #{arguments.size} for 2.")
end
raise(Puppet::ParseError, "delete(): Wrong number of arguments "+
"given #{arguments.size} for 2") unless arguments.size == 2
collection = arguments[0].dup
Array(arguments[1]).each do |item|

View file

@ -0,0 +1,45 @@
#
# delete_regex.rb
#
module Puppet::Parser::Functions
newfunction(:delete_regex, :type => :rvalue, :doc => <<-EOS
deletes all instances of a given element that match a regular expression
from an array or key from a hash. Multiple regular expressions are assumed
to be matched as an OR.
*Examples:*
delete_regex(['a','b','c','b'], 'b')
Would return: ['a','c']
delete_regex(['a','b','c','b'], ['b', 'c'])
Would return: ['a']
delete_regex({'a'=>1,'b'=>2,'c'=>3}, 'b')
Would return: {'a'=>1,'c'=>3}
delete_regex({'a'=>1,'b'=>2,'c'=>3}, '^a$')
Would return: {'b'=>2,'c'=>3}
EOS
) do |arguments|
raise(Puppet::ParseError, "delete_regex(): Wrong number of arguments "+
"given #{arguments.size} for 2") unless arguments.size == 2
collection = arguments[0].dup
Array(arguments[1]).each do |item|
case collection
when Array, Hash, String
collection.reject! { |coll_item| (coll_item =~ %r{\b#{item}\b}) }
else
raise(TypeError, "delete_regex(): First argument must be an Array, " +
"Hash, or String. Given an argument of class #{collection.class}.")
end
end
collection
end
end
# vim: set ts=2 sw=2 et :

View file

@ -0,0 +1,16 @@
#
# dig.rb
#
module Puppet::Parser::Functions
newfunction(:dig, :type => :rvalue, :doc => <<-EOS
DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version.
EOS
) do |arguments|
warning("dig() DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version.")
if ! Puppet::Parser::Functions.autoloader.loaded?(:dig44)
Puppet::Parser::Functions.autoloader.load(:dig44)
end
function_dig44(arguments)
end
end

View file

@ -0,0 +1,56 @@
#
# dig44.rb
#
module Puppet::Parser::Functions
newfunction(:dig44, :type => :rvalue, :doc => <<-EOS
DEPRECATED: This function has been replaced in puppet 4.5.0.
Looks up into a complex structure of arrays and hashes and returns nil
or the default value if nothing was found.
Path is an array of keys to be looked up in data argument. The function
will go down the structure and try to extract the required value.
$data = {
'a' => {
'b' => [
'b1',
'b2',
'b3' ]}}
$value = dig44($data, ['a', 'b', '2'], 'not_found')
=> $value = 'b3'
a -> first hash key
b -> second hash key
2 -> array index starting with 0
not_found -> (optional) will be returned if there is no value or the path
did not match. Defaults to nil.
In addition to the required "path" argument, "dig44" accepts default
argument. It will be returned if no value was found or a path component is
missing. And the fourth argument can set a variable path separator.
EOS
) do |arguments|
# Two arguments are required
raise(Puppet::ParseError, "dig44(): Wrong number of arguments " +
"given (#{arguments.size} for at least 2)") if arguments.size < 2
data, path, default = *arguments
if !(data.is_a?(Hash) || data.is_a?(Array))
raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, " <<
"given #{data.class.name}")
end
unless path.is_a? Array
raise(Puppet::ParseError, "dig44(): second argument must be an array, " <<
"given #{path.class.name}")
end
value = path.reduce(data) { |h, k| (h.is_a?(Hash) || h.is_a?(Array)) ? h[k] : break }
value.nil? ? default : value
end
end

View file

@ -0,0 +1,15 @@
# Custom Puppet function to convert dos to unix format
module Puppet::Parser::Functions
newfunction(:dos2unix, :type => :rvalue, :arity => 1, :doc => <<-EOS
Returns the Unix version of the given string.
Takes a single string argument.
EOS
) do |arguments|
unless arguments[0].is_a?(String)
raise(Puppet::ParseError, 'dos2unix(): Requires string as argument')
end
arguments[0].gsub(/\r\n/, "\n")
end
end

View file

@ -13,14 +13,18 @@ Returns true if the variable is empty.
value = arguments[0]
unless value.is_a?(Array) || value.is_a?(Hash) || value.is_a?(String)
unless value.is_a?(Array) || value.is_a?(Hash) || value.is_a?(String) || value.is_a?(Numeric)
raise(Puppet::ParseError, 'empty(): Requires either ' +
'array, hash or string to work with')
'array, hash, string or integer to work with')
end
result = value.empty?
if value.is_a?(Numeric)
return false
else
result = value.empty?
return result
return result
end
end
end

View file

@ -0,0 +1,45 @@
#
# enclose_ipv6.rb
#
module Puppet::Parser::Functions
newfunction(:enclose_ipv6, :type => :rvalue, :doc => <<-EOS
Takes an array of ip addresses and encloses the ipv6 addresses with square brackets.
EOS
) do |arguments|
require 'ipaddr'
rescuable_exceptions = [ ArgumentError ]
if defined?(IPAddr::InvalidAddressError)
rescuable_exceptions << IPAddr::InvalidAddressError
end
if (arguments.size != 1) then
raise(Puppet::ParseError, "enclose_ipv6(): Wrong number of arguments "+
"given #{arguments.size} for 1")
end
unless arguments[0].is_a?(String) or arguments[0].is_a?(Array) then
raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument type "+
"given #{arguments[0].class} expected String or Array")
end
input = [arguments[0]].flatten.compact
result = []
input.each do |val|
unless val == '*'
begin
ip = IPAddr.new(val)
rescue *rescuable_exceptions
raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument "+
"given #{val} is not an ip address.")
end
val = "[#{ip.to_s}]" if ip.ipv6?
end
result << val
end
return result.uniq
end
end

View file

@ -17,18 +17,29 @@ third argument to the ensure_resource() function.
raise(Puppet::ParseError, 'ensure_packages(): Requires second argument to be a Hash')
end
packages = Array(arguments[0])
if arguments[0].is_a?(Hash)
if arguments[1]
defaults = { 'ensure' => 'present' }.merge(arguments[1])
else
defaults = { 'ensure' => 'present' }
end
if arguments[1]
defaults = { 'ensure' => 'present' }.merge(arguments[1])
Puppet::Parser::Functions.function(:ensure_resources)
function_ensure_resources(['package', Hash(arguments[0]), defaults ])
else
defaults = { 'ensure' => 'present' }
end
packages = Array(arguments[0])
Puppet::Parser::Functions.function(:ensure_resource)
packages.each { |package_name|
function_ensure_resource(['package', package_name, defaults ])
if arguments[1]
defaults = { 'ensure' => 'present' }.merge(arguments[1])
else
defaults = { 'ensure' => 'present' }
end
Puppet::Parser::Functions.function(:ensure_resource)
packages.each { |package_name|
function_ensure_resource(['package', package_name, defaults ])
}
end
end
end

View file

@ -0,0 +1,54 @@
require 'puppet/parser/functions'
Puppet::Parser::Functions.newfunction(:ensure_resources,
:type => :statement,
:doc => <<-'ENDOFDOC'
Takes a resource type, title (only hash), and a list of attributes that describe a
resource.
user { 'dan':
gid => 'mygroup',
ensure => present,
}
An hash of resources should be passed in and each will be created with
the type and parameters specified if it doesn't already exist.
ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'})
From Hiera Backend:
userlist:
dan:
gid: 'mygroup'
uid: '600'
alex:
gid: 'mygroup'
Call:
ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'})
ENDOFDOC
) do |vals|
type, title, params = vals
raise(ArgumentError, 'Must specify a type') unless type
raise(ArgumentError, 'Must specify a title') unless title
params ||= {}
if title.is_a?(Hash)
resource_hash = Hash(title)
resources = resource_hash.keys
Puppet::Parser::Functions.function(:ensure_resource)
resources.each { |resource_name|
if resource_hash[resource_name]
params_merged = params.merge(resource_hash[resource_name])
else
params_merged = params
end
function_ensure_resource([ type, resource_name, params_merged ])
}
else
raise(Puppet::ParseError, 'ensure_resources(): Requires second argument to be a Hash')
end
end

View file

@ -38,8 +38,11 @@ has_interface_with("lo") => true
# Bug with 3.7.1 - 3.7.3 when using future parser throws :undefined_variable
# https://tickets.puppetlabs.com/browse/PUP-3597
factval = nil
catch :undefined_variable do
factval = lookupvar(kind)
begin
catch :undefined_variable do
factval = lookupvar(kind)
end
rescue Puppet::ParseError # Eat the exception if strict_variables = true is set
end
if factval == value
return true

View file

@ -29,7 +29,7 @@ Would return: {'a'=>1,'b'=>2,'c'=>3}
# This is to make it compatible with older version of Ruby ...
array = array.flatten
result = Hash[*array]
rescue Exception
rescue StandardError
raise(Puppet::ParseError, 'hash(): Unable to compute ' +
'hash from array given')
end

View file

@ -4,13 +4,13 @@
module Puppet::Parser::Functions
newfunction(:intersection, :type => :rvalue, :doc => <<-EOS
This function returns an array an intersection of two.
This function returns an array of the intersection of two.
*Examples:*
intersection(["a","b","c"],["b","c","d"])
intersection(["a","b","c"],["b","c","d"]) # returns ["b","c"]
intersection(["a","b","c"],[1,2,3,4]) # returns [] (true, when evaluated as a Boolean)
Would return: ["b","c"]
EOS
) do |arguments|

View file

@ -0,0 +1,50 @@
module Puppet::Parser::Functions
newfunction(:is_absolute_path, :type => :rvalue, :arity => 1, :doc => <<-'ENDHEREDOC') do |args|
Returns boolean true if the string represents an absolute path in the filesystem. This function works
for windows and unix style paths.
The following values will return true:
$my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet'
is_absolute_path($my_path)
$my_path2 = '/var/lib/puppet'
is_absolute_path($my_path2)
$my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet']
is_absolute_path($my_path3)
$my_path4 = ['/var/lib/puppet']
is_absolute_path($my_path4)
The following values will return false:
is_absolute_path(true)
is_absolute_path('../var/lib/puppet')
is_absolute_path('var/lib/puppet')
$undefined = undef
is_absolute_path($undefined)
ENDHEREDOC
require 'puppet/util'
path = args[0]
# This logic was borrowed from
# [lib/puppet/file_serving/base.rb](https://github.com/puppetlabs/puppet/blob/master/lib/puppet/file_serving/base.rb)
# Puppet 2.7 and beyond will have Puppet::Util.absolute_path? Fall back to a back-ported implementation otherwise.
if Puppet::Util.respond_to?(:absolute_path?) then
value = (Puppet::Util.absolute_path?(path, :posix) or Puppet::Util.absolute_path?(path, :windows))
else
# This code back-ported from 2.7.x's lib/puppet/util.rb Puppet::Util.absolute_path?
# Determine in a platform-specific way whether a path is absolute. This
# defaults to the local platform if none is specified.
# Escape once for the string literal, and once for the regex.
slash = '[\\\\/]'
name = '[^\\\\/]+'
regexes = {
:windows => %r!^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))!i,
:posix => %r!^/!
}
value = (!!(path =~ regexes[:posix])) || (!!(path =~ regexes[:windows]))
end
value
end
end

View file

@ -0,0 +1,21 @@
#
# is_email_address.rb
#
module Puppet::Parser::Functions
newfunction(:is_email_address, :type => :rvalue, :doc => <<-EOS
Returns true if the string passed to this function is a valid email address.
EOS
) do |arguments|
if arguments.size != 1
raise(Puppet::ParseError, 'is_email_address(): Wrong number of arguments '\
"given #{arguments.size} for 1")
end
# Taken from http://emailregex.com/ (simpler regex)
valid_email_regex = %r{\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z}
return (arguments[0] =~ valid_email_regex) == 0
end
end
# vim: set ts=2 sw=2 et :

View file

@ -0,0 +1,28 @@
#
# is_ipv4_address.rb
#
module Puppet::Parser::Functions
newfunction(:is_ipv4_address, :type => :rvalue, :doc => <<-EOS
Returns true if the string passed to this function is a valid IPv4 address.
EOS
) do |arguments|
require 'ipaddr'
if (arguments.size != 1) then
raise(Puppet::ParseError, "is_ipv4_address(): Wrong number of arguments "+
"given #{arguments.size} for 1")
end
begin
ip = IPAddr.new(arguments[0])
rescue ArgumentError
return false
end
return ip.ipv4?
end
end
# vim: set ts=2 sw=2 et :

View file

@ -0,0 +1,28 @@
#
# is_ipv6_address.rb
#
module Puppet::Parser::Functions
newfunction(:is_ipv6_address, :type => :rvalue, :doc => <<-EOS
Returns true if the string passed to this function is a valid IPv6 address.
EOS
) do |arguments|
require 'ipaddr'
if (arguments.size != 1) then
raise(Puppet::ParseError, "is_ipv6_address(): Wrong number of arguments "+
"given #{arguments.size} for 1")
end
begin
ip = IPAddr.new(arguments[0])
rescue ArgumentError
return false
end
return ip.ipv6?
end
end
# vim: set ts=2 sw=2 et :

View file

@ -0,0 +1,24 @@
module Puppet::Parser::Functions
newfunction(:load_module_metadata, :type => :rvalue, :doc => <<-EOT
EOT
) do |args|
raise(Puppet::ParseError, "load_module_metadata(): Wrong number of arguments, expects one or two") unless [1,2].include?(args.size)
mod = args[0]
allow_empty_metadata = args[1]
module_path = function_get_module_path([mod])
metadata_json = File.join(module_path, 'metadata.json')
metadata_exists = File.exists?(metadata_json)
if metadata_exists
metadata = PSON.load(File.read(metadata_json))
else
if allow_empty_metadata
metadata = {}
else
raise(Puppet::ParseError, "load_module_metadata(): No metadata.json file for module #{mod}")
end
end
return metadata
end
end

View file

@ -0,0 +1,34 @@
module Puppet::Parser::Functions
newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'ENDHEREDOC') do |args|
Load a JSON file containing an array, string, or hash, and return the data
in the corresponding native data type.
The second parameter is the default value. It will be returned if the file
was not found or could not be parsed.
For example:
$myhash = loadjson('/etc/puppet/data/myhash.json')
$myhash = loadjson('no-file.json', {'default' => 'value'})
ENDHEREDOC
raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1
if File.exists?(args[0])
begin
content = File.read(args[0])
PSON::load(content) || args[1]
rescue Exception => e
if args[1]
args[1]
else
raise e
end
end
else
warning("Can't load '#{args[0]}' File does not exist!")
args[1]
end
end
end

View file

@ -1,23 +1,32 @@
module Puppet::Parser::Functions
newfunction(:loadyaml, :type => :rvalue, :arity => -2, :doc => <<-'ENDHEREDOC') do |args|
Load a YAML file containing an array, string, or hash, and return the data
in the corresponding native data type.
The second parameter is the default value. It will be returned if the file
was not found or could not be parsed.
newfunction(:loadyaml, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args|
Load a YAML file containing an array, string, or hash, and return the data
in the corresponding native data type.
For example:
For example:
$myhash = loadyaml('/etc/puppet/data/myhash.yaml')
$myhash = loadyaml('no-file.yaml', {'default' => 'value'})
ENDHEREDOC
$myhash = loadyaml('/etc/puppet/data/myhash.yaml')
ENDHEREDOC
raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1
require 'yaml'
unless args.length == 1
raise Puppet::ParseError, ("loadyaml(): wrong number of arguments (#{args.length}; must be 1)")
end
if File.exists?(args[0]) then
YAML.load_file(args[0])
if File.exists?(args[0])
begin
YAML::load_file(args[0]) || args[1]
rescue Exception => e
if args[1]
args[1]
else
raise e
end
end
else
warning("Can't load " + args[0] + ". File does not exist!")
nil
warning("Can't load '#{args[0]}' File does not exist!")
args[1]
end
end

View file

@ -4,20 +4,25 @@
module Puppet::Parser::Functions
newfunction(:parsejson, :type => :rvalue, :doc => <<-EOS
This function accepts JSON as a string and converts into the correct Puppet
structure.
EOS
) do |arguments|
This function accepts JSON as a string and converts it into the correct
Puppet structure.
if (arguments.size != 1) then
raise(Puppet::ParseError, "parsejson(): Wrong number of arguments "+
"given #{arguments.size} for 1")
The optional second argument can be used to pass a default value that will
be returned if the parsing of YAML string have failed.
EOS
) do |arguments|
raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1
begin
PSON::load(arguments[0]) || arguments[1]
rescue StandardError => e
if arguments[1]
arguments[1]
else
raise e
end
end
json = arguments[0]
# PSON is natively available in puppet
PSON.load(json)
end
end

View file

@ -6,17 +6,26 @@ module Puppet::Parser::Functions
newfunction(:parseyaml, :type => :rvalue, :doc => <<-EOS
This function accepts YAML as a string and converts it into the correct
Puppet structure.
EOS
The optional second argument can be used to pass a default value that will
be returned if the parsing of YAML string have failed.
EOS
) do |arguments|
if (arguments.size != 1) then
raise(Puppet::ParseError, "parseyaml(): Wrong number of arguments "+
"given #{arguments.size} for 1")
end
raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1
require 'yaml'
YAML::load(arguments[0])
begin
YAML::load(arguments[0]) || arguments[1]
# in ruby 1.9.3 Psych::SyntaxError is a RuntimeException
# this still needs to catch that and work also on rubies that
# do not have Psych available.
rescue StandardError, Psych::SyntaxError => e
if arguments[1]
arguments[1]
else
raise e
end
end
end
end

View file

@ -0,0 +1,22 @@
Puppet::Parser::Functions::newfunction(
:seeded_rand,
:arity => 2,
:type => :rvalue,
:doc => <<-EOS
Usage: `seeded_rand(MAX, SEED)`. MAX must be a positive integer; SEED is any string.
Generates a random whole number greater than or equal to 0 and less
than MAX, using the value of SEED for repeatable randomness. If SEED
starts with "$fqdn:", this is behaves the same as `fqdn_rand`.
EOS
) do |args|
require 'digest/md5'
raise(ArgumentError, "seeded_rand(): first argument must be a positive integer") unless function_is_integer([args[0]]) and args[0].to_i > 0
raise(ArgumentError, "seeded_rand(): second argument must be a string") unless args[1].is_a? String
max = args[0].to_i
seed = Digest::MD5.hexdigest(args[1]).hex
Puppet::Util.deterministic_rand(seed,max)
end

View file

@ -0,0 +1,30 @@
#
# shell_escape.rb
#
require 'shellwords'
module Puppet::Parser::Functions
newfunction(:shell_escape, :type => :rvalue, :doc => <<-EOS
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 double quotes nor in single
quotes.
This function behaves the same as ruby's Shellwords.shellescape() function.
EOS
) do |arguments|
raise(Puppet::ParseError, "shell_escape(): Wrong number of arguments " +
"given (#{arguments.size} for 1)") if arguments.size != 1
# explicit conversion to string is required for ruby 1.9
string = arguments[0].to_s
result = Shellwords.shellescape(string)
return result
end
end
# vim: set ts=2 sw=2 et :

View file

@ -0,0 +1,31 @@
#
# shell_join.rb
#
require 'shellwords'
module Puppet::Parser::Functions
newfunction(:shell_join, :type => :rvalue, :doc => <<-EOS
Builds a command line string from the 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
EOS
) do |arguments|
raise(Puppet::ParseError, "shell_join(): Wrong number of arguments " +
"given (#{arguments.size} for 1)") if arguments.size != 1
array = arguments[0]
raise Puppet::ParseError, ("First argument is not an Array: #{array.inspect}") unless array.is_a?(Array)
# explicit conversion to string is required for ruby 1.9
array = array.map { |item| item.to_s }
result = Shellwords.shelljoin(array)
return result
end
end
# vim: set ts=2 sw=2 et :

View file

@ -0,0 +1,26 @@
#
# shell_split.rb
#
require 'shellwords'
module Puppet::Parser::Functions
newfunction(:shell_split, :type => :rvalue, :doc => <<-EOS
Splits 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
EOS
) do |arguments|
raise(Puppet::ParseError, "shell_split(): Wrong number of arguments " +
"given (#{arguments.size} for 1)") if arguments.size != 1
string = arguments[0].to_s
result = Shellwords.shellsplit(string)
return result
end
end
# vim: set ts=2 sw=2 et :

View file

@ -2,11 +2,9 @@
# size.rb
#
# TODO(Krzysztof Wilczynski): Support for hashes would be nice too ...
module Puppet::Parser::Functions
newfunction(:size, :type => :rvalue, :doc => <<-EOS
Returns the number of elements in a string or array.
Returns the number of elements in a string, an array or a hash
EOS
) do |arguments|
@ -29,13 +27,13 @@ Returns the number of elements in a string or array.
Float(item)
raise(Puppet::ParseError, 'size(): Requires either ' +
'string or array to work with')
'string, array or hash to work with')
rescue ArgumentError
result = item.size
end
elsif item.is_a?(Array)
elsif item.is_a?(Array) || item.is_a?(Hash)
result = item.size
else
raise(Puppet::ParseError, 'size(): Unknown type given')

View file

@ -5,8 +5,8 @@
module Puppet::Parser::Functions
newfunction(:str2bool, :type => :rvalue, :doc => <<-EOS
This converts a string to a boolean. This attempt to convert strings that
contain things like: y, 1, t, true to 'true' and strings that contain things
like: 0, f, n, false, no to 'false'.
contain things like: Y,y, 1, T,t, TRUE,true to 'true' and strings that contain things
like: 0, F,f, N,n, false, FALSE, no to 'false'.
EOS
) do |arguments|
@ -32,8 +32,8 @@ like: 0, f, n, false, no to 'false'.
# We yield false in this case.
#
when /^$/, '' then false # Empty string will be false ...
when /^(1|t|y|true|yes)$/ then true
when /^(0|f|n|false|no)$/ then false
when /^(1|t|y|true|yes)$/i then true
when /^(0|f|n|false|no)$/i then false
when /^(undef|undefined)$/ then false # This is not likely to happen ...
else
raise(Puppet::ParseError, 'str2bool(): Unknown type of boolean given')

View file

@ -4,7 +4,8 @@
module Puppet::Parser::Functions
newfunction(:suffix, :type => :rvalue, :doc => <<-EOS
This function applies a suffix to all elements in an array.
This function applies a suffix to all elements in an array, or to the keys
in a hash.
*Examples:*
@ -18,10 +19,10 @@ Will return: ['ap','bp','cp']
raise(Puppet::ParseError, "suffix(): Wrong number of arguments " +
"given (#{arguments.size} for 1)") if arguments.size < 1
array = arguments[0]
enumerable = arguments[0]
unless array.is_a?(Array)
raise Puppet::ParseError, "suffix(): expected first argument to be an Array, got #{array.inspect}"
unless enumerable.is_a?(Array) or enumerable.is_a?(Hash)
raise Puppet::ParseError, "suffix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}"
end
suffix = arguments[1] if arguments[1]
@ -32,10 +33,17 @@ Will return: ['ap','bp','cp']
end
end
# Turn everything into string same as join would do ...
result = array.collect do |i|
i = i.to_s
suffix ? i + suffix : i
if enumerable.is_a?(Array)
# Turn everything into string same as join would do ...
result = enumerable.collect do |i|
i = i.to_s
suffix ? i + suffix : i
end
else
result = Hash[enumerable.map do |k,v|
k = k.to_s
[ suffix ? k + suffix : k, v ]
end]
end
return result

View file

@ -0,0 +1,53 @@
module Puppet::Parser::Functions
newfunction(
:try_get_value,
:type => :rvalue,
:arity => -2,
:doc => <<-eos
DEPRECATED: this function is deprecated, please use dig() instead.
Looks up into a complex structure of arrays and hashes and returns a value
or the default value if nothing was found.
Key can contain slashes to describe path components. The function will go down
the structure and try to extract the required value.
$data = {
'a' => {
'b' => [
'b1',
'b2',
'b3',
]
}
}
$value = try_get_value($data, 'a/b/2', 'not_found', '/')
=> $value = 'b3'
a -> first hash key
b -> second hash key
2 -> array index starting with 0
not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil.
/ -> (optional) path delimiter. Defaults to '/'.
In addition to the required "key" argument, "try_get_value" accepts default
argument. It will be returned if no value was found or a path component is
missing. And the fourth argument can set a variable path separator.
eos
) do |args|
warning("try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.")
data = args[0]
path = args[1] || ''
default = args[2]
if !(data.is_a?(Hash) || data.is_a?(Array)) || path == ''
return default || data
end
separator = args[3] || '/'
path = path.split(separator).map{ |key| key =~ /^\d+$/ ? key.to_i : key }
function_dig([data, path, default])
end
end

View file

@ -4,7 +4,7 @@
module Puppet::Parser::Functions
newfunction(:union, :type => :rvalue, :doc => <<-EOS
This function returns a union of two arrays.
This function returns a union of two or more arrays.
*Examples:*
@ -14,20 +14,15 @@ Would return: ["a","b","c","d"]
EOS
) do |arguments|
# Two arguments are required
# Check that 2 or more arguments have been given ...
raise(Puppet::ParseError, "union(): Wrong number of arguments " +
"given (#{arguments.size} for 2)") if arguments.size != 2
"given (#{arguments.size} for < 2)") if arguments.size < 2
first = arguments[0]
second = arguments[1]
unless first.is_a?(Array) && second.is_a?(Array)
raise(Puppet::ParseError, 'union(): Requires 2 arrays')
arguments.each do |argument|
raise(Puppet::ParseError, 'union(): Every parameter must be an array') unless argument.is_a?(Array)
end
result = first | second
return result
arguments.reduce(:|)
end
end

View file

@ -0,0 +1,15 @@
# Custom Puppet function to convert unix to dos format
module Puppet::Parser::Functions
newfunction(:unix2dos, :type => :rvalue, :arity => 1, :doc => <<-EOS
Returns the DOS version of the given string.
Takes a single string argument.
EOS
) do |arguments|
unless arguments[0].is_a?(String)
raise(Puppet::ParseError, 'unix2dos(): Requires string as argument')
end
arguments[0].gsub(/\r*\n/, "\r\n")
end
end

View file

@ -12,7 +12,7 @@ Converts a string or an array of strings to uppercase.
Will return:
ASDF
ABCD
EOS
) do |arguments|

View file

@ -40,28 +40,10 @@ module Puppet::Parser::Functions
unless arg.is_a?(Array) then
candidates = Array.new(1,arg)
end
# iterate over all pathes within the candidates array
# iterate over all paths within the candidates array
candidates.each do |path|
# This logic was borrowed from
# [lib/puppet/file_serving/base.rb](https://github.com/puppetlabs/puppet/blob/master/lib/puppet/file_serving/base.rb)
# Puppet 2.7 and beyond will have Puppet::Util.absolute_path? Fall back to a back-ported implementation otherwise.
if Puppet::Util.respond_to?(:absolute_path?) then
unless Puppet::Util.absolute_path?(path, :posix) or Puppet::Util.absolute_path?(path, :windows)
raise Puppet::ParseError, ("#{path.inspect} is not an absolute path.")
end
else
# This code back-ported from 2.7.x's lib/puppet/util.rb Puppet::Util.absolute_path?
# Determine in a platform-specific way whether a path is absolute. This
# defaults to the local platform if none is specified.
# Escape once for the string literal, and once for the regex.
slash = '[\\\\/]'
name = '[^\\\\/]+'
regexes = {
:windows => %r!^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))!i,
:posix => %r!^/!,
}
rval = (!!(path =~ regexes[:posix])) || (!!(path =~ regexes[:windows]))
rval or raise Puppet::ParseError, ("#{path.inspect} is not an absolute path.")
unless function_is_absolute_path([path])
raise Puppet::ParseError, ("#{path.inspect} is not an absolute path.")
end
end
end

View file

@ -53,7 +53,7 @@ module Puppet::Parser::Functions
rescue Puppet::ExecutionFailure => detail
msg += "\n#{detail}"
raise Puppet::ParseError, msg
rescue Exception => detail
rescue StandardError => detail
msg += "\n#{detail.class.name} #{detail}"
raise Puppet::ParseError, msg
ensure

View file

@ -0,0 +1,31 @@
module Puppet::Parser::Functions
newfunction(:validate_email_address, :doc => <<-ENDHEREDOC
Validate that all values passed are valid email addresses.
Fail compilation if any value fails this check.
The following values will pass:
$my_email = "waldo@gmail.com"
validate_email_address($my_email)
validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email)
The following values will fail, causing compilation to abort:
$some_array = [ 'bad_email@/d/efdf.com' ]
validate_email_address($some_array)
ENDHEREDOC
) do |args|
rescuable_exceptions = [ArgumentError]
if args.empty?
raise Puppet::ParseError, "validate_email_address(): wrong number of arguments (#{args.length}; must be > 0)"
end
args.each do |arg|
raise Puppet::ParseError, "#{arg.inspect} is not a string." unless arg.is_a?(String)
begin
raise Puppet::ParseError, "#{arg.inspect} is not a valid email address" unless function_is_email_address([arg])
rescue *rescuable_exceptions
raise Puppet::ParseError, "#{arg.inspect} is not a valid email address"
end
end
end
end

View file

@ -49,7 +49,7 @@ module Puppet::Parser::Functions
Plus all of the above, but any combination of values passed as strings ('false' or "false").
Plus all of the above, but with incorrect combinations of negative integer values.
Plus all of the above, but with non-integer crap in arrays or maximum / minimum argument.
Plus all of the above, but with non-integer items in arrays or maximum / minimum argument.
ENDHEREDOC

View file

@ -0,0 +1,50 @@
module Puppet::Parser::Functions
newfunction(:validate_ip_address, :doc => <<-ENDHEREDOC
Validate that all values passed are valid IP addresses,
regardless they are IPv4 or IPv6
Fail compilation if any value fails this check.
The following values will pass:
$my_ip = "1.2.3.4"
validate_ip_address($my_ip)
validate_ip_address("8.8.8.8", "172.16.0.1", $my_ip)
$my_ip = "3ffe:505:2"
validate_ip_address(1)
validate_ip_address($my_ip)
validate_ip_address("fe80::baf6:b1ff:fe19:7507", $my_ip)
The following values will fail, causing compilation to abort:
$some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ]
validate_ip_address($some_array)
ENDHEREDOC
) do |args|
require "ipaddr"
rescuable_exceptions = [ ArgumentError ]
if defined?(IPAddr::InvalidAddressError)
rescuable_exceptions << IPAddr::InvalidAddressError
end
unless args.length > 0 then
raise Puppet::ParseError, ("validate_ip_address(): wrong number of arguments (#{args.length}; must be > 0)")
end
args.each do |arg|
unless arg.is_a?(String)
raise Puppet::ParseError, "#{arg.inspect} is not a string."
end
begin
unless IPAddr.new(arg).ipv4? or IPAddr.new(arg).ipv6?
raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address."
end
rescue *rescuable_exceptions
raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address."
end
end
end
end

View file

@ -8,7 +8,7 @@ module Puppet::Parser::Functions
$my_ip = "1.2.3.4"
validate_ipv4_address($my_ip)
validate_bool("8.8.8.8", "172.16.0.1", $my_ip)
validate_ipv4_address("8.8.8.8", "172.16.0.1", $my_ip)
The following values will fail, causing compilation to abort:

View file

@ -23,16 +23,23 @@ module Puppet::Parser::Functions
validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7')
Note: Compilation will also abort, if the first argument is not a String. Always use
quotes to force stringification:
validate_re("${::operatingsystemmajrelease}", '^[57]$')
ENDHEREDOC
if (args.length < 2) or (args.length > 3) then
raise Puppet::ParseError, ("validate_re(): wrong number of arguments (#{args.length}; must be 2 or 3)")
raise Puppet::ParseError, "validate_re(): wrong number of arguments (#{args.length}; must be 2 or 3)"
end
raise Puppet::ParseError, "validate_re(): input needs to be a String, not a #{args[0].class}" unless args[0].is_a? String
msg = args[2] || "validate_re(): #{args[0].inspect} does not match #{args[1].inspect}"
# We're using a flattened array here because we can't call String#any? in
# Ruby 1.9 like we can in Ruby 1.8
raise Puppet::ParseError, (msg) unless [args[1]].flatten.any? do |re_str|
raise Puppet::ParseError, msg unless [args[1]].flatten.any? do |re_str|
args[0] =~ Regexp.compile(re_str)
end

View file

@ -3,7 +3,7 @@ module Puppet::Parser::Functions
newfunction(:validate_slength, :doc => <<-'ENDHEREDOC') do |args|
Validate that the first argument is a string (or an array of strings), and
less/equal to than the length of the second argument. An optional third
parameter can be given a the minimum length. It fails if the first
parameter can be given the minimum length. It fails if the first
argument is not a string or array of strings, and if arg 2 and arg 3 are
not convertable to a number.
@ -43,9 +43,7 @@ module Puppet::Parser::Functions
min_length = 0
end
if min_length > max_length
raise Puppet::ParseError, "validate_slength(): Expected second argument to be larger than third argument"
end
raise Puppet::ParseError, "validate_slength(): Expected second argument to be equal to or larger than third argument" unless max_length >= min_length
validator = lambda do |str|
unless str.length <= max_length and str.length >= min_length

View file

@ -0,0 +1,47 @@
module Puppet::Parser::Functions
newfunction(:validate_x509_rsa_key_pair, :doc => <<-ENDHEREDOC
Validates a PEM-formatted X.509 certificate and RSA private key using
OpenSSL. Verifies that the certficate's signature was created from the
supplied key.
Fail compilation if any value fails this check.
validate_x509_rsa_key_pair($cert, $key)
ENDHEREDOC
) do |args|
require 'openssl'
NUM_ARGS = 2 unless defined? NUM_ARGS
unless args.length == NUM_ARGS then
raise Puppet::ParseError,
("validate_x509_rsa_key_pair(): wrong number of arguments (#{args.length}; must be #{NUM_ARGS})")
end
args.each do |arg|
unless arg.is_a?(String)
raise Puppet::ParseError, "#{arg.inspect} is not a string."
end
end
begin
cert = OpenSSL::X509::Certificate.new(args[0])
rescue OpenSSL::X509::CertificateError => e
raise Puppet::ParseError, "Not a valid x509 certificate: #{e}"
end
begin
key = OpenSSL::PKey::RSA.new(args[1])
rescue OpenSSL::PKey::RSAError => e
raise Puppet::ParseError, "Not a valid RSA key: #{e}"
end
unless cert.verify(key)
raise Puppet::ParseError, "Certificate signature does not match supplied key"
end
end
end

View file

@ -1,24 +1,31 @@
Puppet::Type.type(:file_line).provide(:ruby) do
def exists?
lines.find do |line|
line.chomp == resource[:line].chomp
if resource[:replace].to_s != 'true' and count_matches(match_regex) > 0
true
else
lines.find do |line|
line.chomp == resource[:line].chomp
end
end
end
def create
if resource[:match]
handle_create_with_match
elsif resource[:after]
handle_create_with_after
else
append_line
unless resource[:replace].to_s != 'true' and count_matches(match_regex) > 0
if resource[:match]
handle_create_with_match
elsif resource[:after]
handle_create_with_after
else
append_line
end
end
end
def destroy
local_lines = lines
File.open(resource[:path],'w') do |fh|
fh.write(local_lines.reject{|l| l.chomp == resource[:line] }.join(''))
if resource[:match_for_absence].to_s == 'true' and resource[:match]
handle_destroy_with_match
else
handle_destroy_line
end
end
@ -32,10 +39,13 @@ Puppet::Type.type(:file_line).provide(:ruby) do
@lines ||= File.readlines(resource[:path])
end
def match_regex
resource[:match] ? Regexp.new(resource[:match]) : nil
end
def handle_create_with_match()
regex = resource[:match] ? Regexp.new(resource[:match]) : nil
regex_after = resource[:after] ? Regexp.new(resource[:after]) : nil
match_count = count_matches(regex)
match_count = count_matches(match_regex)
if match_count > 1 && resource[:multiple].to_s != 'true'
raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'"
@ -43,7 +53,7 @@ Puppet::Type.type(:file_line).provide(:ruby) do
File.open(resource[:path], 'w') do |fh|
lines.each do |l|
fh.puts(regex.match(l) ? resource[:line] : l)
fh.puts(match_regex.match(l) ? resource[:line] : l)
if (match_count == 0 and regex_after)
if regex_after.match(l)
fh.puts(resource[:line])
@ -84,6 +94,25 @@ Puppet::Type.type(:file_line).provide(:ruby) do
lines.select{|l| l.match(regex)}.size
end
def handle_destroy_with_match
match_count = count_matches(match_regex)
if match_count > 1 && resource[:multiple].to_s != 'true'
raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'"
end
local_lines = lines
File.open(resource[:path],'w') do |fh|
fh.write(local_lines.reject{|l| match_regex.match(l) }.join(''))
end
end
def handle_destroy_line
local_lines = lines
File.open(resource[:path],'w') do |fh|
fh.write(local_lines.reject{|l| l.chomp == resource[:line] }.join(''))
end
end
##
# append the line to the file.
#

View file

@ -4,7 +4,7 @@ Puppet::Type.newtype(:file_line) do
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 will append the line to
the end of the file to ensure the desired state. Multiple resources may
the end of the file to ensure the desired state. Multiple resources may
be declared to manage multiple lines in the same file.
Example:
@ -31,12 +31,25 @@ Puppet::Type.newtype(:file_line) do
match => '^export\ HTTP_PROXY\=',
}
In this code example match will look for a line beginning with export
In this code example match will look for a line beginning with export
followed by HTTP_PROXY and replace it with the value in line.
Match Example With `ensure => absent`:
file_line { 'bashrc_proxy':
ensure => absent,
path => '/etc/bashrc',
line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128',
match => '^export\ HTTP_PROXY\=',
match_for_absence => true,
}
In this code example match will look for a line beginning with export
followed by HTTP_PROXY and delete it. If multiple lines match, an
error will be raised unless the `multiple => true` parameter is set.
**Autorequires:** If Puppet is managing the file that will contain the line
being managed, the file_line resource will autorequire that file.
EOT
ensurable do
@ -49,10 +62,18 @@ Puppet::Type.newtype(:file_line) do
end
newparam(:match) do
desc 'An optional ruby regular expression to run against existing lines in the file.' +
desc 'An optional ruby regular expression to run against existing lines in the file.' +
' If a match is found, we replace that line rather than adding a new line.' +
' A regex comparisson is performed against the line value and if it does not' +
' match an exception will be raised. '
' A regex comparison is performed against the line value and if it does not' +
' match an exception will be raised.'
end
newparam(:match_for_absence) do
desc '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.'
newvalues(true, false)
defaultto false
end
newparam(:multiple) do
@ -72,20 +93,31 @@ Puppet::Type.newtype(:file_line) do
newparam(:path) do
desc 'The file Puppet will ensure contains the line specified by the line parameter.'
validate do |value|
unless (Puppet.features.posix? and value =~ /^\//) or (Puppet.features.microsoft_windows? and (value =~ /^.:\// or value =~ /^\/\/[^\/]+\/[^\/]+/))
raise(Puppet::Error, "File paths must be fully qualified, not '#{value}'")
unless Puppet::Util.absolute_path?(value)
raise Puppet::Error, "File paths must be fully qualified, not '#{value}'"
end
end
end
newparam(:replace) do
desc 'If true, replace line that matches. If false, do not write line if a match is found'
newvalues(true, false)
defaultto true
end
# Autorequire the file resource if it's being managed
autorequire(:file) do
self[:path]
end
validate do
unless self[:line] and self[:path]
raise(Puppet::Error, "Both line and path are required attributes")
unless self[:line]
unless (self[:ensure].to_s == 'absent') and (self[:match_for_absence].to_s == 'true') and self[:match]
raise(Puppet::Error, "line is a required attribute")
end
end
unless self[:path]
raise(Puppet::Error, "path is a required attribute")
end
end
end

View file

@ -14,5 +14,5 @@
# Requires: nothing
#
class stdlib {
include stdlib::stages
include ::stdlib::stages
}

View file

@ -26,7 +26,7 @@
# Sample Usage:
#
# node default {
# include stdlib
# include ::stdlib
# class { java: stage => 'runtime' }
# }
#

View file

@ -1,6 +1,6 @@
{
"name": "puppetlabs-stdlib",
"version": "4.6.0",
"version": "4.12.0",
"author": "puppetlabs",
"summary": "Standard library of resources for Puppet modules.",
"license": "Apache-2.0",
@ -56,7 +56,8 @@
"operatingsystem": "Debian",
"operatingsystemrelease": [
"6",
"7"
"7",
"8"
]
},
{
@ -71,7 +72,8 @@
"operatingsystem": "Solaris",
"operatingsystemrelease": [
"10",
"11"
"11",
"12"
]
},
{
@ -99,11 +101,11 @@
"requirements": [
{
"name": "pe",
"version_requirement": "3.x"
"version_requirement": ">= 3.0.0 < 2015.4.0"
},
{
"name": "puppet",
"version_requirement": ">=2.7.20 <4.0.0"
"version_requirement": ">=2.7.20 <5.0.0"
}
],
"description": "Standard Library for Puppet Modules",

40
spec/acceptance/clamp_spec.rb Executable file
View file

@ -0,0 +1,40 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
describe 'clamp function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
describe 'success' do
it 'clamps list of values' do
pp = <<-EOS
$x = 17
$y = 225
$z = 155
$o = clamp($x, $y, $z)
if $o == $z {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
it 'clamps array of values' do
pp = <<-EOS
$a = [7, 19, 66]
$b = 19
$o = clamp($a)
if $o == $b {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
end
describe 'failure' do
it 'handles improper argument counts'
it 'handles no arguments'
end
end

View file

@ -34,6 +34,20 @@ describe 'concat function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('oper
}
EOS
apply_manifest(pp, :catch_failures => true)
end
it 'should concat hash arguments' do
pp = <<-EOS
$output = concat([{"a" => "b"}], {"c" => "d", "e" => "f"})
validate_array($output)
if size($output) != 2 {
fail("${output} should have 2 elements.")
}
if $output[1] != {"c" => "d", "e" => "f"} {
fail("${output} does not have the expected hash for the second element.")
}
EOS
apply_manifest(pp, :catch_failures => true)
end
end

View file

@ -27,6 +27,20 @@ describe 'empty function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('opera
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
it 'handles numerical values' do
pp = <<-EOS
$a = 7
$b = false
$o = empty($a)
if $o == $b {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end

View file

@ -1,22 +0,0 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
describe 'ensure_packages function', :unless => fact('osfamily') =~ /windows/i do
describe 'success' do
it 'ensure_packages a package' do
apply_manifest('package { "rake": ensure => absent, provider => "gem", }')
pp = <<-EOS
$a = "rake"
ensure_packages($a,{'provider' => 'gem'})
EOS
apply_manifest(pp, :expect_changes => true)
end
it 'ensures a package already declared'
it 'takes defaults arguments'
end
describe 'failure' do
it 'handles no arguments'
it 'handles non strings'
end
end

View file

@ -1,18 +1,26 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
describe 'ensure_resource function', :unless => fact('osfamily') =~ /windows/i do
describe 'ensure_resource function' do
describe 'success' do
it 'ensure_resource a package' do
apply_manifest('package { "rake": ensure => absent, provider => "gem", }')
it 'ensures a resource already declared' do
apply_manifest('')
pp = <<-EOS
$a = "rake"
ensure_resource('package', $a, {'provider' => 'gem'})
notify { "test": loglevel => 'err' }
ensure_resource('notify', 'test', { 'loglevel' => 'err' })
EOS
apply_manifest(pp, :expect_changes => true)
end
it 'ensures a undeclared resource' do
apply_manifest('')
pp = <<-EOS
ensure_resource('notify', 'test', { 'loglevel' => 'err' })
EOS
apply_manifest(pp, :expect_changes => true)
end
it 'ensures a resource already declared'
it 'takes defaults arguments'
end
describe 'failure' do

View file

@ -3,80 +3,59 @@ require 'spec_helper_acceptance'
describe 'fqdn_rand_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
describe 'success' do
let(:facts_d) do
if fact('is_pe', '--puppet') == "true"
if fact('osfamily') =~ /windows/i
if fact('kernelmajversion').to_f < 6.0
'c:/documents and settings/all users/application data/puppetlabs/facter/facts.d'
else
'c:/programdata/puppetlabs/facter/facts.d'
end
else
'/etc/puppetlabs/facter/facts.d'
include_context "with faked facts"
context "when the FQDN is 'fakehost.localdomain'" do
before :each do
fake_fact("fqdn", "fakehost.localdomain")
end
it 'generates random alphanumeric strings' do
pp = <<-eos
$l = 10
$o = fqdn_rand_string($l)
notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
eos
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "(7oDp0KOr1b|9Acvnhkt4J)"/)
end
else
'/etc/facter/facts.d'
end
end
after :each do
shell("if [ -f '#{facts_d}/fqdn.txt' ] ; then rm '#{facts_d}/fqdn.txt' ; fi")
end
before :each do
#no need to create on windows, pe creates by default
if fact('osfamily') !~ /windows/i
shell("mkdir -p '#{facts_d}'")
end
end
it 'generates random alphanumeric strings' do
shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
pp = <<-eos
$l = 10
$o = fqdn_rand_string($l)
notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
eos
it 'generates random alphanumeric strings with custom charsets' do
pp = <<-eos
$l = 10
$c = '0123456789'
$o = fqdn_rand_string($l, $c)
notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
eos
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "7oDp0KOr1b"/)
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "(7203048515|2383756694)"/)
end
end
end
it 'generates random alphanumeric strings with custom charsets' do
shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
pp = <<-eos
$l = 10
$c = '0123456789'
$o = fqdn_rand_string($l, $c)
notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
eos
it 'generates random alphanumeric strings with custom seeds' do
pp = <<-eos
$l = 10
$s = 'seed'
$o = fqdn_rand_string($l, undef, $s)
notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
eos
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "7203048515"/)
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "(3HS4mbuI3E|1jJtAMs94d)"/)
end
end
end
it 'generates random alphanumeric strings with custom seeds' do
shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
pp = <<-eos
$l = 10
$s = 'seed'
$o = fqdn_rand_string($l, undef, $s)
notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
eos
it 'generates random alphanumeric strings with custom charsets and seeds' do
pp = <<-eos
$l = 10
$c = '0123456789'
$s = 'seed'
$o = fqdn_rand_string($l, $c, $s)
notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
eos
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "3HS4mbuI3E"/)
end
end
it 'generates random alphanumeric strings with custom charsets and seeds' do
shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
pp = <<-eos
$l = 10
$c = '0123456789'
$s = 'seed'
$o = fqdn_rand_string($l, $c, $s)
notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
eos
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "3104058232"/)
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "(3104058232|7100592312)"/)
end
end
end
end

View file

@ -3,78 +3,57 @@ require 'spec_helper_acceptance'
describe 'fqdn_rotate function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
describe 'success' do
let(:facts_d) do
if fact('is_pe', '--puppet') == "true"
if fact('osfamily') =~ /windows/i
if fact('kernelmajversion').to_f < 6.0
'C:/Documents and Settings/All Users/Application Data/PuppetLabs/facter/facts.d'
else
'C:/ProgramData/PuppetLabs/facter/facts.d'
end
else
'/etc/puppetlabs/facter/facts.d'
include_context "with faked facts"
context "when the FQDN is 'fakehost.localdomain'" do
before :each do
fake_fact("fqdn", "fakehost.localdomain")
end
it 'rotates arrays' do
pp = <<-EOS
$a = ['a','b','c','d']
$o = fqdn_rotate($a)
notice(inline_template('fqdn_rotate is <%= @o.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is \["d", "a", "b", "c"\]/)
end
else
'/etc/facter/facts.d'
end
end
after :each do
shell("if [ -f '#{facts_d}/fqdn.txt' ] ; then rm '#{facts_d}/fqdn.txt' ; fi")
end
before :each do
#No need to create on windows, PE creates by default
if fact('osfamily') !~ /windows/i
shell("mkdir -p '#{facts_d}'")
end
end
it 'rotates arrays' do
shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
pp = <<-EOS
$a = ['a','b','c','d']
$o = fqdn_rotate($a)
notice(inline_template('fqdn_rotate is <%= @o.inspect %>'))
EOS
it 'rotates arrays with custom seeds' do
pp = <<-EOS
$a = ['a','b','c','d']
$s = 'seed'
$o = fqdn_rotate($a, $s)
notice(inline_template('fqdn_rotate is <%= @o.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is \["d", "a", "b", "c"\]/)
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is \["c", "d", "a", "b"\]/)
end
end
end
it 'rotates arrays with custom seeds' do
shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
pp = <<-EOS
$a = ['a','b','c','d']
$s = 'seed'
$o = fqdn_rotate($a, $s)
notice(inline_template('fqdn_rotate is <%= @o.inspect %>'))
EOS
it 'rotates strings' do
pp = <<-EOS
$a = 'abcd'
$o = fqdn_rotate($a)
notice(inline_template('fqdn_rotate is <%= @o.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is \["c", "d", "a", "b"\]/)
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is "dabc"/)
end
end
end
it 'rotates strings' do
shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
pp = <<-EOS
$a = 'abcd'
$o = fqdn_rotate($a)
notice(inline_template('fqdn_rotate is <%= @o.inspect %>'))
EOS
it 'rotates strings with custom seeds' do
pp = <<-EOS
$a = 'abcd'
$s = 'seed'
$o = fqdn_rotate($a, $s)
notice(inline_template('fqdn_rotate is <%= @o.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is "dabc"/)
end
end
it 'rotates strings with custom seeds' do
shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
pp = <<-EOS
$a = 'abcd'
$s = 'seed'
$o = fqdn_rotate($a, $s)
notice(inline_template('fqdn_rotate is <%= @o.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is "cdab"/)
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is "cdab"/)
end
end
end
end

View file

@ -0,0 +1,30 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
if get_puppet_version =~ /^4/
describe 'is_a function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
it 'should match a string' do
pp = <<-EOS
if 'hello world'.is_a(String) {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
it 'should not match a integer as string' do
pp = <<-EOS
if 5.is_a(String) {
notify { 'output wrong': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).not_to match(/Notice: output wrong/)
end
end
end
end

View file

@ -0,0 +1,52 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
describe 'is_ipv4_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
describe 'success' do
it 'is_ipv4_addresss' do
pp = <<-EOS
$a = '1.2.3.4'
$b = true
$o = is_ipv4_address($a)
if $o == $b {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
it 'is_ipv4_addresss strings' do
pp = <<-EOS
$a = "aoeu"
$b = false
$o = is_ipv4_address($a)
if $o == $b {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
it 'is_ipv4_addresss ipv4 out of range' do
pp = <<-EOS
$a = '1.2.3.400'
$b = false
$o = is_ipv4_address($a)
if $o == $b {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
end
describe 'failure' do
it 'handles improper argument counts'
end
end

View file

@ -0,0 +1,66 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
describe 'is_ipv6_address function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
describe 'success' do
it 'is_ipv6_addresss' do
pp = <<-EOS
$a = "fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74"
$b = true
$o = is_ipv6_address($a)
if $o == $b {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
it 'is_ipv6_addresss ipv6 compressed' do
pp = <<-EOS
$a = "fe00::1"
$b = true
$o = is_ipv6_address($a)
if $o == $b {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
it 'is_ipv6_addresss strings' do
pp = <<-EOS
$a = "aoeu"
$b = false
$o = is_ipv6_address($a)
if $o == $b {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
it 'is_ipv6_addresss ip out of range' do
pp = <<-EOS
$a = 'fe80:0000:cd12:d123:e2f8:47ff:fe09:gggg'
$b = false
$o = is_ipv6_address($a)
if $o == $b {
notify { 'output correct': }
}
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/Notice: output correct/)
end
end
end
describe 'failure' do
it 'handles improper argument counts'
end
end

View file

@ -0,0 +1,52 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
tmpdir = default.tmpdir('stdlib')
describe 'loadjson function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
describe 'success' do
it 'loadjsons array of values' do
shell("echo '{\"aaa\":1,\"bbb\":2,\"ccc\":3,\"ddd\":4}' > #{tmpdir}/testjson.json")
pp = <<-EOS
$o = loadjson('#{tmpdir}/testjson.json')
notice(inline_template('loadjson[aaa] is <%= @o["aaa"].inspect %>'))
notice(inline_template('loadjson[bbb] is <%= @o["bbb"].inspect %>'))
notice(inline_template('loadjson[ccc] is <%= @o["ccc"].inspect %>'))
notice(inline_template('loadjson[ddd] is <%= @o["ddd"].inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/loadjson\[aaa\] is 1/)
expect(r.stdout).to match(/loadjson\[bbb\] is 2/)
expect(r.stdout).to match(/loadjson\[ccc\] is 3/)
expect(r.stdout).to match(/loadjson\[ddd\] is 4/)
end
end
it 'returns the default value if there is no file to load' do
pp = <<-EOS
$o = loadjson('#{tmpdir}/no-file.json', {'default' => 'value'})
notice(inline_template('loadjson[default] is <%= @o["default"].inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/loadjson\[default\] is "value"/)
end
end
it 'returns the default value if the file was parsed with an error' do
shell("echo '!' > #{tmpdir}/testjson.json")
pp = <<-EOS
$o = loadjson('#{tmpdir}/testjson.json', {'default' => 'value'})
notice(inline_template('loadjson[default] is <%= @o["default"].inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/loadjson\[default\] is "value"/)
end
end
end
describe 'failure' do
it 'fails with no arguments'
end
end

View file

@ -26,6 +26,29 @@ describe 'loadyaml function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('op
expect(r.stdout).to match(/loadyaml\[ddd\] is 4/)
end
end
it 'returns the default value if there is no file to load' do
pp = <<-EOS
$o = loadyaml('#{tmpdir}/no-file.yaml', {'default' => 'value'})
notice(inline_template('loadyaml[default] is <%= @o["default"].inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/loadyaml\[default\] is "value"/)
end
end
it 'returns the default value if the file was parsed with an error' do
shell("echo '!' > #{tmpdir}/testyaml.yaml")
pp = <<-EOS
$o = loadyaml('#{tmpdir}/testyaml.yaml', {'default' => 'value'})
notice(inline_template('loadyaml[default] is <%= @o["default"].inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/loadyaml\[default\] is "value"/)
end
end
end
describe 'failure' do
it 'fails with no arguments'

View file

@ -1,10 +0,0 @@
HOSTS:
centos-59-x64:
roles:
- master
platform: el-5-x86_64
box : centos-59-x64-vbox4210-nocm
box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-59-x64-vbox4210-nocm.box
hypervisor : vagrant
CONFIG:
type: git

View file

@ -1,15 +0,0 @@
HOSTS:
'centos-6-vcloud':
roles:
- master
platform: el-6-x86_64
hypervisor: vcloud
template: centos-6-x86_64
CONFIG:
type: foss
ssh:
keys: "~/.ssh/id_rsa-acceptance"
datastore: instance0
folder: Delivery/Quality Assurance/Enterprise/Dynamic
resourcepool: delivery/Quality Assurance/Enterprise/Dynamic
pooling_api: http://vcloud.delivery.puppetlabs.net/

View file

@ -1,12 +0,0 @@
HOSTS:
centos-64-x64:
roles:
- master
- database
- dashboard
platform: el-6-x86_64
box : centos-64-x64-vbox4210-nocm
box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box
hypervisor : vagrant
CONFIG:
type: pe

View file

@ -1,10 +0,0 @@
HOSTS:
centos-64-x64:
roles:
- master
platform: el-6-x86_64
box : centos-64-x64-vbox4210-nocm
box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-64-x64-vbox4210-nocm.box
hypervisor : vagrant
CONFIG:
type: foss

View file

@ -1,10 +0,0 @@
HOSTS:
centos-65-x64:
roles:
- master
platform: el-6-x86_64
box : centos-65-x64-vbox436-nocm
box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-65-x64-virtualbox-nocm.box
hypervisor : vagrant
CONFIG:
type: foss

View file

@ -0,0 +1,10 @@
HOSTS:
centos-7-x64:
roles:
- agent
- default
platform: redhat-7-x86_64
hypervisor: vagrant
box: puppetlabs/centos-7.2-64-nocm
CONFIG:
type: foss

View file

@ -0,0 +1,10 @@
HOSTS:
debian-8-x64:
roles:
- agent
- default
platform: debian-8-amd64
hypervisor: vagrant
box: puppetlabs/debian-8.2-64-nocm
CONFIG:
type: foss

View file

@ -1,10 +1,10 @@
HOSTS:
centos-65-x64:
ubuntu-1404-x64:
roles:
- master
platform: el-6-x86_64
box : centos-65-x64-vbox436-nocm
box_url : http://puppet-vagrant-boxes.puppetlabs.com/centos-65-x64-virtualbox-nocm.box
hypervisor : vagrant
- agent
- default
platform: ubuntu-14.04-amd64
hypervisor: vagrant
box: puppetlabs/ubuntu-14.04-64-nocm
CONFIG:
type: foss

View file

@ -0,0 +1,12 @@
HOSTS:
centos-7-x64:
platform: el-7-x86_64
hypervisor: docker
image: centos:7
docker_preserve_image: true
docker_cmd: '["/usr/sbin/init"]'
# install various tools required to get the image up to usable levels
docker_image_commands:
- 'yum install -y crontabs tar wget openssl sysvinit-tools iproute which initscripts'
CONFIG:
trace_limit: 200

View file

@ -0,0 +1,11 @@
HOSTS:
debian-8-x64:
platform: debian-8-amd64
hypervisor: docker
image: debian:8
docker_preserve_image: true
docker_cmd: '["/sbin/init"]'
docker_image_commands:
- 'apt-get update && apt-get install -y net-tools wget locales strace lsof && echo "en_US.UTF-8 UTF-8" > /etc/locale.gen && locale-gen'
CONFIG:
trace_limit: 200

View file

@ -0,0 +1,12 @@
HOSTS:
ubuntu-1404-x64:
platform: ubuntu-14.04-amd64
hypervisor: docker
image: ubuntu:14.04
docker_preserve_image: true
docker_cmd: '["/sbin/init"]'
docker_image_commands:
# ensure that upstart is booting correctly in the container
- 'rm /usr/sbin/policy-rc.d && rm /sbin/initctl && dpkg-divert --rename --remove /sbin/initctl && apt-get update && apt-get install -y net-tools wget && locale-gen en_US.UTF-8'
CONFIG:
trace_limit: 200

View file

@ -1,10 +0,0 @@
HOSTS:
fedora-18-x64:
roles:
- master
platform: fedora-18-x86_64
box : fedora-18-x64-vbox4210-nocm
box_url : http://puppet-vagrant-boxes.puppetlabs.com/fedora-18-x64-vbox4210-nocm.box
hypervisor : vagrant
CONFIG:
type: foss

Some files were not shown because too many files have changed in this diff Show more