Compare commits

..

No commits in common. "master" and "ortiche" have entirely different histories.

171 changed files with 905 additions and 4417 deletions

5
.gitattributes vendored
View file

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

4
.rspec
View file

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

View file

@ -1,7 +1,9 @@
---
.gitignore:
paths:
- '!spec/fixtures/'
- 'spec/fixtures/manifests/site.pp'
- 'spec/fixtures/modules/*'
.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

View file

@ -1,35 +1,21 @@
#This file is generated by ModuleSync, do not edit.
---
sudo: false
language: ruby
cache: bundler
script: "bundle exec rake validate lint spec"
bundler_args: --without system_tests
script: "bundle exec rake validate && bundle exec rake lint && bundle exec rake spec SPEC_OPTS='--color --format documentation'"
matrix:
fast_finish: true
include:
- 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
- rvm: 1.8.7
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,143 +1,3 @@
## 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
@ -433,7 +293,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)
@ -530,7 +390,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
% bundle exec rake spec
% 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
% bundle exec rake spec_clean
% bundle exec rspec spec/acceptance
% rake spec_clean
% rspec spec/acceptance
```
This will now download a pre-fabricated image configured in the [default node-set](./spec/acceptance/nodesets/default.yml),
@ -208,9 +208,11 @@ review.
Additional Resources
====================
* [Getting additional help](http://puppet.com/community/get-help)
* [Getting additional help](http://puppetlabs.com/community/get-help)
* [Writing tests](https://docs.puppet.com/guides/module_guides/bgtm.html#step-three-module-testing)
* [Writing tests](http://projects.puppetlabs.com/projects/puppet/wiki/Development_Writing_Tests)
* [Patchwork](https://patchwork.puppetlabs.com)
* [General GitHub documentation](http://help.github.com/)

68
Gemfile
View file

@ -1,40 +1,54 @@
#This file is generated by ModuleSync, do not edit.
source ENV['GEM_SOURCE'] || 'https://rubygems.org'
source ENV['GEM_SOURCE'] || "https://rubygems.org"
def location_for(place, version = nil)
def location_for(place, fake_version = nil)
if place =~ /^(git[:@][^#]*)#(.*)/
[version, { :git => $1, :branch => $2, :require => false}].compact
[fake_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, version, { :require => false}].compact
[place, { :require => false }]
end
end
group :development, :unit_tests do
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
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
end
beaker_version = ENV['BEAKER_VERSION']
beaker_rspec_version = ENV['BEAKER_RSPEC_VERSION']
group :system_tests do
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'])
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
end
gem 'facter', *location_for(ENV['FACTER_GEM_VERSION'])
gem 'puppet', *location_for(ENV['PUPPET_GEM_VERSION'])
if File.exists? "#{__FILE__}.local"
eval(File.read("#{__FILE__}.local"), binding)
facterversion = ENV['GEM_FACTER_VERSION'] || ENV['FACTER_GEM_VERSION']
if facterversion
gem 'facter', *location_for(facterversion)
else
gem 'facter', :require => false
end
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

209
LICENSE
View file

@ -1,202 +1,19 @@
Copyright (C) 2011 Puppet Labs Inc
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
and some parts:
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Copyright (C) 2011 Krzysztof Wilczynski
1. Definitions.
Puppet Labs can be contacted at: info@puppetlabs.com
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
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
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
http://www.apache.org/licenses/LICENSE-2.0
"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.
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
View file

@ -1,23 +0,0 @@
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,63 +76,30 @@ 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.
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.
~~~
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',
}
~~~
##### Parameters
All parameters are optional, unless otherwise noted.
* `after`: Specifies the line after which Puppet adds any new lines. (Existing lines are added in place.) Valid options: String. Default: Undefined.
* `after`: Specifies the line after which Puppet will add 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. 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.
* `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.
* `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
@ -146,34 +113,7 @@ 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`, 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.
Converts a string to and from base64 encoding. Requires an action ('encode', 'decode') and either a plain or base64-encoded string. *Type*: rvalue.
#### `basename`
@ -191,22 +131,9 @@ 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 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.
Capitalizes the first letter of a string or array of strings. Requires either a single string or an array as an input. *Type*: rvalue.
#### `ceiling`
@ -220,14 +147,6 @@ 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:
@ -235,12 +154,6 @@ 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.
@ -263,24 +176,12 @@ 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}, `delete(['ab', 'b'], 'b')` returns ['ab'].
*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}. *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.
@ -293,124 +194,25 @@ 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 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.
Returns 'true' if the variable is empty. *Type*: rvalue.
#### `ensure_packages`
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'})
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.
#### `ensure_resource`
Takes a resource type, title, and a hash of attributes that describe the resource(s).
Takes a resource type, title, and a list of attributes that describe a resource.
~~~
user { 'dan':
@ -430,37 +232,7 @@ An array of resources can also be passed in, and each will be created with the t
*Type*: statement.
#### `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`
#### `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.
@ -490,13 +262,10 @@ 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')
@ -614,33 +383,6 @@ 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.
@ -673,14 +415,6 @@ 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.
@ -707,62 +441,12 @@ 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`
@ -775,7 +459,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.
@ -805,11 +489,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. The optional second argument is returned if the data was not correct.
Converts a string of JSON into the correct Puppet structure. *Type*: rvalue.
#### `parseyaml`
Converts a string of YAML into the correct Puppet structure. *Type*: rvalue. The optional second argument is returned if the data was not correct.
Converts a string of YAML into the correct Puppet structure. *Type*: rvalue.
#### `pick`
@ -821,16 +505,12 @@ 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.
@ -868,8 +548,6 @@ 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`
@ -894,51 +572,13 @@ 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, an array or a hash. *Type*: rvalue.
Returns the number of elements in a string or an array. *Type*: rvalue.
#### `sort`
@ -950,7 +590,7 @@ Returns a new string where runs of the same character that occur in this set are
#### `str2bool`
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.
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.
#### `str2saltedsha512`
@ -1015,12 +655,7 @@ Removes leading and trailing whitespace from a string or from every string insid
#### `suffix`
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.
Applies a suffix to all elements in an array. For example, `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp']. *Type*: rvalue.
#### `swapcase`
@ -1034,50 +669,6 @@ 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.
@ -1088,25 +679,12 @@ Returns the literal type when passed a value. Requires the new parser. Useful fo
#### `union`
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.
Returns a union of two arrays, without duplicates. For example, `union(["a","b","c"],["b","c","d"])` returns ["a","b","c","d"].
#### `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.
@ -1310,42 +888,10 @@ 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 items in arrays or maximum / minimum argument.
* Plus all of the above, but with non-integer crap 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.
@ -1388,24 +934,17 @@ 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 the second argument is not convertable to a number. Optionally, a minimum string length can be given as the third argument.
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.
The following values pass:
~~~
validate_slength("discombobulate",17)
validate_slength(["discombobulate","moo"],17)
validate_slength(["discombobulate","moo"],17,3)
~~~
The following values fail:
@ -1413,7 +952,6 @@ 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.
@ -1448,25 +986,9 @@ 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.
@ -1486,7 +1008,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.
@ -1497,18 +1019,21 @@ 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
##Contributors
The list of contributors can be found at: https://github.com/puppetlabs/puppetlabs-stdlib/graphs/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,42 +1,7 @@
require 'puppet_blacksmith/rake_tasks'
require 'puppet-lint/tasks/puppet-lint'
require 'rubygems'
# keep for compatibility for now
require 'puppetlabs_spec_helper/rake_tasks'
require 'puppet-lint/tasks/puppet-lint'
PuppetLint.configuration.send('disable_80chars')
PuppetLint.configuration.ignore_paths = ["spec/**/*.pp", "pkg/**/*.pp"]
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 +0,0 @@
include ::stdlib

View file

@ -48,7 +48,7 @@ class Facter::Util::DotD
end
end
end
rescue StandardError => e
rescue Exception => 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 StandardError => e
rescue Exception => 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 StandardError => e
rescue Exception => 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 StandardError => e
rescue Exception => e
Facter.warn("Failed to handle #{file} as script facts: #{e.class}: #{e}")
Facter.debug(e.backtrace.join("\n\t"))
end

View file

@ -1,21 +0,0 @@
# 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,13 +10,8 @@
#
Facter.add("pe_version") do
setcode do
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
pe_ver = Facter.value("puppetversion").match(/Puppet Enterprise (\d+\.\d+\.\d+)/)
pe_ver[1] if pe_ver
end
end

View file

@ -30,16 +30,3 @@ 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

@ -1,17 +0,0 @@
# 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

@ -1,32 +0,0 @@
# 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

@ -1,55 +0,0 @@
#
# 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,19 +6,14 @@ module Puppet::Parser::Functions
Usage:
$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)
$encodestring = base64('encode','thestring')
$decodestring = base64('decode','dGhlc3RyaW5n')
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']
@ -30,37 +25,11 @@ 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'
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
result = Base64.encode64(args[1])
when 'decode'
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
result = Base64.decode64(args[1])
end
return result

