Write users to .htpasswd in chef recipe - ruby

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.

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

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?

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

Related

Chef template loop: can't convert Chef::Node::immutableMash into String

I've got a Vagrant setup in which I'm trying to use Chef-solo to generate an conf file which loops though defined variables to pass to the application. Everything is working except the loop and I'm not familiar enough with Ruby/Chef to spot the error.
I'm going to lay out the whole chain of events in case there is something along the way that is the problem, but the first portions of this process seem to work fine.
A config file is written in yaml and includes env variable definitions to be passed:
...
variables:
- DEBUG: 2
...
The config file is read in by the Vagrantfile into a ruby hash and used to create the Chef json nodes:
...
settings = YAML::load(File.read("config.yaml"))
# Provision The Virtual Machine Using Chef
config.vm.provision "chef_solo" do |chef|
chef.json = {
"mysql" => {"server_root_password" => "secret"},
"postgresql" => {"password" => {"postgres" => "secret"}},
"nginx" => {"pid" => "/run/nginx.pid"},
"php-fpm" => {"pid" => "/run/php5-fpm.pid"},
"databases" => settings["databases"] || [],
"sites" => settings["sites"] || [],
"variables" => settings["variables"] || []
}
...
A bunch of chef cookbooks are run (apt, php, nginx, mysql etc) and finally my custom cookbook which is whats giving me grief. The portion of the cookbook responsible for creating a the conf file is shown here:
# Configure All Of The Server Environment Variables
template "#{node['php-fpm']['pool_conf_dir']}/vars.conf" do
source "vars.erb"
owner "root"
group "root"
mode 0644
variables(
:vars => node['variables']
)
notifies :restart, "service[php-fpm]"
end
And the vars.erb is just a one-liner
<%= #vars.each {|key, value| puts "env[" + key + " = " + value } %>
So, when I run all this chef spits out an error about not being able to convert a hash to a string.
can't convert Chef::Node::immutableMash into String
So for some reason this is coming across as an immutableMash and the value of key ends up being the hash [{"DEBUG"=>2}] and value ends up a nil object, but I'm not sure why or how to correct it.
The hash is ending up as the value of key in your example because the YAML file declares DEBUG: 2 as a list member of variables. This translates to variables being an array with a single hash member.
Try changing the template code to this:
<%= #vars[0].each {|key, value| puts "env[" + key + " = " + value } %>
Or try changing the YAML to this and not changing the template code:
variables:
DEBUG: 2
Either change will get your template loop iterating over the hash that you are expecting.

Chef template and using it in a loop

