Reputation: 383
I just started to study chef. These days, I'm testing the sample of templates on -- https://docs.chef.io/resources/template/
But I failed all the times ... Here's my code --
default.rb
file '/srv/www/htdocs/index.html' do
content 'Hello World!'
end
include_recipe '::e'
e.rb
--default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin)
default['authorization']['sudo']['users'] = %w(jerry greg)
template '/tmp/test.txt' do
source 'test.txt.erb'
mode '0440'
owner 'root'
group 'root'
variables(
sudoers_groups: node['authorization']['sudo']['groups'],
sudoers_users: node['authorization']['sudo']['users']
)
end
test.txt.erb
Defaults !lecture,tty_tickets,!fqdn
root ALL=(ALL) ALL
<% @sudoers_users.each do |user| -%>
<%= user %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL
<% end -%>
%sysadmin ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL
<% @sudoers_groups.each do |group| -%>
<%= group %> ALL=(ALL) <%= "NOPASSWD:" if @passwordless %>ALL
<% end -%>
[2022-05-06T18:01:07+08:00] FATAL: NameError: undefined local variable or method `default' for cookbook: sample, recipe: e :Chef::Recipe
node['authorization']['sudo']['groups']
to pass parameters to sudoers_groups, I think the e.rb maybe should be this --node['authorization']['sudo']['groups'] = %w(sysadmin wheel admin)
node['authorization']['sudo']['users'] = %w(jerry greg)
template '/tmp/test.txt' do
source 'test.txt.erb'
mode '0440'
owner 'root'
group 'root'
variables(
sudoers_groups: node['authorization']['sudo']['groups'],
sudoers_users: node['authorization']['sudo']['users']
)
end
[2022-05-06T17:39:38+08:00] FATAL: NoMethodError: undefined method `[]' for nil:NilClass
I really messed up by this official sample. Please kind help me, Thanks in advance for any ideas.
Regards Eisen
Upvotes: 1
Views: 602
Reputation: 7340
There are many places where attributes can be defined. For the purpose of this answer, we'll limit it to the recipe, and the attributes file. There are different precedence rules for attributes.
Defining in cookbook's attributes file, such as sample/attributes/default.rb
with the default
precedence:
default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin)
default['authorization']['sudo']['users'] = %w(jerry greg)
Then the recipe sample/recipes/e.rb
and template test.txt.erb
could be used as you described in your question.
But when we define the attributes in recipe, we need to use the syntax node.<precedence>
, such as node.default
:
Defined in sample/recipes/e.rb
:
node.default['authorization']['sudo']['groups'] = %w(sysadmin wheel admin)
node.default['authorization']['sudo']['users'] = %w(jerry greg)
template '/tmp/test.txt' do
# and so on
Upvotes: 2