View file

@ -4,29 +4,15 @@
module Puppet::Parser::Functions
newfunction(:bool2str, :type => :rvalue, :doc => <<-EOS
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'
Converts a boolean to a string.
Requires a single boolean as an input.
EOS
) do |arguments|
unless arguments.size == 1 or arguments.size == 3
raise(Puppet::ParseError, "bool2str(): Wrong number of arguments " +
"given (#{arguments.size} for 3)")
end
raise(Puppet::ParseError, "bool2str(): Wrong number of arguments " +
"given (#{arguments.size} for 1)") if arguments.size < 1
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
@ -34,11 +20,7 @@ module Puppet::Parser::Functions
raise(Puppet::ParseError, 'bool2str(): Requires a boolean to work with')
end
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
return value.to_s
end
end

View file

@ -1,30 +0,0 @@
#
# 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 + (x.is_a?(Array) ? x : [x])
result = result + Array(x)
end
return result

View file

@ -1,35 +0,0 @@
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,10 +26,7 @@ ENDOFDOC
ret = false
if resource = findresource(reference.to_s)
matches = params.collect do |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)
resource[key] == value
end
ret = params.empty? || !matches.include?(false)
end

View file

@ -2,6 +2,8 @@
# 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
@ -23,8 +25,10 @@ string, or key from a hash.
EOS
) do |arguments|
raise(Puppet::ParseError, "delete(): Wrong number of arguments "+
"given #{arguments.size} for 2") unless arguments.size == 2
if (arguments.size != 2) then
raise(Puppet::ParseError, "delete(): Wrong number of arguments "+
"given #{arguments.size} for 2.")
end
collection = arguments[0].dup
Array(arguments[1]).each do |item|

