I am trying to use attributes in a chef template - ruby

I am having trouble trying to get information from a default attributes file into a template using Chef. Currently, I have this:
# attributes/default.rb
default['environment']['extrahosts'] = [ 'hostname1:address1', 'hostname2:address2' ]
#recipes/default.rb
extra_hosts = node[:environment][:extrahosts]
...
...
template '/blahblah' do
source 'blahblah.erb'
variables( :extra_hosts => extra_hosts )
end
#templates/blahblah.erb
<% for #item in #extra_hosts %>
- <%= #item %>
<% end %>
Although this doesn't work. What do I add to my template to yield:
- hostname1:address1
- hostname2:address2

The way you write a loop in Ruby is to use the each method and a block.
<% #extra_hosts.each do |item| %>
- <%= item %>
<% end %>
Also note that the loop variable doesn't have the at sign because it isn't an instance variable.

Related

Puppet ruby template with ip validation - skip failed values not error and stop

I have the following code in a Puppet (ruby) .erb template with a validate function on each value that is iterated over from an array. I want it to continue with next values and preferably issue a warning, or silently continue. The code below errors and stops if an entry fails validation.
For example if the array is $nameservers = ['1.1.1.1','/some.domain/2.2.2.2'] I want it to only process the 1.1.1.1 entry.
This is actually so I can use the same input array for either /etc/resolv.conf or /etc/dnsmask.conf as determined by other logic in my manifest that gets processed by one of 2 templates (no, I'm not crazy) :).
I know that validation can be done in the manifest or on top scope variables, however I have a need to do this in the template.
search <%= scope.lookupvar('dns_search') %>
<% scope.lookupvar('nameservers').each do |server| -%>
<% if scope.function_validate_ip_address([server]) -%>
nameserver <%= server -%>
<% end -%>
<% end -%>
Cheers
I managed to get it working with the following code. The only thing I can't get to add is a trailing newline after the LAST entry only. Any comments on how this block could be improved appreciated.
search <%= scope.lookupvar('dns_search') %>
<% scope.lookupvar('nameservers').each do |server| -%>
<% begin -%>
<% if scope.function_validate_ip_address([server]) %>
nameserver <%= server -%>
<% end -%>
<% rescue => e -%>
<% scope.call_function('warning',[e]) -%>
<% next %>
<% end -%>
<% end -%>

Only execute code in erb if variable exists?

Ruby newbie here who just started using Ruby with .erb templates and I'm having a problem with the code. I have a hangman game that's passing variables from the .rb file to the .erb file and everything was working fine until I tried to check it on initial load (no variables present) and it threw errors. So I figured I'd use defined? with an if statement to check if the variable exists and then execute the code if it does and ignore if doesn't. It works fine when I use:
<% if defined?bad_guesses %>
<%= bad_guesses %>
<% end %>
But the information I need is an array and when I try to use an .each or .times statement like this:
<% if defined?bad_guesses %>
<% bad_guesses.each do |i| %>
<%= i %>
<% end %>
<% end %>
I get:
NoMethodError at /
undefined method `each' for nil:NilClass
C:/Projects/hangman/views/index.erb in block in singleton class
<% bad_guesses.each do |i| %> hangman.rb in block in
erb :index, :locals => {:game_status => game_status, :bad_guesses => bad_guesses, :good_guesses => good_guesses, :word => word}
Any suggestions appreciated.
Also, is this even the proper way to do this? When you make an .erb template that uses variables passed in from a class in your .rb file, how do you ignore it until it exists to the template?
Passing variables using:
get '/' do
if params['make'] != nil
make = params['make'].to_i
game_status, bad_guesses, good_guesses, word = Hangman.get_word(make)
elsif params['guess'] != nil
guess = params['guess'].to_s
game_status, bad_guesses, good_guesses, word = Hangman.check_guess(guess)
end
erb :index, :locals => {:game_status => game_status, :bad_guesses => bad_guesses, :good_guesses => good_guesses, :word => word}
end
Looking at this:
<% if defined?bad_guesses %>
<% bad_guesses.each do |i| %>
<%= i %>
<% end %>
<% end %>
a few points:
defined?a is bad style; use defined?(bad_guesses) or defined? bad_guesses instead.
defined? checks if it's defined, so if you say foo = nil; defined? foo it will be true.
You could alternatively use this:
defined?(bad_guesses) && bad_guesses
On the other hand, undefined instance variables are nil by default:
# it shows undefined
defined? #non_existing_var
# but you can still check if it's truthy:
puts "found" if #non_existing_var
# it won't print anything
Similar to instance variables in this regard are hashes. The default value of an unknown key is nil.
The problem with instance variables is they are not scoped to the partial. Instead, I recommend sending your local variables as a nested hash:
locals: { data: { foo: "bar" } }
Then you can safely check for values which may not exist:
if data[:foo]
# this runs
elsif data[:non_existent]
# this doesnt run
end
For my purposes, the following syntax worked:
<% if some_var %>
<%= some_var %>
<% end %>
This block is rendered if some_var is not nil.

Use a variable name in an erb include call

I'm using Sinatra and I'd like to include another erb file in one of my views but using a variable for the file name.
I was thinking something like this may work but I get an error saying no such file could be found.
<%= erb :'layout/nav/#{device_type}' %>
Currently I'm using the below switch statement to achieve the desired results but the above would be cleaner and less code.
<% case device_type
when 'mobile'%>
<%= erb :'layout/nav/mobile' %>
<% when 'tablet' %>
<%= erb :'layout/nav/tablet' %>
<% else %>
<%= erb :'layout/nav/desktop' %>
<% end %>
Thanks
Giles
I think that could work, you just need to use double quotes to interpolate strings.
Try
<%= erb :"layout/nav/#{device_type}" %>

erb idiom to handle undefined variable

I'm trying to write some puppet .erb, I'd like to handle this "environment" variable if it's:
undefined
a string with newlines
an array.
I've got as far as this:
<% Array(environment).join("\n").split(%r{\n}).each do |f| %>
one line: <%= f %>
<% end %>
But haven't gotten around the undefined case yet. I've tried this
<% if (defined?(environment)).nil? %?
<% Array(environment).join("\n").split(%r{\n}).each do |f| %>
one line: <%= f %>
<% end %>
<% end %>
but am still getting "(erb):11: undefined local variable or method `environment' for main:Object (NameError)" when trying to test it like this:
ruby -rerb -e "environmentUNDEFINEME= [ 'cronvar=cronval', 'var2=val2' ];
puts ERB.new(File.read('templates/job.erb')).result"
Sorry this is so basic, but somebody's got to ask the easy questions. Any help?
I would do this:
<% if defined?(environment) %>
<% Array(environment).each do |f| %>
one line: <%= f %>
<% end %>
<% end %>
I didn't understand why you joining on new lines and then splitting on them again, so I removed it from the example.

reflection of erb variables

I'm using a puppet template, which does an erb interpretation of the template file. I'd like to know all the variables available to me, however, there are variables available (e.g., fqdn) that are not listed by any of the reflection methods I'm aware of, specifically, none of these:
<% Module.constants.each do |v| %># module constant: <%= v %>
<% end %>
<% Kernel.local_variables.each do |v| %># local variable: <%= v %>
<% end %>
<% Kernel.instance_variables.each do |v| %># instance variable: <%= v %>
<% end %>
<% Module.class_variables.each do |v| %># class variable: <%= v %>
<% end %>
<% Kernel.global_variables.each do |v| %># global variable: <%= v %>
<% end %>
Is there an extra reflection method for erb that will reveal these to me?
The "See all client variables" should do what you want
Don't really know about puppet templates, but if fqdn is a local variable, then calling local_variables (as in self.local_variables) should display it.
I don't know as much as I'd like to about erb's built-in means of reflection, but with Puppet, I think the hash returned by scope.to_hash is probably what you want. From the templating reference:
<% scope.to_hash.keys.each do |k| -%>
<%= k %>
<% end -%>
Alternately, if you just want a one-time look at the variables the agent node supplies, you can run facter on the node; that's how Puppet gets all that info in the first place.

Resources