Tampa
Tampa

Reputation: 78254

Chef templates and how to do a for loop in ruby

I am very new to ruby and chef. I am trying to create entries in an nginx.conf file based on the number of cores.

for i in <%= node["cpu"]["total"]%>
upstream frontends {
        server 127.0.0.1:805x;
    }

end

So..if 4 cores the file will look like this:

upstream frontends {
            server 127.0.0.1:8051;
            server 127.0.0.1:8052;
            server 127.0.0.1:8053;
            server 127.0.0.1:8054;
        }

Upvotes: 2

Views: 6938

Answers (3)

Tom Lime
Tom Lime

Reputation: 1204

Here is an example with if statement.

Cookbook:

template "/opt/auth/users.xml" do
 ...
 variables(
   :users => auth_users
 )
end

Template:

<% @users.each do |u| %>
  <user username="<%= u['username'] %>" password="<%= u['password'] %>" roles="<%= u['roles'] if u['roles'] %>" groups="<%= u['groups'] if u['groups'] %>" />
<% end %>

Upvotes: 0

yfeldblum
yfeldblum

Reputation: 65435

Recipe

template "/etc/nginx/sites-available/my-site.conf" do
  variables :frontends_count => node["cpu"]["total"]
end

Template

upstream frontends {
<% @frontends_count.times do |i| %>
  server 127.0.0.1:805<%= i + 1 %>;
<% end %>
}

Upvotes: 14

Michael Kohl
Michael Kohl

Reputation: 66837

I'm not familiar with Chef, since I'm a Puppet user. Generally I would tackle it like this though:

n.times { |i| puts "server 127.0.0.1:805#{i+1}" }

Output:

server 127.0.0.1:8051
server 127.0.0.1:8052
server 127.0.0.1:8053
server 127.0.0.1:8054

Obviously you have to replace n by node["cpu"]["total"] (I assume that's an integer) and use something other than puts, but that should get you started. I guess this should work in Chef:

upstream frontends {
<% node["cpu"]["total"].times do |i| -%>
  <%= "server 127.0.0.1:805#{i+1}" %>
<% end -%>
}

Upvotes: 3

Related Questions