Chef Users resource (check if exists?)

2020-08-02 11:33发布

问题:

I know how to create a user resource:

user "random" do
  supports :manage_home => true
  comment "Random User"
  uid 1234
  gid "users"
  home "/home/random"
  shell "/bin/bash"
  password "$1$JJsvHslV$szsCjVEroftprNn4JHtDi."
end

But I'm unsure how to use Chef to find a list of all users on a current node. I looked at inspecting node[:users] during a chef-client run, but only node[:current_user] is available to me. Is there a way, in a Chef recipe, to ask if a regular user exists?

I'm in a situation where I shouldn't/can't create users (due to company regulations, but I definitely shouldn't proceed with the installation of other things defined in my cookbook unless xyz users already exist.)

回答1:

Ohai queries the users on the system for you:

if node['etc']['passwd']['random']
  # Do deploy
end


回答2:

That works only for local accounts, but if the accounts are managed by LDAP or AD the above does not hold. I would recommend using:

"getent group #{mygroup}" 
"getent passwd #{myuser}" 

in a ruby block.



回答3:

I was getting the same undefined method '[]' for nil:NilClass error message as Tom Klino. I suspect that those having trouble with coderanger's solution have disabled the passwd Ohai plugin.

It is very common for those of us with large directory environments to disable the passwd plugin in client.rb to avoid the 413 error ("Request Entity Too Large") when the client report runs. Check /etc/chef/client.rb for:

ohai.disabled_plugins [:Passwd]

With this plugin disabled, node['etc']['passwd'] is unavailable to your recipes, hence the error. In my environment, re-enabling the plugin fixes this error.



回答4:

This does not work, if accounts are not local:

if node['etc']['passwd']['random']
  # Do deploy
end

I've got "passwd: files sss" in my nsswitch.conf, as the accounts are in IPA. I guess only the solution from SorinS works.