How to write this in a loop.
I am very new to ruby so struggling with the approach.
I am trying to create a response file and then update the fixpack for IHS (IBM HTTP Server)
#Install the fix pack for IHS
template "/tmp/ihs-fixpack-response1.txt" do
source "ihs-fixpack-response.erb"
mode 0755
owner "root"
group "root"
variables({
:fixpack => "7.0.0-WS-IHS-LinuxX32-FP0000019.pak",
:product_path => node[:websphere][:ihs][:ihs_path]
})
end
# code for installing Fixpack
bash "ihs/was-updateinstaller" do
user "root"
code %(#{node[:websphere][:ihs][:ihs_updi_path]}/update.sh -options "/tmp/ihs-fixpack-response1.txt" -silent)
end
#Install the fix pack for the plugin.
template "/tmp/ihs-fixpack-response2.txt" do
source "ihs-fixpack-response.erb"
mode 0755
owner "root"
group "root"
variables({
:fixpack => "7.0.0-WS-PLG-LinuxX32-FP0000019.pak",
:product_path => node[:websphere][:ihs][:ihs_wasPluginPath]
})
end
# code for installing Fixpack
bash "ihs/was-updateinstaller" do
user "root"
code %(#{node[:websphere][:ihs][:ihs_updi_path]}/update.sh -options "/tmp/ihs-fixpack-response2.txt" -silent)
end
I believe this will do what you want:
[ [ "7.0.0-WS-IHS-LinuxX32-FP0000019.pak", node[:websphere][:ihs][:ihs_path] ],
[ "7.0.0-WS-PLG-LinuxX32-FP0000019.pak", node[:websphere][:ihs][:ihs_wasPluginPath] ]
].zip(1..2).each do |vars, i|
template "/tmp/ihs-fixpack-response#{i}.txt" do
source "ihs-fixpack-response.erb"
mode 0755
owner "root"
group "root"
variables({
:fixpack => vars.first,
:product_path => vars.last
})
end
bash "ihs/was-updateinstaller" do
user "root"
code %(#{node[:websphere][:ihs][:ihs_updi_path]}/update.sh -options "/tmp/ihs-fixpack-response#{i}.txt" -silent)
end
end

Chef Recipes - Setting node attributes in ruby_block

I have a Chef recipe for a multi-node web service, each node of which needs to get the hostname and IP of the other nodes, to put it into its own local configuration.
The code is shown below. The problem is that when the node.set[][] assignments are made in the ruby_block as shown, the values are empty when the template that relies upon them is created. If I want to create that template, I have to move all of the ruby_block code outside, and have it "loose" in the recipe. Which makes it harder to do unit-testing with Chefspec and the like.
Can any Chef guru set me straight? Is it just impossible to do node.set[] like this inside of a ruby_block? And if so, why doesn't it say so in the docs?
$cm = { :name => "web", :hostname => "" , :ip_addr => "" }
$ca = { :name => "data", :hostname => "" , :ip_addr => "" }
$cg = { :name => "gateway", :hostname => "" , :ip_addr => "" }
$component_list = [$cm, $ca, $cg]
ruby_block "get host addresses" do
block do
for cmpnt in $component_list
# do REST calls to external service to get cmpnt.hostname, ip_addr
# .......
node.set[cmpnt.name]['name'] = cmpnt.name
node.set[cmpnt.name]['host'] = cmpnt.hostname
node.set[cmpnt.name]['ip'] = cmpnt.ip_addr
end
end
end
template "/etc/app/configuration/config.xml" do
source "config.xml.erb"
variables( :dataHost => node['data']['host'],
:webHost => node['web']['host'],
:gatewayHost => node['gateway']['host'] )
action :create
end
I also added
subscribes :create, "ruby_block[get host addresses]", :immediately
to the template definition to ensure that the ruby_block ran before the template was created. This didn't make a difference.
I realize this is an old post, however for future reference, I just ran across this gist which gives a nice example of node variable assignments in the Compile vs. Converge phases. To adapt the gist to your example, you'll need to add code like the following to your ruby_block:
template_r = run_context.resource_collection.find(:template => "/etc/app/configuration/config.xml")
template_r.content node['data']['host']
template_r.content node['web']['host']
template_r.content node['gateway']['host']
For Chef 11, also see Lazy Attribute Evaluation.
The problem seems to be that attribute values inside your template resource definition get evaluated before actually invoking any resources.
I.e. the file is first executed as simple Ruby, compiling the resources, and only the the resource actions gets invoked. By that time, it is too late already.
I ran into the same problem when trying to encapsulate certain attribute manipulations into a resource. It simply does not work. Should anyone know a solution to this problem, I would appreciate it very much.
EDIT:
b = ruby_block...
...
end
b.run_action(:create)
Could possibly do the trick. It invokes the resource immediately.
The simplest answer to this is to not use chef attributes and not use ruby_block to do the work of talking to the REST API. The code can also be moved to a custom resource for better reuse:
unified_mode true
provides :my_resource
action :run do
cm = { :name => "web", :hostname => "" , :ip_addr => "" }
ca = { :name => "data", :hostname => "" , :ip_addr => "" }
cg = { :name => "gateway", :hostname => "" , :ip_addr => "" }
component_list = [cm, ca, cg]
hash = {}
for cmpnt in component_list
# do REST calls to external service to get cmpnt.hostname, ip_addr
# .......
hash[cmpnt.name] = {}
hash[cmpnt.name]['name'] = cmpnt.name
hash[cmpnt.name]['host'] = cmpnt.hostname
hash[cmpnt.name]['ip'] = cmpnt.ip_addr
end
template "/etc/app/configuration/config.xml" do
source "config.xml.erb"
variables( :dataHost => hash['data']['host'],
:webHost => hash['web']['host'],
:gatewayHost => hash['gateway']['host'] )
action :create
end
end
By using unified_mode and moving into a custom resource, it also makes it easier to use a node attribute without requiring the use of lazy {} or ruby_blocks. It also still allows chef configuration (like setting up resolv.conf or other network requirements before doing the REST calls) prior to calling this code while not having to think about compile/converge two pass issues in recipe context.
There is also no reason to use a resource like ruby_block to do pure ruby processing which does not change the system under management. In this case the ruby_block is hitting a REST service purely to collect data. That does not need to be placed into a Chef resource. It isn't clear from the question if that was being done because the questioner though it was a "best practice" (in this case it is not), or if it was being done to move execution to compile time in order to allow other chef resources that aren't part of the question to fire first (in which case using a custom resource is a much better solution than using a ruby_block).
It's been a while since this question, but in case someone is still looking for it, lazy evaluate is your friend:
template '/tmp/sql_file.sql' do
source "sql_file.sql.erb"
mode 0700
variables lazy {
# Create a new instance of MySQL library
mysql_lib = Acx::MySQL.new(
'127.0.0.1', 'root', node['mysql']['service']['pass']
)
password = node['mysql']['service']['support_admin']['ct_password']
# It returns the encrypted password after evaluate it, to
# be used in template variables
{ admin_password: mysql_lib.encrypted_password(password) }
}
end
https://docs.chef.io/resource_common.html#lazy-evaluation

Ruby parsing error

I have the following recipe for Chef:
def prestashop_deployDatabase (username)
sql_path = '/tmp/prestashop_create_tables.sql'
template sql_path do
source "prestashop152.sql.erb"
owner "root"
group node['mysql']['root_group']
mode "0600"
variables(
:username => #{username}
)
action :create
end
end
For some reason; it cannot understand the 'username' argument i'm passing.
PS: I'm a Ruby n00b.
#{username} is a comment in ruby. You should write "#{username}", or better in this case, just username.
In ruby:
# in code starts a one-line comment
#{} in a string starts interpolation - everything in the braces will be interpreted as ruby code.
Since you're using # in code here, it comments out the rest of the line {username}, so in effect your code says this:
variables(
:username =>
)
which will give you a syntax error.

How to check for user credentials using active directory and a ruby script

I'm trying write a Ruby script that checks if user credentials are valid using an active directory server. Here's what I've tried so far:
require 'rubygems'
require 'net-ldap'
host = '10.4.1.6'
port = 389
username = 'username'
password = 'password'
ldap = Net::LDAP.new
ldap.host = host
ldap.port = port
ldap.auth "CN=#{username},CN=Users,DC=companyname,DC=ad", password
if ldap.bind
puts 'YES!'
puts ldap.get_operation_result.message
else
puts 'NO :-('
puts ldap.get_operation_result.message
end
If I enter a non existing username and an empty string as a password, the bind operation succeeds. If I enter a valid username and a valid/invalid/empty password, the bind operation fails with error message 'Invalid Credentials'.
I've looked at other threads and read the net-ldap documentation but I can't figure out what I'm doing wrong.
Can someone give me some ideas on how to achieve this?
Thanks in advance for any replies :-)
Edit:
As #StuartEllis suggested, the problem was with the user identifier. To figure out the correct DN, I used the following script (taken from the net-ldap documentation):
ldap.auth "CN='adminUser',CN=Users,DC=companyname,DC=ad", 'adminUserPwd'
ldap.bind
treebase = "DC=companyname,DC=ad"
filter = Net::LDAP::Filter.eq( "mail", "username#companyname.com" )
attrs = ["mail", "cn", "sn","objectclass"]
ldap.search( :base => treebase, :filter => filter, :attributes => attrs, :return_result => false ) do |entry|
puts entry._dump 0
end
I then retried using my original script (above) with the obtained DN and voila!
I would guess that your LDAP account details aren't correct, but your LDAP server accepts anonymous binds, which is why it works when you don't specify a valid username and password. LDAP user identifiers are very fiddly, so I'd suggest double-checking the whole thing, including the case of the parts.
Here is sample code I use with the net-ldap gem to verify user logins from the ActiveDirectory server at my work:
def name_for_login( email, password )
email = email[/\A\w+/].downcase # Throw out the domain, if it was there
email << "#mycompany.com" # I only check people in my company
ldap = Net::LDAP.new(
host: 'ldap.mycompany.com', # Thankfully this is a standard name
auth: { method: :simple, email: email, password:password }
)
if ldap.bind
# Yay, the login credentials were valid!
# Get the user's full name and return it
ldap.search(
base: "OU=Users,OU=Accounts,DC=mycompany,DC=com",
filter: Net::LDAP::Filter.eq( "mail", email ),
attributes: %w[ displayName ],
return_result:true
).first.displayName.first
end
end

Resources