Search code examples
rubychef-infracookbook

How to provide attribute value in the template .erb file


How to provide attribute value in a template .erb file

qradar_logs/
├── Berksfile
├── LICENSE
├── README.md
├── attributes
│   └── default.rb
├── chefignore
├── files
│   └── default
│       └── default
├── metadata.rb
├── recipes
│   └── default.rb
├── spec
│   ├── spec_helper.rb
│   └── unit
│       └── recipes
│           └── default_spec.rb
├── templates
│   └── rsyslog.conf.erb
└── test
    └── integration
        └── default
           └── default_test.rb

11 directories, 12 files

In attribute.rb file, I have the following contents:

default['logs']['hostname'] = "169.67.89.72:514"

In my recipe, I provided the following:

hostname = node['logs']['hostname']

In my templates rsyslog.conf file, I would like to use this value based on the value changed in attributes file.

I tried giving:

<%= "#{hostname}" %>

It errors out as:

FATAL: Chef::Mixin::Template::TemplateError: undefined local variable or method `hostname'

How can I access the attributes defined in attribute file in template.erb file?

Thank you


Solution

  • So a few things. First you should use the variables property in your template resource to expose the data to the template:

    template '/whatever' do
      # ...
      variables hostname: node['logs']['hostname']
    end
    

    Then you need to use Erb formatting, which you kind of did but not really:

    <%= @hostname %>
    

    The variable name matches the key you used with variables.