Setting a variable based on enviroment in chef

1k Views Asked by At

I am having trouble setting a variable on a template based on the result of node.chef_environment. Current when I run kitchen converge the chef run errors out on restarting the nrpe service because NRPE is complaining that allowed_hosts is blank. This is my first take at ever writing a cookbook so please excuse any ugly things that I have done.

if node.chef_environment == "development" || node.chef_environment == "qa" || node.chef_environment == "vagrant"
        node.default['allowed_hosts'] = "ipaddr"
elsif node.chef_environment == "staging" || node.chef_environment  == "production"
        node.default['allowed_hosts'] = "ipaddr2"
end

case
when platform_family?("debian")
    package "nagios-nrpe-server"
    package "nagios-plugins-basic"
when platform_family?("rhel")
    package "nagios-nrpe"
    package "nagios-plugins-nrpe"
    package "net-snmp-utils"
else
    Chef::Application.fatal! "[nagios-nrpe client] unsupported platform family: #{node[:platform_family]}"
end

template "/etc/nagios/nrpe.cfg" do
    source "nrpe.cfg.erb"
    owner "root"
    group "root"
    mode "0644"
    variables( 
        :allowed_hosts => node.default['allowed_hosts'] 
    )
end

bash "wget" do
    code <<-EOH
    cd /usr/lib/nagios/
    wget --no-check-certificate remote_source
    EOH
end

directory "/usr/lib/nagios/plugins" do
    action :delete
    recursive true
end

execute "untar plugins" do
    cwd "/usr/lib/nagios/"
    command "tar zxvf cc_sys_nrpe.tar.gz"
end

directory "/usr/lib/nagios/plugins" do
    mode "777"
    recursive true
end

file "/usr/lib/nagios/cc_sys_nrpe.tar.gz" do
    action :delete
end

service "nagios-nrpe-server" do
    supports :status => true, :restart => true, :reload => true
    action :restart
end
2

There are 2 best solutions below

0
On

To set your environment via test kitchen, add this to your .kitchen.yml:

provisioner:
  name: chef_solo
  solo_rb:
    environment: vagrant

or

provisioner:
  name: chef_zero
  client_rb:
    environment: vagrant

While you can set the environment name from recipe code, this will not fully apply the environment attributes or cookbook version constraints (though the latter is moot with solo).

0
On

So the problem ultimately was that test-kitchen is not configured to set node.chef_environment as "vagrant". I came this conclusion once I specifically set the node.chef_environment in the cookbook.