Only_if multiple criteria?


#1

Hi All

I come from a PowerShell background and ruby/chef is completely new to me (hopefully we are getting some training soon)

I have my machines boostrapping and running cookbooks successfully but now want to put some criteria in.

I want the following to install ONLY if the machine name starts with PRD or DR

package ‘Microsoft Monitoring Agent’ do
source 'C:\chef\cache\cookbooks\install.scom.agent\files\default\momagent.msi’
installer_type :custom
options '/qn USE_SETTINGS_FROM_AD=0 ACTIONS_USE_COMPUTER_ACCOUNT=1 USE_MANUALLY_SPECIfIED_SETTINGS=1 MANAGEMENT_GROUP=PRD-OpsMgr MANAGEMENT_SERVER_DNS=bcp-xxxxxx.company.net AcceptEndUserLicenseAgreement=1’
end

I was thinking something like:

only_if {node[‘machinename’] == ‘PRD*’ }

What’s the correct way of writing?:

only_if {node[‘machinename’] == ‘DR*’ -or == ‘PRD*’ }

Thanks
Cam


#2

only_if { ruby_code }

So: only_if { criteria1 || criteria2 }

You can also use multiple guards statements. They all are checked:

only_if { criteria1 in ruby code }
only_if { criteria2 in ruby code }
only_if "some OS shell command"

You’re going to need to learn a little Ruby. For what you want specifically, the answer is:

only_if { node['machinename'] =~ /^DR/ || node['machinename'] =~ /^PRD/ }

See: https://docs.chef.io/resource_common.html#guards and https://ruby-doc.org/


#3

Great, thanks Jeff. I’ll give those a go and have a look at the ruby docs. I did some research but got a bit stumped at the operators.

I’m definitely up for learning Ruby. I’m just at the very beginning of that journey at the moment.

Thanks


#4

Hi Jeff,
executing grep command for a linux host, the $? value is equal to 1. Thus, using this command in the not_if condition I expect that the execute block is not executed, instead it tries to execute it, obviously failing. The code is:

execute ‘disable-base-repo’ do
command "zypper modifyrepo -d SLES11-SP4-Pool"
not_if { !(File.exist?(’/var/cache/SuseRegister/lastzmdconfig.cache’)) }
not_if "grep --quiet ‘No errors’ /var/cache/SuseRegister/lastzmdconfig.cache"
not_if { File.exist?(’/etc/sysconfig/rhn/systemid’) }
timeout 300
end

What do you suggest?

Regards


#5

Sorry, I only saw this now months later.

grep will exit with a process status code of 0 when a match has been found. grep will exit with a process status code 1 when a match was not found. These aren’t literal ‘0’ or ‘1’ of course.

If grep --quiet 'No errors' /var/cache/SuseRegister/lastzmdconfig.cache is returning a process status code of 1, then the string “No errors” was not found in the file and your code is doing what you told it to: execute the resource.