View file

@ -1,45 +0,0 @@
#
# 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

@ -1,16 +0,0 @@
#
# 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

@ -1,56 +0,0 @@
#
# 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

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

View file

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

View file

@ -1,54 +0,0 @@
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,11 +38,8 @@ 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
begin
catch :undefined_variable do
factval = lookupvar(kind)
end
rescue Puppet::ParseError # Eat the exception if strict_variables = true is set
catch :undefined_variable do
factval = lookupvar(kind)
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 StandardError
rescue Exception
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 of the intersection of two.
This function returns an array an intersection of two.
*Examples:*
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)
intersection(["a","b","c"],["b","c","d"])
Would return: ["b","c"]
EOS
) do |arguments|

View file

@ -1,50 +0,0 @@
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

@ -1,21 +0,0 @@
#
# 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

@ -1,28 +0,0 @@
#
# 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

@ -1,28 +0,0 @@
#
# 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

@ -1,24 +0,0 @@
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

@ -1,34 +0,0 @@
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,32 +1,23 @@
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.
For example:
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.
$myhash = loadyaml('/etc/puppet/data/myhash.yaml')
$myhash = loadyaml('no-file.yaml', {'default' => 'value'})
ENDHEREDOC
For example:
raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1
require 'yaml'
$myhash = loadyaml('/etc/puppet/data/myhash.yaml')
ENDHEREDOC
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
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])
else
warning("Can't load '#{args[0]}' File does not exist!")
args[1]
warning("Can't load " + args[0] + ". File does not exist!")
nil
end
end

