phpPhil
phpPhil

Reputation: 926

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.

Upvotes: 2

Views: 1129

Answers (3)

sekrett
sekrett

Reputation: 1275

You can do it the native way, it requires htpasswd to be installed:

execute 'set password' do
  sensitive true
  command "htpasswd -cb /etc/htpasswd.users #{user} #{password}"
  creates '/etc/htpasswd.users'
end

file '/etc/htpasswd.users' do
  owner 'www-data'
  group 'www-data'
  mode 0o600
end

Upvotes: 0

phpPhil
phpPhil

Reputation: 926

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

Upvotes: 2

Noah Gibbs
Noah Gibbs

Reputation: 775

The htpasswd man page looks like it uses MD5 hashing on the passwords.

Perhaps you can generate md5 hashes in your recipe's Ruby code?

Upvotes: 0

Related Questions