Search code examples
rubychef-infrachef-recipe

check connection with chef


I need check connections with chef.

I am trying.

execute "check_sayc" do
command "$comprobacionPuerto='nc -zw3 server port && echo 'opened'
|| echo 'closed'|grep 'opened' if  [[ -z $comprobacionPuerto ]]
then Chef::Log.fatal 'connections refuse' else Chef::Log.info 'connections open' fi'"
end

but

Mixlib::ShellOut::ShellCommandFailed: execute[check_sayc]
(cb_prueba_frontal_deploy_databag::default line 7) had an error:    
Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received
'127'

What it's wrong?


Solution

  • You are mixing shell code and Ruby code in your execute to do things that can't work that way. Also, you have mixed up your quotes in the command.

    I'm not really sure if it makes sense to perform the action you try there with nc, but it's probably easier to use pure ruby:

    ruby_block "check sayc" do
      block do
        server = "www.google.com"
        port = 80
    
        begin
          Timeout.timeout(5) do
            Socket.tcp(server, port){}
          end
          Chef::Log.info 'connections open'
        rescue
          Chef::Log.fatal 'connections refused'
        end
      end
    end
    

    This should do about the same thing you try to achieve but avoids the order issues and the question how to transfer the output of your shellout back into ruby to handle in Chef.

    Edit: I wrapped the connection attempt into a timeout block. This might leak half-open sockets until they are garbage collected later. But I think this is safe in a Chef context.