How can I loop through bash routine in Chef?

别说谁变了你拦得住时间么 提交于 2020-01-26 04:09:05

问题


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?


回答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.




回答2:


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



来源:https://stackoverflow.com/questions/40358877/how-can-i-loop-through-bash-routine-in-chef

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!