Search code examples
rubychef-infrachef-recipe.htpasswdchef-solo

Write users to .htpasswd in chef recipe


In a chef recipe invoked by chef-solo / vagrant I'm trying to write a .htpasswd file from an object of users. I specify the users in vagrantfile like this...

  chef.json = {
      :apache => {
          ...
          :my_users => {
              :john => "test",
              :matt => "test2"
          }
          ...

My chef recipe looks like this at the moment:

file "/etc/apache2/.htpasswd" do
  content "john:n5MfEoHOIQkKg"
  owner "#{node['apache']['user']}"
  group "#{node['apache']['group']}"
  mode '0644'
  action :create
end

As you can see I have hard coded John's credentials in there - however, I'm not a Ruby dev and I'm missing some very basic knowledge here...

How can I write all user credentials in the node['apache']['my_users'] attribute (defined in the chef.json) in a loop into the file while creating the password hash for each clear text password?

Note: I'm trying to avoid using a template for this simple file.


Solution

  • I got this working using the LWRP Charlie suggested.

    First step is to modify the definition of users to be a proper array:

    chef.json = {
        :apache => {
            ...
            :my_users => [ 
                { :username => "john", :password => "test1" },
                { :username => "matt", :password => "test2" }
            ]
            ...
    

    I include the htpasswd dependency to metadata and bershelf. Then in my recipe I create the users in a loop using the htpasswd call:

    node[:apache][:my_users].each do |user|
      htpasswd "/etc/apache2/.htpasswd" do
        user user['username']
        password user['password']
      end
    end