Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Using opscode chef, is there a way to find or loop over all user accounts?

I need to create a configuration file in each users home directory. I do not want to loop over any directory structure for this.

share|improve this question
add comment

2 Answers 2

up vote 3 down vote accepted

All users on the system are automatically detected by ohai when Chef runs, and available in the node['etc'] attribute space. Users are node['etc']['passwd']. You can iterate over this like a hash. You can exclude "system" or "precreated by packages" by comparing whether a user's numeric ID is over whatever is defined in your systems /etc/login.defs UID_MIN.

Example usage in a recipe to create a config file that you have stored in the cookbook, a different file for each user.

node['etc']['passwd'].each do |user, data|
  if data['uid'].to_i > 1000

    cookbook_file "#{data['dir']}/custom_config" do
      source "#{user}_custom_config"
      owner user
      group data['gid']
      mode 0644
    end

  end
end

Replace "custom_config" with whatever your config file is named.

share|improve this answer
    
Foodcritic dictates you should put that conditional inside the cookbook_file declaration: cookbook_file ... do only_if { data['uid'] > 1000 } end –  sethvargo Jul 29 '12 at 17:53
    
@sethvargo I have issues with FC023, as reported here: github.com/acrmp/foodcritic/issues/51 –  jtimberman Jul 30 '12 at 17:41
    
Nice answer. I was trying to figure out if Chef can find the home/users directory, which is conveniently in that provided data['dir'] parameter. –  Patrick M Dec 13 '13 at 23:31
    
To clarify, I did this: home = node['etc']['passwd'][node['nodejs']['user']]['dir'], where my nodejs user is a user I wanted the home directory of. Worked like a charm (once I debugged the user creation resource, heh). –  Patrick M Dec 17 '13 at 3:44
add comment

It looks like ohai's etc.passwd support is based on Ruby Etc.passwd which reads the /etc/passwd file.

This could be fine if your users are defined statically like this. If your server has users defined in a remote system like LDAP or NIS then those users will not be in /etc/passwd. You can list them with

`getent passwd`
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.