View file

@ -4,25 +4,20 @@
module Puppet::Parser::Functions
newfunction(:parsejson, :type => :rvalue, :doc => <<-EOS
This function accepts JSON as a string and converts it into the correct
Puppet structure.
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
This function accepts JSON as a string and converts into the correct Puppet
structure.
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
if (arguments.size != 1) then
raise(Puppet::ParseError, "parsejson(): Wrong number of arguments "+
"given #{arguments.size} for 1")
end
json = arguments[0]
# PSON is natively available in puppet
PSON.load(json)
end
end

View file

@ -6,26 +6,17 @@ 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.
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
EOS
) do |arguments|
raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1
if (arguments.size != 1) then
raise(Puppet::ParseError, "parseyaml(): Wrong number of arguments "+
"given #{arguments.size} for 1")
end
require 'yaml'
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
YAML::load(arguments[0])
end
end

View file

@ -1,22 +0,0 @@
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

@ -1,30 +0,0 @@
#
# 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

@ -1,31 +0,0 @@
#
# 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

@ -1,26 +0,0 @@
#
# 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,9 +2,11 @@
# 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, an array or a hash
Returns the number of elements in a string or array.
EOS
) do |arguments|
@ -27,13 +29,13 @@ Returns the number of elements in a string, an array or a hash
Float(item)
raise(Puppet::ParseError, 'size(): Requires either ' +
'string, array or hash to work with')
'string or array to work with')
rescue ArgumentError
result = item.size
end
elsif item.is_a?(Array) || item.is_a?(Hash)
elsif item.is_a?(Array)
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,y, 1, T,t, TRUE,true to 'true' and strings that contain things
like: 0, F,f, N,n, false, FALSE, no to 'false'.
contain things like: y, 1, t, true to 'true' and strings that contain things
like: 0, f, n, false, no to 'false'.
EOS
) do |arguments|
@ -32,8 +32,8 @@ like: 0, F,f, N,n, false, FALSE, no to 'false'.
# We yield false in this case.
#
when /^$/, '' then false # Empty string will be false ...
when /^(1|t|y|true|yes)$/i then true
when /^(0|f|n|false|no)$/i then false
when /^(1|t|y|true|yes)$/ then true
when /^(0|f|n|false|no)$/ 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,8 +4,7 @@
module Puppet::Parser::Functions
newfunction(:suffix, :type => :rvalue, :doc => <<-EOS
This function applies a suffix to all elements in an array, or to the keys
in a hash.
This function applies a suffix to all elements in an array.
*Examples:*
@ -19,10 +18,10 @@ Will return: ['ap','bp','cp']
raise(Puppet::ParseError, "suffix(): Wrong number of arguments " +
"given (#{arguments.size} for 1)") if arguments.size < 1
enumerable = arguments[0]
array = arguments[0]
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}"
unless array.is_a?(Array)
raise Puppet::ParseError, "suffix(): expected first argument to be an Array, got #{array.inspect}"
end
suffix = arguments[1] if arguments[1]
@ -33,17 +32,10 @@ Will return: ['ap','bp','cp']
end
end
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]
# Turn everything into string same as join would do ...
result = array.collect do |i|
i = i.to_s
suffix ? i + suffix : i
end
return result

View file

@ -1,53 +0,0 @@
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 or more arrays.
This function returns a union of two arrays.
*Examples:*
@ -14,15 +14,20 @@ Would return: ["a","b","c","d"]
EOS
) do |arguments|
# Check that 2 or more arguments have been given ...
# Two arguments are required
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
arguments.each do |argument|
raise(Puppet::ParseError, 'union(): Every parameter must be an array') unless argument.is_a?(Array)
first = arguments[0]
second = arguments[1]
unless first.is_a?(Array) && second.is_a?(Array)
raise(Puppet::ParseError, 'union(): Requires 2 arrays')
end
arguments.reduce(:|)
result = first | second
return result
end
end

