Reputation: 1031
I'm trying to create a recipe which looks in my recipe's files dir and creates a user per public key in the directory.
cookbooks/users/files/default
dir contains:
id_rsa_123456789.pub
id_rsa_234567890.pub
Based on these two files I would like to create 2 user accounts named 123456789
and 234567890
and put their public key in /home/$USER/.ssh/ respectively.
cookbooks/users/attributes/default.rb
contains:
default['users']['pub_keys'] = {}
Dir.foreach('../files/default/') do |pub_key|
if pub_key =~ /\d.pub/
default['users']['pub_keys'][pub_key] = pub_key.match(/[0-9]{9}/)
end
end
This code should create the following:
default['users']['pub_keys'] = {'id_rsa_123456789.pub' => '123456789', 'id_rsa_234567890.pub' => '234567890' }
cookbooks/users/recipes/default.rb
contains:
node['users']['pub_keys'].each do |pub_key, sso|
user sso do
action :create
group 'sudoers'
home "/home/#{sso}"
end
directory "/home/#{sso}/.ssh" do
action :create
end
cookbook_file "/home/#{sso}/.ssh/#{pub_key}" do
source pub_key
owner sso
group sso
mode '0400'
action :create
end
end
I think my recipe is not able to read my hash var but I'm not sure why or how to fix.
Relevant File Content:
----------------------
/tmp/kitchen/cache/cookbooks/users/recipes/default.rb:
1: #
2: # Cookbook:: users
3: # Recipe:: default
4: #
5:
6:
7>> node['users']['pub_keys'].each do |pub_key, sso|
8: user sso do
9: action :create
10: group 'sudoers'
11: home "/home/#{sso}"
13: directory "/home/#{sso}/.ssh" do
14: action :create
15: end
16: cookbook_file "/home/#{sso}/.ssh/#{pub_key}" do
System Info:
------------
chef_version=14.11.21
platform=centos
platform_version=7.6.1810
ruby=ruby 2.5.3p105 (2018-10-18 revision 65156) [x86_64-linux]
program_name=/opt/chef/bin/chef-solo
executable=/opt/chef/bin/chef-solo
Running handlers:
[2019-03-11T19:28:18+00:00] ERROR: Running exception handlers
Running handlers complete
[2019-03-11T19:28:18+00:00] ERROR: Exception handlers complete
Chef Client failed. 0 resources updated in 00 seconds
[2019-03-11T19:28:18+00:00] FATAL: Stacktrace dumped to /tmp/kitchen/cache/chef-stacktrace.out
[2019-03-11T19:28:18+00:00] FATAL: Please provide the contents of the stacktrace.out file if you file a bug report
[2019-03-11T19:28:18+00:00] FATAL: NoMethodError: undefined method `[]' for nil:NilClass
Upvotes: 0
Views: 261
Reputation: 1426
Have you tried to set the attributes manually? I think the Ruby code starting with "Dir.foreach" doesn't work and is against the best practices of chef, anyway.
Upvotes: 1