Search code examples
nginxopensslchef-infrakibana.htpasswd

How to create .htpasswd file for nginx using chef


I am new to chef and I am trying to generate a .htpasswd file to store user hash, I went through some links but this is not helping. I need ngnix to secure Kibana and I want to generate a password for users using openssl. I have created a template file as .htpasswd_temp.erb it looks like this:

<% @kibana_user.each do |user| %>
<%= user %>: 

<% end %>

and my recipe is:

kibana_configs = node['kibana']['kibana_auth']
template 'path/to/.htpasswd' do 
source '.htpasswd_temp.erb '
variables(
  kibana_user: kibana_configs['kiba_user']
)
end

I have created one role file where I have defined all default attributes(including kiba_user). Above code adds users to .htpasswd file but I have no idea how to generate password using openssl. Openssl command works fine using execute resource but execute resource does not work inside template resource, thus does not get reflected in .htpasswd file.I am really confused. Thank so much for your help ^^


Solution

  • the following recipe snippet might by handy for you...

    it assumes that you are familiar with encrypted data bag and that you have stored your credentials in a data bag named creds, with encrypted item named nginx that holds username and password keys.

    htpassed_file = '/root/.htpasswd'
    
    chef_gem 'htauth'
    
    ruby_block 'create .htpasswd' do
      block do
        require 'htauth'
        creds = data_bag_item('creds', 'nginx')
        HTAuth::PasswdFile.open(htpassed_file, HTAuth::File::CREATE) do |pf|
          pf.add(creds['username'], creds['password'])
        end
        FileUtils.chmod 0o600, htpassed_file
      end
    end