summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.travis.yml14
-rw-r--r--Gemfile11
-rw-r--r--README.markdown423
-rw-r--r--lib/puppet/parser/functions/fqdn_rand_string.rb34
-rw-r--r--lib/puppet/parser/functions/pw_hash.rb56
-rw-r--r--lib/puppet/provider/file_line/ruby.rb14
-rw-r--r--lib/puppet/type/file_line.rb30
-rw-r--r--spec/acceptance/fqdn_rand_base64_spec.rb60
-rw-r--r--spec/acceptance/fqdn_rand_string_spec.rb60
-rw-r--r--spec/acceptance/pw_hash_spec.rb34
-rw-r--r--spec/functions/fqdn_rand_string_spec.rb91
-rw-r--r--spec/functions/pw_hash_spec.rb87
-rwxr-xr-xspec/unit/puppet/provider/file_line/ruby_spec.rb88
13 files changed, 872 insertions, 130 deletions
diff --git a/.travis.yml b/.travis.yml
index 503e184..b29f7e7 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -6,13 +6,19 @@ script: "bundle exec rake validate && bundle exec rake lint && bundle exec rake
matrix:
fast_finish: true
include:
+ - rvm: 1.9.3
+ env: PUPPET_GEM_VERSION="~> 3.4.0"
- rvm: 1.8.7
- env: PUPPET_GEM_VERSION="~> 2.7.0" FACTER_GEM_VERSION="~> 1.6.0"
- - rvm: 1.8.7
- env: PUPPET_GEM_VERSION="~> 2.7.0" FACTER_GEM_VERSION="~> 1.7.0"
+ env: PUPPET_GEM_VERSION="~> 3.0"
- rvm: 1.9.3
env: PUPPET_GEM_VERSION="~> 3.0"
- - rvm: 2.0.0
+ - rvm: 1.9.3
+ env: PUPPET_GEM_VERSION="~> 3.0" FUTURE_PARSER="yes"
+ - rvm: 2.1.5
env: PUPPET_GEM_VERSION="~> 3.0"
+ - rvm: 2.1.5
+ env: PUPPET_GEM_VERSION="~> 3.4.0"
+ - rvm: 2.1.5
+ env: PUPPET_GEM_VERSION="~> 3.0" FUTURE_PARSER="yes"
notifications:
email: false
diff --git a/Gemfile b/Gemfile
index e1a59fa..2d19594 100644
--- a/Gemfile
+++ b/Gemfile
@@ -21,12 +21,17 @@ group :development, :unit_tests do
end
beaker_version = ENV['BEAKER_VERSION']
+beaker_rspec_version = ENV['BEAKER_RSPEC_VERSION']
group :system_tests do
if beaker_version
- gem 'beaker', *location_for(beaker_version)
+ gem 'beaker', *location_for(beaker_version)
end
- gem 'beaker-rspec', :require => false
- gem 'serverspec', :require => false
+ if beaker_rspec_version
+ gem 'beaker-rspec', *location_for(beaker_rspec_version)
+ else
+ gem 'beaker-rspec', :require => false
+ end
+ gem 'serverspec', :require => false
end
facterversion = ENV['GEM_FACTER_VERSION'] || ENV['FACTER_GEM_VERSION']
diff --git a/README.markdown b/README.markdown
index 9c6a54b..3889088 100644
--- a/README.markdown
+++ b/README.markdown
@@ -99,44 +99,68 @@ If you want to use a standardized set of run stages for Puppet, `include stdlib`
### Functions
-* `abs`: Returns the absolute value of a number; for example, '-34.56' becomes '34.56'. Takes a single integer and float value as an argument. *Type*: rvalue
+#### `abs`
-* `any2array`: This converts any object to an array containing that object. Empty argument lists are converted to an empty array. Arrays are left untouched. Hashes are converted to arrays of alternating keys and values. *Type*: rvalue
+Returns the absolute value of a number; for example, '-34.56' becomes '34.56'. Takes a single integer and float value as an argument. *Type*: rvalue
-* `base64`: Converts a string to and from base64 encoding.
+#### `any2array`
+
+This converts any object to an array containing that object. Empty argument lists are converted to an empty array. Arrays are left untouched. Hashes are converted to arrays of alternating keys and values. *Type*: rvalue
+
+#### `base64`
+
+Converts a string to and from base64 encoding.
Requires an action ('encode', 'decode') and either a plain or base64-encoded
string. *Type*: rvalue
-* `basename`: Returns the `basename` of a path (optionally stripping an extension). For example:
+#### `basename`
+
+Returns the `basename` of a path (optionally stripping an extension). For example:
* ('/path/to/a/file.ext') returns 'file.ext'
* ('relative/path/file.ext') returns 'file.ext'
* ('/path/to/a/file.ext', '.ext') returns 'file'
*Type*: rvalue
-* `bool2num`: Converts a boolean to a number. Converts values:
+#### `bool2num`
+
+Converts a boolean to a number. Converts values:
* 'false', 'f', '0', 'n', and 'no' to 0.
* 'true', 't', '1', 'y', and 'yes' to 1.
Requires a single boolean or string as an input. *Type*: rvalue
-* `capitalize`: Capitalizes the first letter of a string or array of strings.
+#### `capitalize`
+
+Capitalizes the first letter of a string or array of strings.
Requires either a single string or an array as an input. *Type*: rvalue
-* `ceiling`: Returns the smallest integer greater than or equal to the argument.
+#### `ceiling`
+
+Returns the smallest integer greater than or equal to the argument.
Takes a single numeric value as an argument. *Type*: rvalue
-* `chomp`: Removes the record separator from the end of a string or an array of
+#### `chomp`
+
+Removes the record separator from the end of a string or an array of
strings; for example, 'hello\n' becomes 'hello'. Requires a single string or array as an input. *Type*: rvalue
-* `chop`: 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
+#### `chop`
+
+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
-* `concat`: Appends the contents of multiple arrays onto array 1. For example:
+#### `concat`
+
+Appends the contents of multiple arrays onto array 1. For example:
* `concat(['1','2','3'],'4')` results in: ['1','2','3','4'].
* `concat(['1','2','3'],'4',['5','6','7'])` results in: ['1','2','3','4','5','6','7'].
-* `count`: Takes an array as first argument and an optional second argument. Count the number of elements in array that matches second argument. If called with only an array, it counts the number of elements that are **not** nil/undef. *Type*: rvalue
+#### `count`
+
+Takes an array as first argument and an optional second argument. Count the number of elements in array that matches second argument. If called with only an array, it counts the number of elements that are **not** nil/undef. *Type*: rvalue
-* `defined_with_params`: Takes a resource reference and an optional hash of attributes. Returns 'true' if a resource with the specified attributes has already been added to the catalog. Returns 'false' otherwise.
+#### `defined_with_params`
+
+Takes a resource reference and an optional hash of attributes. Returns 'true' if a resource with the specified attributes has already been added to the catalog. Returns 'false' otherwise.
```
user { 'dan':
@@ -150,28 +174,48 @@ strings; for example, 'hello\n' becomes 'hello'. Requires a single string or arr
*Type*: rvalue
-* `delete`: Deletes all instances of a given element from an array, substring from a
+#### `delete`
+
+Deletes all instances of a given element from an array, substring from a
string, or key from a hash. For example, `delete(['a','b','c','b'], 'b')` returns ['a','c']; `delete('abracadabra', 'bra')` returns 'acada'. `delete({'a' => 1,'b' => 2,'c' => 3},['b','c'])` returns {'a'=> 1} *Type*: rvalue
-* `delete_at`: Deletes a determined indexed value from an array. For example, `delete_at(['a','b','c'], 1)` returns ['a','c']. *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_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
+#### `delete_values`
-* `delete_undef_values`: Deletes all instances of the undef value from an array or hash. For example, `$hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false})` returns {a => 'A', b => '', d => false}. *Type*: rvalue
+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
-* `difference`: Returns the difference between two arrays.
+#### `delete_undef_values`
+
+Deletes all instances of the undef value from an array or hash. For example, `$hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false})` returns {a => 'A', b => '', d => false}. *Type*: rvalue
+
+#### `difference`
+
+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"].
-* `dirname`: Returns the `dirname` of a path. For example, `dirname('/path/to/a/file.ext')` returns '/path/to/a'.
+#### `dirname`
+
+Returns the `dirname` of a path. For example, `dirname('/path/to/a/file.ext')` returns '/path/to/a'.
+
+#### `downcase`
+
+Converts the case of a string or of all strings in an array to lowercase. *Type*: rvalue
+
+#### `empty`
-* `downcase`: Converts the case of a string or of all strings in an array to lowercase. *Type*: rvalue
+Returns 'true' if the variable is empty. *Type*: rvalue
-* `empty`: Returns 'true' if the variable is empty. *Type*: rvalue
+#### `ensure_packages`
-* `ensure_packages`: Takes a list of packages and only installs them if they don't already exist. It optionally takes a hash as a second parameter to be passed as the third argument to the `ensure_resource()` function. *Type*: statement
+Takes a list of packages 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 list of attributes that describe a resource.
+#### `ensure_resource`
+
+Takes a resource type, title, and a list of attributes that describe a resource.
```
user { 'dan':
@@ -191,20 +235,47 @@ also appear in the second array. For example, `difference(["a","b","c"],["b","c"
*Type*: statement
-* `flatten`: This function flattens any deeply nested arrays and returns a single flat array as a result. For example, `flatten(['a', ['b', ['c']]])` returns ['a','b','c']. *Type*: rvalue
+#### `flatten`
+
+This function flattens any deeply nested arrays and returns a single flat array as a result. For example, `flatten(['a', ['b', ['c']]])` returns ['a','b','c']. *Type*: rvalue
+
+#### `floor`
-* `floor`: Returns the largest integer less than or equal to the argument.
+Returns the largest integer less than or equal to the argument.
Takes a single numeric value as an argument. *Type*: rvalue
-* `fqdn_rotate`: Rotates an array a random number of times based on a node's fqdn. *Type*: rvalue
+#### `fqdn_rand_string`
+
+Generates a random alphanumeric string using an optionally-specified character set (default is alphanumeric), combining the `$fqdn` fact and an optional seed for repeatable randomness.
+
+*Usage:*
+```
+fqdn_rand_string(LENGTH, [CHARSET], [SEED])
+```
+*Examples:*
+```
+fqdn_rand_string(10)
+fqdn_rand_string(10, 'ABCDEF!@#$%^')
+fqdn_rand_string(10, '', 'custom seed')
+```
+
+*Type*: rvalue
-* `get_module_path`: Returns the absolute path of the specified module for the current environment.
+#### `fqdn_rotate`
+
+Rotates an array a random number of times based on a node's fqdn. *Type*: rvalue
+
+#### `get_module_path`
+
+Returns the absolute path of the specified module for the current environment.
`$module_path = get_module_path('stdlib')`
*Type*: rvalue
-* `getparam`: Takes a resource reference and the name of the parameter and
+#### `getparam`
+
+Takes a resource reference and the name of the parameter and
returns the value of the resource's parameter. For example, the following code returns 'param_value'.
*Example:*
@@ -222,7 +293,9 @@ returns the value of the resource's parameter. For example, the following code r
*Type*: rvalue
-* `getvar`: Lookup a variable in a remote namespace.
+#### `getvar`
+
+Lookup a variable in a remote namespace.
For example:
@@ -241,9 +314,13 @@ returns the value of the resource's parameter. For example, the following code r
*Type*: rvalue
-* `grep`: This function searches through an array and returns any elements that match the provided regular expression. For example, `grep(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['aaa','aaaddd']. *Type*: rvalue
+#### `grep`
+
+This function searches through an array and returns any elements that match the provided regular expression. For example, `grep(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['aaa','aaaddd']. *Type*: rvalue
+
+#### `has_interface_with`
-* `has_interface_with`: Returns boolean based on kind and value:
+Returns boolean based on kind and value:
* macaddress
* netmask
* ipaddress
@@ -264,11 +341,17 @@ returns the value of the resource's parameter. For example, the following code r
*Type*: rvalue
-* `has_ip_address`: Returns true if the client has the requested IP address on some interface. This function iterates through the `interfaces` fact and checks the `ipaddress_IFACE` facts, performing a simple string comparison. *Type*: rvalue
+#### `has_ip_address`
-* `has_ip_network`: Returns true if the client has an IP address within the requested network. This function iterates through the 'interfaces' fact and checks the 'network_IFACE' facts, performing a simple string comparision. *Type*: rvalue
+Returns true if the client has the requested IP address on some interface. This function iterates through the `interfaces` fact and checks the `ipaddress_IFACE` facts, performing a simple string comparison. *Type*: rvalue
-* `has_key`: Determine if a hash has a certain key value.
+#### `has_ip_network`
+
+Returns true if the client has an IP address within the requested network. This function iterates through the 'interfaces' fact and checks the 'network_IFACE' facts, performing a simple string comparision. *Type*: rvalue
+
+#### `has_key`
+
+Determine if a hash has a certain key value.
*Example*:
@@ -284,39 +367,73 @@ returns the value of the resource's parameter. For example, the following code r
*Type*: rvalue
-* `hash`: This function converts an array into a hash. For example, `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}. *Type*: rvalue
+#### `hash`
+
+This function converts an array into a hash. For example, `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}. *Type*: rvalue
+
+#### `intersection`
+
+This function returns an array an intersection of two. For example, `intersection(["a","b","c"],["b","c","d"])` returns ["b","c"].
+
+#### `is_array`
+
+Returns 'true' if the variable passed to this function is an array. *Type*: rvalue
+
+#### `is_bool`
+
+Returns 'true' if the variable passed to this function is a boolean. *Type*: rvalue
+
+#### `is_domain_name`
+
+Returns 'true' if the string passed to this function is a syntactically correct domain name. *Type*: rvalue
+
+#### `is_float`
+
+Returns 'true' if the variable passed to this function is a float. *Type*: rvalue
+
+#### `is_function_available`
+
+This function accepts a string as an argument and determines whether the Puppet runtime has access to a function by that name. It returns 'true' if the function exists, 'false' if not. *Type*: rvalue
+
+#### `is_hash`
+
+Returns 'true' if the variable passed to this function is a hash. *Type*: rvalue
+
+#### `is_integer`
+
+Returns 'true' if the variable returned to this string is an integer. *Type*: rvalue
-* `intersection`: This function returns an array an intersection of two. For example, `intersection(["a","b","c"],["b","c","d"])` returns ["b","c"].
+#### `is_ip_address`
-* `is_array`: Returns 'true' if the variable passed to this function is an array. *Type*: rvalue
+Returns 'true' if the string passed to this function is a valid IP address. *Type*: rvalue
-* `is_bool`: Returns 'true' if the variable passed to this function is a boolean. *Type*: rvalue
+#### `is_mac_address`
-* `is_domain_name`: Returns 'true' if the string passed to this function is a syntactically correct domain name. *Type*: rvalue
+Returns 'true' if the string passed to this function is a valid MAC address. *Type*: rvalue
-* `is_float`: Returns 'true' if the variable passed to this function is a float. *Type*: rvalue
+#### `is_numeric`
-* `is_function_available`: This function accepts a string as an argument and determines whether the Puppet runtime has access to a function by that name. It returns 'true' if the function exists, 'false' if not. *Type*: rvalue
+Returns 'true' if the variable passed to this function is a number. *Type*: rvalue
-* `is_hash`: Returns 'true' if the variable passed to this function is a hash. *Type*: rvalue
+#### `is_string`
-* `is_integer`: Returns 'true' if the variable returned to this string is an integer. *Type*: rvalue
+Returns 'true' if the variable passed to this function is a string. *Type*: rvalue
-* `is_ip_address`: Returns 'true' if the string passed to this function is a valid IP address. *Type*: rvalue
+#### `join`
-* `is_mac_address`: Returns 'true' if the string passed to this function is a valid MAC address. *Type*: rvalue
+This function joins an array into a string using a separator. For example, `join(['a','b','c'], ",")` results in: "a,b,c". *Type*: rvalue
-* `is_numeric`: Returns 'true' if the variable passed to this function is a number. *Type*: rvalue
+#### `join_keys_to_values`
-* `is_string`: Returns 'true' if the variable passed to this function is a string. *Type*: rvalue
+This function joins each key of a hash to that key's corresponding value with a separator. Keys and values are cast to strings. The return value is an array in which each element is one joined key/value pair. For example, `join_keys_to_values({'a'=>1,'b'=>2}, " is ")` results in ["a is 1","b is 2"]. *Type*: rvalue
-* `join`: This function joins an array into a string using a separator. For example, `join(['a','b','c'], ",")` results in: "a,b,c". *Type*: rvalue
+#### `keys`
-* `join_keys_to_values`: This function joins each key of a hash to that key's corresponding value with a separator. Keys and values are cast to strings. The return value is an array in which each element is one joined key/value pair. For example, `join_keys_to_values({'a'=>1,'b'=>2}, " is ")` results in ["a is 1","b is 2"]. *Type*: rvalue
+Returns the keys of a hash as an array. *Type*: rvalue
-* `keys`: Returns the keys of a hash as an array. *Type*: rvalue
+#### `loadyaml`
-* `loadyaml`: Load a YAML file containing an array, string, or hash, and return the data in the corresponding native data type. For example:
+Load a YAML file containing an array, string, or hash, and return the data in the corresponding native data type. For example:
```
$myhash = loadyaml('/etc/puppet/data/myhash.yaml')
@@ -324,13 +441,21 @@ returns the value of the resource's parameter. For example, the following code r
*Type*: rvalue
-* `lstrip`: Strips leading spaces to the left of a string. *Type*: rvalue
+#### `lstrip`
-* `max`: Returns the highest value of all arguments. Requires at least one argument. *Type*: rvalue
+Strips leading spaces to the left of a string. *Type*: rvalue
-* `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'. *Type*: rvalue
+#### `max`
-* `merge`: Merges two or more hashes together and returns the resulting hash.
+Returns the highest value of all arguments. Requires at least one argument. *Type*: rvalue
+
+#### `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'. *Type*: rvalue
+
+#### `merge`
+
+Merges two or more hashes together and returns the resulting hash.
*Example*:
@@ -344,15 +469,25 @@ returns the value of the resource's parameter. For example, the following code r
When there is a duplicate key, the key in the rightmost hash "wins." *Type*: rvalue
-* `min`: Returns the lowest value of all arguments. Requires at least one argument. *Type*: rvalue
+#### `min`
+
+Returns the lowest value of all arguments. Requires at least one argument. *Type*: rvalue
+
+#### `num2bool`
+
+This function converts a number or a string representation of a number into a true boolean. Zero or anything non-numeric becomes 'false'. Numbers greater than 0 become 'true'. *Type*: rvalue
-* `num2bool`: This function converts a number or a string representation of a number into a true boolean. Zero or anything non-numeric becomes 'false'. Numbers greater than 0 become 'true'. *Type*: rvalue
+#### `parsejson`
-* `parsejson`: This function accepts JSON as a string and converts into the correct Puppet structure. *Type*: rvalue
+This function accepts JSON as a string and converts into the correct Puppet structure. *Type*: rvalue
-* `parseyaml`: This function accepts YAML as a string and converts it into the correct Puppet structure. *Type*: rvalue
+#### `parseyaml`
-* `pick`: From a list of values, returns the first value that is not undefined or an empty string. Takes any number of arguments, and raises an error if all values are undefined or empty.
+This function accepts YAML as a string and converts it into the correct Puppet structure. *Type*: rvalue
+
+#### `pick`
+
+From a list of values, returns the first value that is not undefined or an empty string. Takes any number of arguments, and raises an error if all values are undefined or empty.
```
$real_jenkins_version = pick($::jenkins_version, '1.449')
@@ -360,10 +495,14 @@ returns the value of the resource's parameter. For example, the following code r
*Type*: rvalue
-* `prefix`: This function 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'], and `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'pa'=>'b','pb'=>'c','pc'=>'d'}. *Type*: rvalue
+#### `prefix`
+
+This function 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'], and `prefix({'a'=>'b','b'=>'c','c'=>'d'}, 'p')` returns {'pa'=>'b','pb'=>'c','pc'=>'d'}. *Type*: rvalue
+
+#### `assert_private`
-* `assert_private`: This function sets the current class or definition as private.
+This function sets the current class or definition as private.
Calling the class or definition from outside the current module will fail. For example, `assert_private()` called in class `foo::bar` outputs the following message if class is called from outside module `foo`:
```
@@ -378,7 +517,27 @@ Calling the class or definition from outside the current module will fail. For e
*Type*: statement
-* `range`: When given range in the form of '(start, stop)', `range` extrapolates a range as an array. For example, `range("0", "9")` returns [0,1,2,3,4,5,6,7,8,9]. Zero-padded strings are converted to integers automatically, so `range("00", "09")` returns [0,1,2,3,4,5,6,7,8,9].
+#### `pw_hash`
+
+Hashes a password using the crypt function. Provides a hash usable on most POSIX systems.
+
+The first argument to this function is the password to hash. If it is undef or an empty string, this function returns undef.
+
+The second argument to this function is which type of hash to use. It will be converted into the appropriate crypt(3) hash specifier. Valid hash types are:
+
+|Hash type |Specifier|
+|---------------------|---------|
+|MD5 |1 |
+|SHA-256 |5 |
+|SHA-512 (recommended)|6 |
+
+The third argument to this function is the salt to use.
+
+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`
+
+When given range in the form of '(start, stop)', `range` extrapolates a range as an array. For example, `range("0", "9")` returns [0,1,2,3,4,5,6,7,8,9]. Zero-padded strings are converted to integers automatically, so `range("00", "09")` returns [0,1,2,3,4,5,6,7,8,9].
Non-integer strings are accepted; `range("a", "c")` returns ["a","b","c"], and `range("host01", "host10")` returns ["host01", "host02", ..., "host09", "host10"].
@@ -386,26 +545,46 @@ Calling the class or definition from outside the current module will fail. For e
*Type*: rvalue
-* `reject`: This function searches through an array and rejects all elements that match the provided regular expression. For example, `reject(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['bbb','ccc']. *Type*: rvalue
+#### `reject`
+
+This function searches through an array and rejects all elements that match the provided regular expression. For example, `reject(['aaa','bbb','ccc','aaaddd'], 'aaa')` returns ['bbb','ccc']. *Type*: rvalue
+
+#### `reverse`
+
+Reverses the order of a string or array. *Type*: rvalue
+
+#### `rstrip`
+
+Strips leading spaces to the right of the string.*Type*: rvalue
+
+#### `shuffle`
+
+Randomizes the order of a string or array elements. *Type*: rvalue
+
+#### `size`
-* `reverse`: Reverses the order of a string or array. *Type*: rvalue
+Returns the number of elements in a string or array. *Type*: rvalue
-* `rstrip`: Strips leading spaces to the right of the string.*Type*: rvalue
+#### `sort`
-* `shuffle`: Randomizes the order of a string or array elements. *Type*: rvalue
+Sorts strings and arrays lexically. *Type*: rvalue
-* `size`: Returns the number of elements in a string or array. *Type*: rvalue
+#### `squeeze`
-* `sort`: Sorts strings and arrays lexically. *Type*: rvalue
+Returns a new string where runs of the same character that occur in this set are replaced by a single character. *Type*: rvalue
-* `squeeze`: Returns a new string where runs of the same character that occur in this set are replaced by a single character. *Type*: rvalue
+#### `str2bool`
-* `str2bool`: This 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
+This 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`: This converts a string to a salted-SHA512 password hash, used for OS X versions >= 10.7. Given any string, this function returns a hex version of a salted-SHA512 password hash, which can be inserted into your Puppet
+#### `str2saltedsha512`
+
+This converts a string to a salted-SHA512 password hash, used for OS X versions >= 10.7. Given any string, this function returns a hex version of a salted-SHA512 password hash, which can be inserted into your Puppet
manifests as a valid password attribute. *Type*: rvalue
-* `strftime`: This function returns formatted time. For example, `strftime("%s")` returns the time since epoch, and `strftime("%Y=%m-%d")` returns the date. *Type*: rvalue
+#### `strftime`
+
+This function returns formatted time. For example, `strftime("%s")` returns the time since epoch, and `strftime("%Y=%m-%d")` returns the date. *Type*: rvalue
*Format:*
@@ -455,35 +634,59 @@ manifests as a valid password attribute. *Type*: rvalue
* `%Z`: Time zone name
* `%%`: Literal '%' character
-* `strip`: This function removes leading and trailing whitespace from a string or from every string inside an array. For example, `strip(" aaa ")` results in "aaa". *Type*: rvalue
+#### `strip`
+
+This function removes leading and trailing whitespace from a string or from every string inside an array. For example, `strip(" aaa ")` results in "aaa". *Type*: rvalue
+
+#### `suffix`
+
+This function applies a suffix to all elements in an array. For example, `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp']. *Type*: rvalue
+
+#### `swapcase`
+
+This function swaps the existing case of a string. For example, `swapcase("aBcD")` results in "AbCd". *Type*: rvalue
-* `suffix`: This function applies a suffix to all elements in an array. For example, `suffix(['a','b','c'], 'p')` returns ['ap','bp','cp']. *Type*: rvalue
+#### `time`
-* `swapcase`: This function swaps the existing case of a string. For example, `swapcase("aBcD")` results in "AbCd". *Type*: rvalue
+This function returns the current time since epoch as an integer. For example, `time()` returns something like '1311972653'. *Type*: rvalue
-* `time`: This function returns the current time since epoch as an integer. For example, `time()` returns something like '1311972653'. *Type*: rvalue
+#### `to_bytes`
-* `to_bytes`: Converts the argument into bytes, for example 4 kB becomes 4096.
+Converts the argument into bytes, for example 4 kB becomes 4096.
Takes a single string value as an argument. *Type*: rvalue
-* `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 may be used. *Type*: rvalue
+#### `type3x`
-* `type_of`: Returns the literal type when passed a value. Requires the new
+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 may be used. *Type*: rvalue
+
+#### `type_of`
+
+Returns the literal type when passed a value. Requires the new
parser. Useful for comparison of types with `<=` such as in `if
type_of($some_value) <= Array[String] { ... }` (which is equivalent to `if
$some_value =~ Array[String] { ... }`) *Type*: rvalue
-* `union`: This function returns a union of two arrays. For example, `union(["a","b","c"],["b","c","d"])` returns ["a","b","c","d"].
+#### `union`
+
+This function returns a union of two arrays. For example, `union(["a","b","c"],["b","c","d"])` returns ["a","b","c","d"].
+
+#### `unique`
-* `unique`: This function removes duplicates from strings and arrays. For example, `unique("aabbcc")` returns 'abc'.
+This function removes duplicates from strings and arrays. For example, `unique("aabbcc")` returns 'abc'.
You can also use this with arrays. For example, `unique(["a","a","b","b","c","c"])` returns ["a","b","c"]. *Type*: rvalue
-* `upcase`: Converts an object, array or hash of objects that respond to upcase to uppercase. For example, `upcase("abcd")` returns 'ABCD'. *Type*: rvalue
+#### `upcase`
+
+Converts an object, array or hash of objects that respond to upcase to uppercase. For example, `upcase("abcd")` returns 'ABCD'. *Type*: rvalue
+
+#### `uriescape`
+
+Urlencodes a string or array of strings. Requires either a single string or an array as an input. *Type*: rvalue
-* `uriescape`: Urlencodes a string or array of strings. Requires either a single string or an array as an input. *Type*: rvalue
+#### `validate_absolute_path`
-* `validate_absolute_path`: Validate the string represents an absolute path in the filesystem. This function works for Windows and Unix style paths.
+Validate the string represents an absolute path in the filesystem. This function works for Windows and Unix style paths.
The following values will pass:
@@ -512,7 +715,9 @@ You can also use this with arrays. For example, `unique(["a","a","b","b","c","c"
*Type*: statement
-* `validate_array`: Validate that all passed values are array data structures. Abort catalog compilation if any value fails this check.
+#### `validate_array`
+
+Validate that all passed values are array data structures. Abort catalog compilation if any value fails this check.
The following values will pass:
@@ -532,7 +737,9 @@ You can also use this with arrays. For example, `unique(["a","a","b","b","c","c"
*Type*: statement
-* `validate_augeas`: Performs validation of a string using an Augeas lens.
+#### `validate_augeas`
+
+Performs validation of a string using an Augeas lens.
The first argument of this function should be the string to test, and the second argument should be the name of the Augeas lens to use. If Augeas fails to parse the string with the lens, the compilation aborts with a parse error.
A third optional argument lists paths which should **not** be found in the file. The `$file` variable points to the location of the temporary file being tested in the Augeas tree.
@@ -557,7 +764,9 @@ The first argument of this function should be the string to test, and the second
*Type*: statement
-* `validate_bool`: Validate that all passed values are either true or false. Abort catalog compilation if any value fails this check.
+#### `validate_bool`
+
+Validate that all passed values are either true or false. Abort catalog compilation if any value fails this check.
The following values will pass:
@@ -578,7 +787,9 @@ The first argument of this function should be the string to test, and the second
*Type*: statement
-* `validate_cmd`: Performs validation of a string with an external command. The first argument of this function should be a string to test, and the second argument should be a path to a test command taking a % as a placeholder for the file path (will default to the end of the command if no % placeholder given). If the command, launched against a tempfile containing the passed string, returns a non-null value, compilation will abort with a parse error.
+#### `validate_cmd`
+
+Performs validation of a string with an external command. The first argument of this function should be a string to test, and the second argument should be a path to a test command taking a % as a placeholder for the file path (will default to the end of the command if no % placeholder given). If the command, launched against a tempfile containing the passed string, returns a non-null value, compilation will abort with a parse error.
If a third argument is specified, this will be the error message raised and seen by the user.
@@ -593,7 +804,9 @@ If a third argument is specified, this will be the error message raised and seen
*Type*: statement
-* `validate_hash`: Validates that all passed values are hash data structures. Abort catalog compilation if any value fails this check.
+#### `validate_hash`
+
+Validates that all passed values are hash data structures. Abort catalog compilation if any value fails this check.
The following values will pass:
@@ -613,7 +826,9 @@ If a third argument is specified, this will be the error message raised and seen
*Type*: statement
-* `validate_integer`: Validate that the first argument is an integer (or an array of integers). Abort catalog compilation if any of the checks fail.
+#### `validate_integer`
+
+Validate that the first argument is an integer (or an array of integers). Abort catalog compilation if any of the checks fail.
The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max.
@@ -669,7 +884,9 @@ If a third argument is specified, this will be the error message raised and seen
*Type*: statement
-* `validate_numeric`: Validate that the first argument is a numeric value (or an array of numeric values). Abort catalog compilation if any of the checks fail.
+#### `validate_numeric`
+
+Validate that the first argument is a numeric value (or an array of numeric values). Abort catalog compilation if any of the checks fail.
The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max.
@@ -683,7 +900,9 @@ If a third argument is specified, this will be the error message raised and seen
*Type*: statement
-* `validate_re`: Performs simple validation of a string against one or more regular expressions. The first argument of this function should be the string to
+#### `validate_re`
+
+Performs simple validation of a string against one or more regular expressions. The first argument of this function should be the string to
test, and the second argument should be a stringified regular expression
(without the // delimiters) or an array of regular expressions. If none
of the regular expressions match the string passed in, compilation aborts with a parse error.
@@ -711,7 +930,9 @@ of the regular expressions match the string passed in, compilation aborts with a
*Type*: statement
-* `validate_slength`: Validates that the first argument is a string (or an array of strings), and is less than or equal to the length of the second argument. It fails if the first argument is not a string or array of strings, or if arg 2 is not convertable to a number.
+#### `validate_slength`
+
+Validates that the first argument is a string (or an array of strings), and is less than or equal to the length of the second argument. It fails if the first argument is not a string or array of strings, or if arg 2 is not convertable to a number.
The following values pass:
@@ -729,7 +950,9 @@ of the regular expressions match the string passed in, compilation aborts with a
*Type*: statement
-* `validate_string`: Validates that all passed values are string data structures. Aborts catalog compilation if any value fails this check.
+#### `validate_string`
+
+Validates that all passed values are string data structures. Aborts catalog compilation if any value fails this check.
The following values pass:
@@ -749,7 +972,9 @@ of the regular expressions match the string passed in, compilation aborts with a
*Type*: statement
-* `values`: When given a hash, this function returns the values of that hash.
+#### `values`
+
+When given a hash, this function returns the values of that hash.
*Examples:*
@@ -766,7 +991,9 @@ of the regular expressions match the string passed in, compilation aborts with a
*Type*: rvalue
-* `values_at`: Finds value inside an array based on location. The first argument is the array you want to analyze, and the second element can be a combination of:
+#### `values_at`
+
+Finds value inside an array based on location. The first argument is the array you want to analyze, and the second element can be a combination of:
* A single numeric index
* A range in the form of 'start-stop' (eg. 4-9)
@@ -776,7 +1003,9 @@ of the regular expressions match the string passed in, compilation aborts with a
*Type*: rvalue
-* `zip`: Takes one element from first array and merges corresponding elements from second array. 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
+#### `zip`
+
+Takes one element from first array and merges corresponding elements from second array. 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
diff --git a/lib/puppet/parser/functions/fqdn_rand_string.rb b/lib/puppet/parser/functions/fqdn_rand_string.rb
new file mode 100644
index 0000000..785c9fd
--- /dev/null
+++ b/lib/puppet/parser/functions/fqdn_rand_string.rb
@@ -0,0 +1,34 @@
+Puppet::Parser::Functions::newfunction(
+ :fqdn_rand_string,
+ :arity => -2,
+ :type => :rvalue,
+ :doc => "Usage: `fqdn_rand_string(LENGTH, [CHARSET], [SEED])`. LENGTH is
+ required and must be a positive integer. CHARSET is optional and may be
+ `undef` or a string. SEED is optional and may be any number or string.
+
+ Generates a random string LENGTH characters long using the character set
+ provided by CHARSET, combining the `$fqdn` fact and the value of SEED for
+ repeatable randomness. (That is, each node will get a different random
+ string from this function, but a given node's result will be the same every
+ time unless its hostname changes.) Adding a SEED can be useful if you need
+ more than one unrelated string. CHARSET will default to alphanumeric if
+ `undef` or an empty string.") do |args|
+ raise(ArgumentError, "fqdn_rand_string(): wrong number of arguments (0 for 1)") if args.size == 0
+ Puppet::Parser::Functions.function('is_integer')
+ raise(ArgumentError, "fqdn_rand_base64(): first argument must be a positive integer") unless function_is_integer([args[0]]) and args[0].to_i > 0
+ raise(ArgumentError, "fqdn_rand_base64(): second argument must be undef or a string") unless args[1].nil? or args[1].is_a? String
+
+ Puppet::Parser::Functions.function('fqdn_rand')
+
+ length = args.shift.to_i
+ charset = args.shift.to_s.chars.to_a
+
+ charset = (0..9).map { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a if charset.empty?
+
+ rand_string = ''
+ for current in 1..length
+ rand_string << charset[function_fqdn_rand([charset.size, (args + [current.to_s]).join(':')]).to_i]
+ end
+
+ rand_string
+end
diff --git a/lib/puppet/parser/functions/pw_hash.rb b/lib/puppet/parser/functions/pw_hash.rb
new file mode 100644
index 0000000..ad3e393
--- /dev/null
+++ b/lib/puppet/parser/functions/pw_hash.rb
@@ -0,0 +1,56 @@
+Puppet::Parser::Functions::newfunction(
+ :pw_hash,
+ :type => :rvalue,
+ :arity => 3,
+ :doc => "Hashes a password using the crypt function. Provides a hash
+ usable on most POSIX systems.
+
+ The first argument to this function is the password to hash. If it is
+ undef or an empty string, this function returns undef.
+
+ The second argument to this function is which type of hash to use. It
+ will be converted into the appropriate crypt(3) hash specifier. Valid
+ hash types are:
+
+ |Hash type |Specifier|
+ |---------------------|---------|
+ |MD5 |1 |
+ |SHA-256 |5 |
+ |SHA-512 (recommended)|6 |
+
+ The third argument to this function is the salt to use.
+
+ 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.") do |args|
+ raise ArgumentError, "pw_hash(): wrong number of arguments (#{args.size} for 3)" if args.size != 3
+ raise ArgumentError, "pw_hash(): first argument must be a string" unless args[0].is_a? String or args[0].nil?
+ raise ArgumentError, "pw_hash(): second argument must be a string" unless args[1].is_a? String
+ hashes = { 'md5' => '1',
+ 'sha-256' => '5',
+ 'sha-512' => '6' }
+ hash_type = hashes[args[1].downcase]
+ raise ArgumentError, "pw_hash(): #{args[1]} is not a valid hash type" if hash_type.nil?
+ raise ArgumentError, "pw_hash(): third argument must be a string" unless args[2].is_a? String
+ raise ArgumentError, "pw_hash(): third argument must not be empty" if args[2].empty?
+ raise ArgumentError, "pw_hash(): characters in salt must be in the set [a-zA-Z0-9./]" unless args[2].match(/\A[a-zA-Z0-9.\/]+\z/)
+
+ password = args[0]
+ return nil if password.nil? or password.empty?
+
+ # handle weak implementations of String#crypt
+ if 'test'.crypt('$1$1') != '$1$1$Bp8CU9Oujr9SSEw53WV6G.'
+ # JRuby < 1.7.17
+ if RUBY_PLATFORM == 'java'
+ # override String#crypt for password variable
+ def password.crypt(salt)
+ # puppetserver bundles Apache Commons Codec
+ org.apache.commons.codec.digest.Crypt.crypt(self.to_java_bytes, salt)
+ end
+ else
+ # MS Windows and other systems that don't support enhanced salts
+ raise Puppet::ParseError, 'system does not support enhanced salts'
+ end
+ end
+ password.crypt("$#{hash_type}$#{args[2]}")
+end
diff --git a/lib/puppet/provider/file_line/ruby.rb b/lib/puppet/provider/file_line/ruby.rb
index ae1a8b3..e7854f0 100644
--- a/lib/puppet/provider/file_line/ruby.rb
+++ b/lib/puppet/provider/file_line/ruby.rb
@@ -34,13 +34,22 @@ Puppet::Type.type(:file_line).provide(:ruby) do
def handle_create_with_match()
regex = resource[:match] ? Regexp.new(resource[:match]) : nil
+ regex_after = resource[:after] ? Regexp.new(resource[:after]) : nil
match_count = count_matches(regex)
+
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
+
File.open(resource[:path], 'w') do |fh|
lines.each do |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])
+ match_count += 1 #Increment match_count to indicate that the new line has been inserted.
+ end
+ end
end
if (match_count == 0)
@@ -78,7 +87,10 @@ Puppet::Type.type(:file_line).provide(:ruby) do
#
# @api private
def append_line
- File.open(resource[:path], 'a') do |fh|
+ File.open(resource[:path], 'w') do |fh|
+ lines.each do |l|
+ fh.puts(l)
+ end
fh.puts resource[:line]
end
end
diff --git a/lib/puppet/type/file_line.rb b/lib/puppet/type/file_line.rb
index df263e6..29f9538 100644
--- a/lib/puppet/type/file_line.rb
+++ b/lib/puppet/type/file_line.rb
@@ -3,9 +3,9 @@ Puppet::Type.newtype(:file_line) do
desc <<-EOT
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 add the line to
- ensure the desired state. Multiple resources may be declared to manage
- multiple lines in the same file.
+ 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
+ be declared to manage multiple lines in the same file.
Example:
@@ -13,6 +13,7 @@ Puppet::Type.newtype(:file_line) do
path => '/etc/sudoers',
line => '%sudo ALL=(ALL) ALL',
}
+
file_line { 'sudo_rule_nopw':
path => '/etc/sudoers',
line => '%sudonopw ALL=(ALL) NOPASSWD: ALL',
@@ -21,6 +22,18 @@ Puppet::Type.newtype(:file_line) do
In this example, Puppet will ensure 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 will look for a line beginning with export
+ followed by HTTP_PROXY and replace it with the value in line.
+
**Autorequires:** If Puppet is managing the file that will contain the line
being managed, the file_line resource will autorequire that file.
@@ -36,12 +49,15 @@ Puppet::Type.newtype(:file_line) do
end
newparam(:match) do
- desc 'An optional regular expression to run against existing lines in the file;\n' +
- 'if a match is found, we replace that line rather than adding a new line.'
+ desc 'An optional ruby regular expression to run against existing lines in the file.' +
+ ' If a match is found, we replace that line rather than adding a new line.' +
+ ' A regex comparisson is performed against the line value and if it does not' +
+ ' match an exception will be raised. '
end
newparam(:multiple) do
- desc 'An optional value to determine if match can change multiple lines.'
+ desc 'An optional value to determine if match can change multiple lines.' +
+ ' If set to false, an exception will be raised if more than one line matches'
newvalues(true, false)
end
@@ -50,7 +66,7 @@ Puppet::Type.newtype(:file_line) do
end
newparam(:line) do
- desc 'The line to be appended to the file located by the path parameter.'
+ desc 'The line to be appended to the file or used to replace matches found by the match attribute.'
end
newparam(:path) do
diff --git a/spec/acceptance/fqdn_rand_base64_spec.rb b/spec/acceptance/fqdn_rand_base64_spec.rb
new file mode 100644
index 0000000..1b4eb72
--- /dev/null
+++ b/spec/acceptance/fqdn_rand_base64_spec.rb
@@ -0,0 +1,60 @@
+#! /usr/bin/env ruby -S rspec
+require 'spec_helper_acceptance'
+
+describe 'fqdn_rand_base64 function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
+ describe 'success' do
+ let(:facts_d) do
+ if fact('is_pe', '--puppet') == "true"
+ if fact('osfamily') =~ /windows/i
+ if fact('kernelmajversion').to_f < 6.0
+ 'c:/documents and settings/all users/application data/puppetlabs/facter/facts.d'
+ else
+ 'c:/programdata/puppetlabs/facter/facts.d'
+ end
+ else
+ '/etc/puppetlabs/facter/facts.d'
+ end
+ else
+ '/etc/facter/facts.d'
+ end
+ end
+ after :each do
+ shell("if [ -f '#{facts_d}/fqdn.txt' ] ; then rm '#{facts_d}/fqdn.txt' ; fi")
+ end
+ before :each do
+ #no need to create on windows, pe creates by default
+ if fact('osfamily') !~ /windows/i
+ shell("mkdir -p '#{facts_d}'")
+ end
+ end
+ it 'generates random base64 strings' do
+ shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
+ pp = <<-eos
+ $l = 10
+ $o = fqdn_rand_base64($l)
+ notice(inline_template('fqdn_rand_base64 is <%= @o.inspect %>'))
+ eos
+
+ apply_manifest(pp, :catch_failures => true) do |r|
+ expect(r.stdout).to match(/fqdn_rand_base64 is "8ySYp0dq0B"/)
+ end
+ end
+ it 'generates random base64 strings with custom seeds' do
+ shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
+ pp = <<-eos
+ $l = 10
+ $s = 'seed'
+ $o = fqdn_rand_base64($l, $s)
+ notice(inline_template('fqdn_rand_base64 is <%= @o.inspect %>'))
+ eos
+
+ apply_manifest(pp, :catch_failures => true) do |r|
+ expect(r.stdout).to match(/fqdn_rand_base64 is "6J2c4oMRUJ"/)
+ end
+ end
+ end
+ describe 'failure' do
+ it 'handles improper argument counts'
+ it 'handles non-numbers for length argument'
+ end
+end
diff --git a/spec/acceptance/fqdn_rand_string_spec.rb b/spec/acceptance/fqdn_rand_string_spec.rb
new file mode 100644
index 0000000..a934fbb
--- /dev/null
+++ b/spec/acceptance/fqdn_rand_string_spec.rb
@@ -0,0 +1,60 @@
+#! /usr/bin/env ruby -S rspec
+require 'spec_helper_acceptance'
+
+describe 'fqdn_rand_string function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
+ describe 'success' do
+ let(:facts_d) do
+ if fact('is_pe', '--puppet') == "true"
+ if fact('osfamily') =~ /windows/i
+ if fact('kernelmajversion').to_f < 6.0
+ 'c:/documents and settings/all users/application data/puppetlabs/facter/facts.d'
+ else
+ 'c:/programdata/puppetlabs/facter/facts.d'
+ end
+ else
+ '/etc/puppetlabs/facter/facts.d'
+ end
+ else
+ '/etc/facter/facts.d'
+ end
+ end
+ after :each do
+ shell("if [ -f '#{facts_d}/fqdn.txt' ] ; then rm '#{facts_d}/fqdn.txt' ; fi")
+ end
+ before :each do
+ #no need to create on windows, pe creates by default
+ if fact('osfamily') !~ /windows/i
+ shell("mkdir -p '#{facts_d}'")
+ end
+ end
+ it 'generates random alphanumeric strings' do
+ shell("echo fqdn=fakehost.localdomain > '#{facts_d}/fqdn.txt'")
+ pp = <<-eos
+ $l = 10
+ $o = fqdn_rand_string($l)
+ notice(inline_template('fqdn_rand_string is <%= @o.inspect %>'))
+ eos
+
+ apply_manifest(pp, :catch_failures => true) do |r|
+ expect(r.stdout).to match(/fqdn_rand_string is "7oDp0KOr1b"/)
+ 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, $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
+ end
+ describe 'failure' do
+ it 'handles improper argument counts'
+ it 'handles non-numbers for length argument'
+ end
+end
diff --git a/spec/acceptance/pw_hash_spec.rb b/spec/acceptance/pw_hash_spec.rb
new file mode 100644
index 0000000..4768975
--- /dev/null
+++ b/spec/acceptance/pw_hash_spec.rb
@@ -0,0 +1,34 @@
+#! /usr/bin/env ruby -S rspec
+require 'spec_helper_acceptance'
+
+# Windows and OS X do not have useful implementations of crypt(3)
+describe 'pw_hash function', :unless => (UNSUPPORTED_PLATFORMS + ['windows', 'Darwin']).include?(fact('operatingsystem')) do
+ describe 'success' do
+ it 'hashes passwords' do
+ pp = <<-EOS
+ $o = pw_hash('password', 6, 'salt')
+ notice(inline_template('pw_hash is <%= @o.inspect %>'))
+ EOS
+
+ apply_manifest(pp, :catch_failures => true) do |r|
+ expect(r.stdout).to match(/pw_hash is "\$6\$salt\$IxDD3jeSOb5eB1CX5LBsqZFVkJdido3OUILO5Ifz5iwMuTS4XMS130MTSuDDl3aCI6WouIL9AjRbLCelDCy\.g\."/)
+ end
+ end
+
+ it 'returns nil if no password is provided' do
+ pp = <<-EOS
+ $o = pw_hash('', 6, 'salt')
+ notice(inline_template('pw_hash is <%= @o.inspect %>'))
+ EOS
+
+ apply_manifest(pp, :catch_failures => true) do |r|
+ expect(r.stdout).to match(/pw_hash is ""/)
+ end
+ end
+ end
+ describe 'failure' do
+ it 'handles less than three arguments'
+ it 'handles more than three arguments'
+ it 'handles non strings'
+ end
+end
diff --git a/spec/functions/fqdn_rand_string_spec.rb b/spec/functions/fqdn_rand_string_spec.rb
new file mode 100644
index 0000000..949d930
--- /dev/null
+++ b/spec/functions/fqdn_rand_string_spec.rb
@@ -0,0 +1,91 @@
+#! /usr/bin/env ruby -S rspec
+require 'spec_helper'
+
+describe "the fqdn_rand_string function" do
+ let(:scope) { PuppetlabsSpec::PuppetInternals.scope }
+
+ it "should exist" do
+ expect(Puppet::Parser::Functions.function("fqdn_rand_string")).to eq("function_fqdn_rand_string")
+ end
+
+ it "should raise an ArgumentError if there is less than 1 argument" do
+ expect { fqdn_rand_string() }.to( raise_error(ArgumentError, /wrong number of arguments/))
+ end
+
+ it "should raise an ArgumentError if argument 1 isn't a positive integer" do
+ expect { fqdn_rand_string(0) }.to( raise_error(ArgumentError, /first argument must be a positive integer/))
+ expect { fqdn_rand_string(-1) }.to( raise_error(ArgumentError, /first argument must be a positive integer/))
+ expect { fqdn_rand_string(0.5) }.to( raise_error(ArgumentError, /first argument must be a positive integer/))
+ end
+
+ it "provides a valid alphanumeric string when no character set is provided" do
+ length = 100
+ string = %r{\A[a-zA-Z0-9]{#{length}}\z}
+ expect(fqdn_rand_string(length).match(string)).not_to eq(nil)
+ end
+
+ it "provides a valid alphanumeric string when an undef character set is provided" do
+ length = 100
+ string = %r{\A[a-zA-Z0-9]{#{length}}\z}
+ expect(fqdn_rand_string(length, :charset => nil).match(string)).not_to eq(nil)
+ end
+
+ it "provides a valid alphanumeric string when an empty character set is provided" do
+ length = 100
+ string = %r{\A[a-zA-Z0-9]{#{length}}\z}
+ expect(fqdn_rand_string(length, :charset => '').match(string)).not_to eq(nil)
+ end
+
+ it "uses a provided character set" do
+ length = 100
+ charset = '!@#$%^&*()-_=+'
+ string = %r{\A[#{charset}]{#{length}}\z}
+ expect(fqdn_rand_string(length, :charset => charset).match(string)).not_to eq(nil)
+ end
+
+ it "provides a random string exactly as long as the given length" do
+ expect(fqdn_rand_string(10).size).to eql(10)
+ end
+
+ it "provides the same 'random' value on subsequent calls for the same host" do
+ expect(fqdn_rand_string(10)).to eql(fqdn_rand_string(10))
+ end
+
+ it "considers the same host and same extra arguments to have the same random sequence" do
+ first_random = fqdn_rand_string(10, :extra_identifier => [1, "same", "host"])
+ second_random = fqdn_rand_string(10, :extra_identifier => [1, "same", "host"])
+
+ expect(first_random).to eql(second_random)
+ end
+
+ it "allows extra arguments to control the random value on a single host" do
+ first_random = fqdn_rand_string(10, :extra_identifier => [1, "different", "host"])
+ second_different_random = fqdn_rand_string(10, :extra_identifier => [2, "different", "host"])
+
+ expect(first_random).not_to eql(second_different_random)
+ end
+
+ it "should return different strings for different hosts" do
+ val1 = fqdn_rand_string(10, :host => "first.host.com")
+ val2 = fqdn_rand_string(10, :host => "second.host.com")
+
+ expect(val1).not_to eql(val2)
+ end
+
+ def fqdn_rand_string(max, args = {})
+ host = args[:host] || '127.0.0.1'
+ charset = args[:charset]
+ extra = args[:extra_identifier] || []
+
+ scope = PuppetlabsSpec::PuppetInternals.scope
+ scope.stubs(:[]).with("::fqdn").returns(host)
+ scope.stubs(:lookupvar).with("::fqdn").returns(host)
+
+ function_args = [max]
+ if args.has_key?(:charset) or !extra.empty?
+ function_args << charset
+ end
+ function_args += extra
+ scope.function_fqdn_rand_string(function_args)
+ end
+end
diff --git a/spec/functions/pw_hash_spec.rb b/spec/functions/pw_hash_spec.rb
new file mode 100644
index 0000000..01a1105
--- /dev/null
+++ b/spec/functions/pw_hash_spec.rb
@@ -0,0 +1,87 @@
+#! /usr/bin/env ruby -S rspec
+require 'spec_helper'
+
+describe "the pw_hash function" do
+ let(:scope) { PuppetlabsSpec::PuppetInternals.scope }
+
+ it "should exist" do
+ expect(Puppet::Parser::Functions.function("pw_hash")).to eq("function_pw_hash")
+ end
+
+ it "should raise an ArgumentError if there are less than 3 arguments" do
+ expect { scope.function_pw_hash([]) }.to( raise_error(ArgumentError, /[Ww]rong number of arguments/) )
+ expect { scope.function_pw_hash(['password']) }.to( raise_error(ArgumentError, /[Ww]rong number of arguments/) )
+ expect { scope.function_pw_hash(['password', 'sha-512']) }.to( raise_error(ArgumentError, /[Ww]rong number of arguments/) )
+ end
+
+ it "should raise an ArgumentError if there are more than 3 arguments" do
+ expect { scope.function_pw_hash(['password', 'sha-512', 'salt', 5]) }.to( raise_error(ArgumentError, /[Ww]rong number of arguments/) )
+ end
+
+ it "should raise an ArgumentError if the first argument is not a string" do
+ expect { scope.function_pw_hash([['password'], 'sha-512', 'salt']) }.to( raise_error(ArgumentError, /first argument must be a string/) )
+ # in Puppet 3, numbers are passed as strings, so we can't test that
+ end
+
+ it "should return nil if the first argument is empty" do
+ expect(scope.function_pw_hash(['', 'sha-512', 'salt'])).to eq(nil)
+ end
+
+ it "should return nil if the first argument is undef" do
+ expect(scope.function_pw_hash([nil, 'sha-512', 'salt'])).to eq(nil)
+ end
+
+ it "should raise an ArgumentError if the second argument is an invalid hash type" do
+ expect { scope.function_pw_hash(['', 'invalid', 'salt']) }.to( raise_error(ArgumentError, /not a valid hash type/) )
+ end
+
+ it "should raise an ArgumentError if the second argument is not a string" do
+ expect { scope.function_pw_hash(['', [], 'salt']) }.to( raise_error(ArgumentError, /second argument must be a string/) )
+ end
+
+ it "should raise an ArgumentError if the third argument is not a string" do
+ expect { scope.function_pw_hash(['password', 'sha-512', ['salt']]) }.to( raise_error(ArgumentError, /third argument must be a string/) )
+ # in Puppet 3, numbers are passed as strings, so we can't test that
+ end
+
+ it "should raise an ArgumentError if the third argument is empty" do
+ expect { scope.function_pw_hash(['password', 'sha-512', '']) }.to( raise_error(ArgumentError, /third argument must not be empty/) )
+ end
+
+ it "should raise an ArgumentError if the third argument has invalid characters" do
+ expect { scope.function_pw_hash(['password', 'sha-512', '%']) }.to( raise_error(ArgumentError, /characters in salt must be in the set/) )
+ end
+
+ it "should fail on platforms with weak implementations of String#crypt" do
+ String.any_instance.expects(:crypt).with('$1$1').returns('$1SoNol0Ye6Xk')
+ expect { scope.function_pw_hash(['password', 'sha-512', 'salt']) }.to( raise_error(Puppet::ParseError, /system does not support enhanced salts/) )
+ end
+
+ it "should return a hashed password" do
+ result = scope.function_pw_hash(['password', 'sha-512', 'salt'])
+ expect(result).to eql('$6$salt$IxDD3jeSOb5eB1CX5LBsqZFVkJdido3OUILO5Ifz5iwMuTS4XMS130MTSuDDl3aCI6WouIL9AjRbLCelDCy.g.')
+ end
+
+ it "should use the specified salt" do
+ result = scope.function_pw_hash(['password', 'sha-512', 'salt'])
+ expect(result).to match('salt')
+ end
+
+ it "should use the specified hash type" do
+ resultmd5 = scope.function_pw_hash(['password', 'md5', 'salt'])
+ resultsha256 = scope.function_pw_hash(['password', 'sha-256', 'salt'])
+ resultsha512 = scope.function_pw_hash(['password', 'sha-512', 'salt'])
+
+ expect(resultmd5).to eql('$1$salt$qJH7.N4xYta3aEG/dfqo/0')
+ expect(resultsha256).to eql('$5$salt$Gcm6FsVtF/Qa77ZKD.iwsJlCVPY0XSMgLJL0Hnww/c1')
+ expect(resultsha512).to eql('$6$salt$IxDD3jeSOb5eB1CX5LBsqZFVkJdido3OUILO5Ifz5iwMuTS4XMS130MTSuDDl3aCI6WouIL9AjRbLCelDCy.g.')
+ end
+
+ it "should generate a valid hash" do
+ password_hash = scope.function_pw_hash(['password', 'sha-512', 'salt'])
+
+ hash_parts = password_hash.match(%r{\A\$(.*)\$([a-zA-Z0-9./]+)\$([a-zA-Z0-9./]+)\z})
+
+ expect(hash_parts).not_to eql(nil)
+ end
+end
diff --git a/spec/unit/puppet/provider/file_line/ruby_spec.rb b/spec/unit/puppet/provider/file_line/ruby_spec.rb
index d2a129c..a84fc78 100755
--- a/spec/unit/puppet/provider/file_line/ruby_spec.rb
+++ b/spec/unit/puppet/provider/file_line/ruby_spec.rb
@@ -46,12 +46,12 @@ describe provider_class do
@tmpfile = tmp.path
tmp.close!
@resource = Puppet::Type::File_line.new(
- {
- :name => 'foo',
- :path => @tmpfile,
- :line => 'foo = bar',
- :match => '^foo\s*=.*$',
- }
+ {
+ :name => 'foo',
+ :path => @tmpfile,
+ :line => 'foo = bar',
+ :match => '^foo\s*=.*$',
+ }
)
@provider = provider_class.new(@resource)
end
@@ -69,11 +69,11 @@ describe provider_class do
it 'should replace all lines that matches' do
@resource = Puppet::Type::File_line.new(
{
- :name => 'foo',
- :path => @tmpfile,
- :line => 'foo = bar',
- :match => '^foo\s*=.*$',
- :multiple => true
+ :name => 'foo',
+ :path => @tmpfile,
+ :line => 'foo = bar',
+ :match => '^foo\s*=.*$',
+ :multiple => true,
}
)
@provider = provider_class.new(@resource)
@@ -89,11 +89,11 @@ describe provider_class do
expect {
@resource = Puppet::Type::File_line.new(
{
- :name => 'foo',
- :path => @tmpfile,
- :line => 'foo = bar',
- :match => '^foo\s*=.*$',
- :multiple => 'asgadga'
+ :name => 'foo',
+ :path => @tmpfile,
+ :line => 'foo = bar',
+ :match => '^foo\s*=.*$',
+ :multiple => 'asgadga',
}
)
}.to raise_error(Puppet::Error, /Invalid value "asgadga"\. Valid values are true, false\./)
@@ -140,7 +140,54 @@ describe provider_class do
let :provider do
provider_class.new(resource)
end
-
+ context 'match and after set' do
+ shared_context 'resource_create' do
+ let(:match) { '^foo2$' }
+ let(:after) { '^foo1$' }
+ let(:resource) {
+ Puppet::Type::File_line.new(
+ {
+ :name => 'foo',
+ :path => @tmpfile,
+ :line => 'inserted = line',
+ :after => after,
+ :match => match,
+ }
+ )
+ }
+ end
+ before :each do
+ File.open(@tmpfile, 'w') do |fh|
+ fh.write("foo1\nfoo2\nfoo = baz")
+ end
+ end
+ describe 'inserts at match' do
+ include_context 'resource_create'
+ it {
+ provider.create
+ expect(File.read(@tmpfile).chomp).to eq("foo1\ninserted = line\nfoo = baz")
+ }
+ end
+ describe 'inserts a new line after when no match' do
+ include_context 'resource_create' do
+ let(:match) { '^nevergoingtomatch$' }
+ end
+ it {
+ provider.create
+ expect(File.read(@tmpfile).chomp).to eq("foo1\ninserted = line\nfoo2\nfoo = baz")
+ }
+ end
+ describe 'append to end of file if no match for both after and match' do
+ include_context 'resource_create' do
+ let(:match) { '^nevergoingtomatch$' }
+ let(:after) { '^stillneverafter' }
+ end
+ it {
+ provider.create
+ expect(File.read(@tmpfile).chomp).to eq("foo1\nfoo2\nfoo = baz\ninserted = line")
+ }
+ end
+ end
context 'with one line matching the after expression' do
before :each do
File.open(@tmpfile, 'w') do |fh|
@@ -194,7 +241,12 @@ describe provider_class do
@tmpfile = tmp.path
tmp.close!
@resource = Puppet::Type::File_line.new(
- {:name => 'foo', :path => @tmpfile, :line => 'foo', :ensure => 'absent' }
+ {
+ :name => 'foo',
+ :path => @tmpfile,
+ :line => 'foo',
+ :ensure => 'absent',
+ }
)
@provider = provider_class.new(@resource)
end