DEV Community

ZedTuX
ZedTuX

Posted on • Originally published at blog.zedroot.org

Stream command output from a Chef recipe

In this article I will show you how to see, in real-time, a command output from a Chef recipe.

Executing a command, the chef way

As a command example, as I'm working with it right now, let's take the Kubernetes installation tool: kubeadm.

This app tells you what he is doing in its output.

I first did this:

execute 'kubeadm init' do
command = <<-CMD
kubeadm init \
--token=#{node['kubeadm']['token']} \
--pod-network-cidr=#{node['kubeadm']['pod_cidr']} \
--service-cidr=#{node['kubeadm']['service_cidr']} \
--service-dns-domain=#{node['kubeadm']['dns_domain']} \
--apiserver-advertise-address=#{node['kubeadm']['api_ip_address']}
CMD
action :run
not_if "grep 'https://#{node['kubeadm']['api_ip_address']}' /etc/kubernetes/kubelet.conf"
end
view raw master.rb hosted with ❤ by GitHub

While this runs the command successfully, all the command's output is invisible:

* execute[kubeadm init] action run
           - execute     kubeadm init     --token=vfopfv.fgum14jkv3ldssu8     --pod-network-cidr=10.244.0.0/16     --service-cidr=10.96.0.0/12     --service-dns-domain=cluster.local     --apiserver-advertise-address=172.28.128.200

Enter fullscreen mode Exit fullscreen mode

Executing a command, the Ruby way

Let's now make this real-time :

require 'pty'
# Initialize master
ruby_block 'kubeadm init' do
block do
command = <<-CMD
kubeadm init \
--token=#{node['kubeadm']['token']} \
--pod-network-cidr=#{node['kubeadm']['pod_cidr']} \
--service-cidr=#{node['kubeadm']['service_cidr']} \
--service-dns-domain=#{node['kubeadm']['dns_domain']} \
--apiserver-advertise-address=#{node['kubeadm']['api_ip_address']}
CMD
PTY.spawn(command) do |stdout, _, _|
begin
loop { puts stdout.gets.gsub(/\r\n/, '').gsub(/\t/, ' ') }
rescue Errno::EIO
end
end
end
action :run
not_if "grep 'https://#{master_ip_address}' /etc/kubernetes/kubelet.conf"
end
view raw master.rb hosted with ❤ by GitHub

Now you get the command output in real time:

         * ruby_block[kubeadm init] action run[init] Using Kubernetes version: v1.15.1
       [preflight] Running pre-flight checks
       [preflight] Pulling images required for setting up a Kubernetes cluster
       [preflight] This might take a minute or two, depending on the speed of your internet connection
       ...
Enter fullscreen mode Exit fullscreen mode

🎉

Retry later

Top comments (0)

Retry later
Retry later