How can I loop through bash routine in Chef?
Asked Answered
D

2

-1

I have a bash script in Chef that fetches the time through NTP protocol from 3 instances running NTP server. The code at present is

if not node.run_list.roles.include?("ntp_server")
  bash "ntpdate" do
    code <<-EOH
    /usr/sbin/ntpdate -s 10.204.255.15 10.204.251.41 10.204.251.21
    EOH
  end
end

This has been working just fine. However, I am supposed to automate the task such as if one of the instances is replaced, there is no manual intervention required to update the IP in the code above.

To achieve that, I have been successfully able to fetch the instances running the ntp_server role.

ntp_servers = search(:node, 'role:ntp_server')

Having done that, I am unable to add those IP's to the bash subroutine in Chef shown above in the code.

Can someone let me know how am I supposed to achieve that?

Didi answered 1/11, 2016 at 11:9 Comment(0)
P
1
  1. You shouldn't use bash block and call ntpdate with each chef run. ntpd should take care of clock being in sync, Chef has cookbook for this.
  2. You could move IP addresses to the node and use join in code.

    ...
    code "/usr/sbin/ntpdate -s #{node["ntp_ipaddresses"].join(" ")}"
    ...
    
  3. Please, use ntp cookbook.

Portion answered 3/11, 2016 at 7:14 Comment(1)
Thank you @Portion for your inputs. Though I managed to solve (added as an answer below) what I intended to do, I am tempted to vote your input as an answer since it follows the best practices involved.Didi
D
0

I managed to solve what I had posted in the question. The way I did it was using a Template and then the bash script. The recipe code now looks

ntp_servers = search(:node, 'role:ntp_server')

if not node.run_list.roles.include?("ntp_server")
  template "/usr/local/bin/ntpdate.sh" do
    source "ntpdate.sh.erb"
    owner "root"
    group "root"
    mode 0644
    variables(
      :ntp_servers => ntp_servers
    )
  end

  bash "ntpdate" do
    user "root"
    code <<-EOH
      bash /usr/local/bin/ntpdate.sh
    EOH
  end
end

Having done this, I created a template in chef with the following configuration

#!/bin/bash
/usr/sbin/ntpdate -s <% @ntp_servers.each do |ntp_server| -%> <%= ntp_server['ipaddress'] %> <% end -%>

This way I could not dynamically add the ip addresses of the servers belonging to role ntp_server

Didi answered 4/11, 2016 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.