diff --git a/README.md b/README.md index bd596a8bc..0023c2cc3 100644 --- a/README.md +++ b/README.md @@ -1997,6 +1997,20 @@ function in Puppet for the many available type conversions. *Type*: rvalue. +#### `os_version_gte` + +Checks to see if the OS version is at least a certain version. Note that only the major version is taken into account. + +Example usage: +``` + if os_version_gte('Debian', '9') { } + if os_version_gte('Ubuntu', '18.04') { } +``` + +Returns: + - Boolean(0) # When OS is below the given version. + - Boolean(1) # When OS is equal to or greater than the given version. + #### `parsejson` Converts a string of JSON into the correct Puppet structure (as a hash, array, string, integer, or a combination of such). diff --git a/lib/puppet/functions/os_version_gte.rb b/lib/puppet/functions/os_version_gte.rb new file mode 100644 index 000000000..e3089a858 --- /dev/null +++ b/lib/puppet/functions/os_version_gte.rb @@ -0,0 +1,20 @@ +# Checks if the OS version is at least a certain version. Note that only the +# major version is taken into account. +# +# Example usage: +# +# if os_version_gte('Debian', '9') { } +# if os_version_gte('Ubuntu', '18.04') { } +Puppet::Functions.create_function(:os_version_gte) do + dispatch :os_version_gte do + param 'String[1]', :os + param 'String[1]', :version + return_type 'Boolean' + end + + def os_version_gte(os, version) + facts = closure_scope['facts'] + (facts['operatingsystem'] == os && + Puppet::Util::Package.versioncmp(version, facts['operatingsystemmajrelease']) >= 0) + end +end diff --git a/spec/functions/os_version_gte_spec.rb b/spec/functions/os_version_gte_spec.rb new file mode 100644 index 000000000..4abfd7ef3 --- /dev/null +++ b/spec/functions/os_version_gte_spec.rb @@ -0,0 +1,33 @@ +require 'spec_helper' + +describe 'os_version_gte' do + context 'on Debian 9' do + let(:facts) do + { + :operatingsystem => 'Debian', + :operatingsystemmajrelease => '9', + } + end + + it { is_expected.to run.with_params('Debian', '9').and_return(true) } + it { is_expected.to run.with_params('Debian', '8').and_return(false) } + it { is_expected.to run.with_params('Debian', '8.0').and_return(false) } + it { is_expected.to run.with_params('Ubuntu', '16.04').and_return(false) } + it { is_expected.to run.with_params('Fedora', '29').and_return(false) } + end + + context 'on Ubuntu 16.04' do + let(:facts) do + { + :operatingsystem => 'Ubuntu', + :operatingsystemmajrelease => '16.04', + } + end + + it { is_expected.to run.with_params('Debian', '9').and_return(false) } + it { is_expected.to run.with_params('Ubuntu', '16').and_return(false) } + it { is_expected.to run.with_params('Ubuntu', '16.04').and_return(true) } + it { is_expected.to run.with_params('Ubuntu', '18.04').and_return(true) } + it { is_expected.to run.with_params('Fedora', '29').and_return(false) } + end +end