View file

@ -1,15 +0,0 @@
# 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:
ABCD
ASDF
EOS
) do |arguments|

View file

@ -40,10 +40,28 @@ module Puppet::Parser::Functions
unless arg.is_a?(Array) then
candidates = Array.new(1,arg)
end
# iterate over all paths within the candidates array
# iterate over all pathes within the candidates array
candidates.each do |path|
unless function_is_absolute_path([path])
raise Puppet::ParseError, ("#{path.inspect} is not an absolute 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.")
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 StandardError => detail
rescue Exception => detail
msg += "\n#{detail.class.name} #{detail}"
raise Puppet::ParseError, msg
ensure

View file

@ -1,31 +0,0 @@
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 items in arrays or maximum / minimum argument.
Plus all of the above, but with non-integer crap in arrays or maximum / minimum argument.
ENDHEREDOC

View file

@ -1,50 +0,0 @@
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_ipv4_address("8.8.8.8", "172.16.0.1", $my_ip)
validate_bool("8.8.8.8", "172.16.0.1", $my_ip)
The following values will fail, causing compilation to abort:

View file

@ -23,23 +23,16 @@ 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 the minimum length. It fails if the first
parameter can be given a 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,7 +43,9 @@ module Puppet::Parser::Functions
min_length = 0
end
raise Puppet::ParseError, "validate_slength(): Expected second argument to be equal to or larger than third argument" unless max_length >= min_length
if min_length > max_length
raise Puppet::ParseError, "validate_slength(): Expected second argument to be larger than third argument"
end
validator = lambda do |str|
unless str.length <= max_length and str.length >= min_length

View file

@ -1,47 +0,0 @@
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,31 +1,24 @@
Puppet::Type.type(:file_line).provide(:ruby) do
def exists?
if resource[:replace].to_s != 'true' and count_matches(match_regex) > 0
true
else
lines.find do |line|
line.chomp == resource[:line].chomp
end
lines.find do |line|
line.chomp == resource[:line].chomp
end
end
def create
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
if resource[:match]
handle_create_with_match
elsif resource[:after]
handle_create_with_after
else
append_line
end
end
def destroy
if resource[:match_for_absence].to_s == 'true' and resource[:match]
handle_destroy_with_match
else
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
@ -39,13 +32,10 @@ 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(match_regex)
match_count = count_matches(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]}'"
@ -53,7 +43,7 @@ Puppet::Type.type(:file_line).provide(:ruby) do
File.open(resource[:path], 'w') do |fh|
lines.each do |l|
fh.puts(match_regex.match(l) ? resource[:line] : l)
fh.puts(regex.match(l) ? resource[:line] : l)
if (match_count == 0 and regex_after)
if regex_after.match(l)
fh.puts(resource[:line])
@ -94,25 +84,6 @@ 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,25 +31,12 @@ 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
@ -62,18 +49,10 @@ 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 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
' A regex comparisson is performed against the line value and if it does not' +
' match an exception will be raised. '
end
newparam(:multiple) do
@ -93,31 +72,20 @@ 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::Util.absolute_path?(value)
raise Puppet::Error, "File paths must be fully qualified, not '#{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}'")
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]
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")
unless self[:line] and self[:path]
raise(Puppet::Error, "Both line and path are required attributes")
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.12.0",
"version": "4.6.0",
"author": "puppetlabs",
"summary": "Standard library of resources for Puppet modules.",
"license": "Apache-2.0",
@ -56,8 +56,7 @@
"operatingsystem": "Debian",
"operatingsystemrelease": [
"6",
"7",
"8"
"7"
]
},
{
@ -72,8 +71,7 @@
"operatingsystem": "Solaris",
"operatingsystemrelease": [
"10",
"11",
"12"
"11"
]
},
{
@ -101,11 +99,11 @@
"requirements": [
{
"name": "pe",
"version_requirement": ">= 3.0.0 < 2015.4.0"
"version_requirement": "3.x"
},
{
"name": "puppet",
"version_requirement": ">=2.7.20 <5.0.0"
"version_requirement": ">=2.7.20 <4.0.0"
}
],
"description": "Standard Library for Puppet Modules",

View file

@ -1,40 +0,0 @@
#! /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,20 +34,6 @@ 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,20 +27,6 @@ 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

@ -0,0 +1,22 @@
#! /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,26 +1,18 @@
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
describe 'ensure_resource function' do
describe 'ensure_resource function', :unless => fact('osfamily') =~ /windows/i do
describe 'success' do
it 'ensures a resource already declared' do
apply_manifest('')
it 'ensure_resource a package' do
apply_manifest('package { "rake": ensure => absent, provider => "gem", }')
pp = <<-EOS
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' })
$a = "rake"
ensure_resource('package', $a, {'provider' => 'gem'})
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,59 +3,80 @@ require 'spec_helper_acceptance'
describe 'fqdn_rand_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
describe 'success' do
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)"/)
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'
end
else
'/etc/facter/facts.d'
end
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 "(7203048515|2383756694)"/)
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
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
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
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "(3HS4mbuI3E|1jJtAMs94d)"/)
end
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "7oDp0KOr1b"/)
end
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
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
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "(3104058232|7100592312)"/)
end
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rand_string is "7203048515"/)
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
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"/)
end
end
end

View file

@ -3,57 +3,78 @@ require 'spec_helper_acceptance'
describe 'fqdn_rotate function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
describe 'success' do
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"\]/)
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'
end
else
'/etc/facter/facts.d'
end
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 \["c", "d", "a", "b"\]/)
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
it 'rotates strings' do
pp = <<-EOS
$a = 'abcd'
$o = fqdn_rotate($a)
notice(inline_template('fqdn_rotate is <%= @o.inspect %>'))
EOS
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
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is "dabc"/)
end
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is \["d", "a", "b", "c"\]/)
end
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
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
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is "cdab"/)
end
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/fqdn_rotate is \["c", "d", "a", "b"\]/)
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
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"/)
end
end
end

View file

@ -1,30 +0,0 @@
#! /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

@ -1,52 +0,0 @@
#! /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

@ -1,66 +0,0 @@
#! /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

@ -1,52 +0,0 @@
#! /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,29 +26,6 @@ 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

@ -0,0 +1,10 @@
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

@ -0,0 +1,15 @@
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

@ -0,0 +1,12 @@
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

@ -0,0 +1,10 @@
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

@ -0,0 +1,10 @@
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

@ -1,10 +0,0 @@
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

@ -1,10 +0,0 @@
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:
ubuntu-1404-x64:
centos-65-x64:
roles:
- agent
- default
platform: ubuntu-14.04-amd64
hypervisor: vagrant
box: puppetlabs/ubuntu-14.04-64-nocm
- 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

@ -1,12 +0,0 @@
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

@ -1,11 +0,0 @@
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

@ -1,12 +0,0 @@
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

@ -0,0 +1,10 @@
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

View file

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

View file

@ -0,0 +1,10 @@
HOSTS:
ubuntu-server-10044-x64:
roles:
- master
platform: ubuntu-10.04-amd64
box : ubuntu-server-10044-x64-vbox4210-nocm
box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-10044-x64-vbox4210-nocm.box
hypervisor : vagrant
CONFIG:
type: foss

View file

@ -0,0 +1,10 @@
HOSTS:
ubuntu-server-12042-x64:
roles:
- master
platform: ubuntu-12.04-amd64
box : ubuntu-server-12042-x64-vbox4210-nocm
box_url : http://puppet-vagrant-boxes.puppetlabs.com/ubuntu-server-12042-x64-vbox4210-nocm.box
hypervisor : vagrant
CONFIG:
type: foss

View file

@ -0,0 +1,11 @@
HOSTS:
ubuntu-server-1404-x64:
roles:
- master
platform: ubuntu-14.04-amd64
box : puppetlabs/ubuntu-14.04-64-nocm
box_url : https://vagrantcloud.com/puppetlabs/ubuntu-14.04-64-nocm
hypervisor : vagrant
CONFIG:
log_level : debug
type: git

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